[Solved] Can't make...
 
Notifications
Clear all

[Solved] Can't make a request using an 'user_id' as parameter on a Flask ApiRest

0 Posts
1 Users
0 Likes
1 Views
0
Topic starter
Elielton Limeira Asks: Can't make a request using an 'user_id' as parameter on a Flask ApiRest
I made this request getting all the data from all the users, and it's working just fine:

Code:
    @app.route('/account/bank-statement', methods=['GET'])
def get_bank_statement():
    try:
        bank_statement = TransferModel.query.all()
        transfer_schema = TransferSchema(many=True)
        bank_statement = transfer_schema.dump(bank_statement)
        array = np.asarray(bank_statement)
        list = array.tolist()
        return make_response(json.dumps(list), 200)
    except ValidationError as error:
        return make_response(error.messages, 422)

But when i try to get the same data from a specific user_id it returns an empty json:

Code:
@app.route('/account/bank-statement/<user_id>', methods=['GET'])
def get_bank_statement_id(user_id):
    try:
        bank_statement = TransferModel.query.get(user_id)
        transfer_schema = TransferSchema(many=True)
        bank_statement = transfer_schema.dump(bank_statement)
        array_result = np.asarray(bank_statement)
        list = array_result.tolist()
        return make_response(json.dumps(list), 200)
    except ValidationError as error:
        return make_response(error.messages, 422)

What i'm doing wrong?

this is the model for that:

Code:
class TransferModel(db.Model):
    __tablename__ = 'transfers'
    transfer_id = db.Column(db.Integer, autoincrement=True, primary_key=True)
    user_id = db.Column(db.String)
    friend_id = db.Column(db.String)
    value = db.Column(db.Integer)
    card_id = db.Column(db.String)
    date = db.Column(db.String(10))

    def __init__(self, user_id, friend_id, value, card_id, date):
        self.user_id = user_id
        self.friend_id = friend_id
        self.value = value
        self.card_id = card_id
        self.date = date

    def __repr__(self, ):
        return '' % self.user_id

    def remodel(friend_data):
        friend_data['card_id'] = friend_data['billing_card']['card_id']
        friend_data['value'] = friend_data['total_to_transfer']
        friend_data['date'] = date.today().strftime("%d/%m/%Y")
        del friend_data['billing_card']
        del friend_data['total_to_transfer']
        return friend_data

    def save_to_db(self, ):
        db.session.add(self)
        db.session.commit()

Ten-tools.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, Ten-tools.

 

 


 

Unreplied Posts

[Solved] What privileges are stripped from processes in docker container when user namespace remapping is enabled?

Rahul Asks: What privileges are stripped from processes in docker container when user namespace remapping is enabled?
I am trying to debug an application inside a docker container. The application is big and I don’t have access to the source code. The docker container entry point is a shell script that is started as root. The script starts the application as a non-root user using ‘su -l ‘. The application works properly in a normal docker installation but fails when docker has been configured to turn on user namespace remapping at system level. The exact OS error eludes me because the application doesn’t have good logging. I just see some functionality broken and am strongly suspecting there is some OS error causing this. I haven’t been able to figure out the cause by looking at the error messages in the logs. I now want to debug this from the docker side. Is there any difference in the privileges available to processes inside a docker container when user name space remapping is enabled ? If so, can I explicitly grant the privilege while creating the docker container ?

PS: I don’t think the application is trying to peek inside the /sys or /proc filesystems. But I am investigating that as well.

Ten-tools.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, Ten-tools.
 
 
 

[Solved] CustomComparator from Java into Swift

hasan kaleli Asks: CustomComparator from Java into Swift
I am trying to convert Java code into Swift. I have gone so far but stuck into the following conversion, I am wondering how to achieve that in Swift.

Code:
class CustomItem {
  var start: Int
  var end: Int
  
  init(start: Int, end: Int) {
    self.start = start
    self.end = end
  }
  
  static func compare_customs(_ content: [UInt8], _ custom1: CustomItem , _ custom2 : CustomItem) -> Int {
    // the logic is implemented here already!
  }
}

var content: [UInt8] = output.getBuffer()

var items = [CustomItem]()
for i in 0..<offsets.count - 1 {
  slices[i] = CustomItem(start: offsets[i], end: offsets[i + 1])
}
items[offsets.count - 1] = CustomItem(start: offsets[offsets.count - 1], end: output.size())

Trying to convert the following Java custom comparator logic into Swift. Any guidance would be appreaciated.

Code:
byte[] content = output.getBuffer();
java.util.Arrays.sort(items, new java.util.Comparator<CustomItem>() {
      @Override
      public int compare(CustomItem custom1, CustomItem custom2) {
        return CustomItem.compare_customs(content, custom1, custom2);
      }
    });

Ten-tools.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, Ten-tools.

 

 


 

[Solved] How do I write a minimal GraphQL query of the Axie server?

Pierre Abbat Asks: How do I write a minimal GraphQL query of the Axie server?
I’m writing a program to download data about Axies and process them. My plan is to download all the marketplace, getting just the index numbers, then download details about Axies. Before getting all the details about an Axie, I’d like to get just one detail. I’ve succeeded in making an HTTPS connection to the server and sending a query, but all it replies is “Bad Request”.

I’ve been using Shane Maglangit’s site Axie GraphQL Docs for examples, but the examples are too big for me to understand, since I don’t know GraphQL or JSON, and part of the queries has literal n and the other part has linefeeds, which is confusing me. His code is in JavaScript, which I don’t know, so I don’t know if JS is doing something different with n than C++ does.

Here’s my code: main.cpp

Code:
#include <iostream>
#include <iomanip>
#include <boost/program_options.hpp>
#include "http.h"
using namespace std;

int main(int argc,char **argv)
{
  string query="{n  "operationName": "GetAxieDetail",n"
  "  "variables":n  {n    "axieId": "5144540"n  },n"
  "  "query": "query GetAxieDetail($axieId: ID!) {\n  ...AxieDetail\n  __typename}n}"
  "fragment AxieDetail on Axie{axie(axieId: $axieId)}"";
  string response;
  string urlv2="https://axieinfinity.com/graphql-server-v2/graphql";
  string urlv1="https://graphql-gateway.axieinfinity.com/graphql";
  response=httpPost(urlv1,query);
  cout<<response<<endl;
  return 0;
}

http.h

Code:
#include <string>

std::string httpPost(std::string url,std::string data);

http.cpp

Code:
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/beast.hpp>
#include <boost/beast/ssl.hpp>
#include <boost/asio/ssl/error.hpp>
#include <boost/asio/ssl/stream.hpp>
#include <array>
#include <iostream>

namespace beast=boost::beast;
namespace http=beast::http;
namespace net=boost::asio;
namespace ssl=net::ssl;
using tcp=net::ip::tcp;
using namespace std;

array<string,4> parseUrl(string url)
// protocol, hostname, port, path. All are strings, including the port.
{
  size_t pos0=url.find("://");
  size_t pos1;
  array<string,4> ret;
  ret[0]=url.substr(0,pos0);
  if (pos0<url.length())
    pos0+=3;
  pos1=url.find("/",pos0);
  ret[1]=url.substr(pos0,pos1-pos0);
  ret[3]=url.substr(pos1);
  pos0=ret[1].find(":");
  if (pos0<ret[1].length())
  {
    ret[2]=ret[1].substr(pos0+1);
    ret[1]=ret[1].substr(0,pos0);
  }
  else
    if (ret[0]=="https")
      ret[2]="443";
    else if (ret[0]=="https")
      ret[2]="80";
    else
      ret[2]="0";
  return ret;
}

string httpPost(string url,string data)
{
  net::io_context context;
  ssl::context ctx(ssl::context::tlsv12_client);
  tcp::resolver res(context);
  tcp::resolver::results_type endpoints;
  beast::ssl_stream<beast::tcp_stream> stream(context,ctx);
  array<string,4> parsed=parseUrl(url);
  http::request<http::string_body> req;
  http::response<http::string_body> resp;
  beast::flat_buffer buffer;
  //load_root_certificates(ctx);
  ctx.set_verify_mode(ssl::verify_peer);
  endpoints=res.resolve(parsed[1],parsed[2]);
  beast::get_lowest_layer(stream).connect(endpoints);
  SSL_set_tlsext_host_name(stream.native_handle(),parsed[1].c_str());
  if (parsed[0]=="https")
    stream.handshake(net::ssl::stream_base::client);
  req.method(http::verb::post);
  req.target(parsed[3]);
  req.set(http::field::host,parsed[1]);
  req.set(http::field::user_agent,BOOST_BEAST_VERSION_STRING);
  req.set(http::field::content_type,"application/json");
  req.set(http::field::accept,"application/json");
  req.body()=data;
  req.prepare_payload();
  http::write(stream,req);
  http::read(stream,buffer,resp);
  cout<<parsed[0]<<"|n"<<parsed[1]<<"|n"<<parsed[2]<<"|n"<<parsed[3]<<"|n";
  cout<<data<<"|n";
  return resp.body();
}

How can I write a query that returns one detail of the Axie with the specified number? Which of the two Axie servers should I use, and what’s the difference?

Ten-tools.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, Ten-tools.

 

 


 

[Solved] parsing url and obtaining the same when the url the pasted

manu p Asks: parsing url and obtaining the same when the url the pasted
I am able to parse the url when the specific row on the table is created. Here 2 things are happening, one is a new tab is created and then the url is getting changed according.

For example, when clicked on row 3, tab 3 is opened and url is changing to “http://127.0.0.1:4692/?tab=3

But when the above is copied and pasted in another tab, the same is not obtained. Instead a default shiny application is opened. Is there a way to get the same page when that url is pasted in another tab?

Code:
library(shiny)
library(readxl)
library(dplyr)
library(xtable)
library(shinyWidgets) ## for picker input
library(shinydashboard) 
library(DT)
library(tidyverse)
library(shinycssloaders)
library(plotly)
library(htmlwidgets)
library(sparkline)
library(data.table)
require(reshape2)
library(glue)


ui <- shinyUI(navbarPage(

  "PaperCut",id = "inTabset",selected = "Summary",
  tabsetPanel(id = "tabs",
          #     tabPanel(
          # "Read me",tags$head(tags$link(rel = "stylesheet", type="text/css", href="style.css"))
          #              ),
              tabPanel(
          "Summary",
    DT::dataTableOutput("tab")))
)
)

server <- function(input, output, session) {

  output$tab <- DT::renderDataTable({
    datatable(iris,selection = 'single')
  })
  
  observeEvent(input$tab_rows_selected, {
    print(input$tab_rows_selected)
  })
 
  
  observeEvent(input$tab_rows_selected, {
    insertTab(inputId = "tabs",
              tabPanel(paste0("tab",input$tab_rows_selected), paste0(input$tab_rows_selected,
                                                                     "This a dynamically-added tab")),select = TRUE
                
    )
  })
  
  observeEvent(input$tab_rows_selected, {
    updateQueryString(
      queryString = sprintf("?tab=%s", input$tab_rows_selected),
      mode = c("replace")
    )
  })
  
}

shinyApp(ui, server)

Ten-tools.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, Ten-tools.

 

 


 

[Solved] Transfer web UI to mobile UI?

StarckOverflar Asks: Transfer web UI to mobile UI?
If I built a frontend design for a website, how can I automatically import that design to a mobile app? Doing it by hand takes time, and the UI also wouldn’t exactly look the same.

How do companies make their mobile app look the same as their website?

Ten-tools.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, Ten-tools.

 

 


 

[Solved] What’s Wrong in this Python Script

Mentally Strong Asks: What’s Wrong in this Python Script
I Think there is a errorin this code there is no synthax error but still my program is not running and only a single line is executed code here:

Code:
import os
import random
print("This is Guessing The Number Game")
rand=random.randint(0,100)
def start():
    guess=int(input("Enter Your Number : "))
    os.system('cls')
    if (guess!=rand):
        if (guess>rand):
            print("You Need To Guess Lower")
            start()
        if (guess<rand):
            print("You Need to Guess Higher")
            start()
    if (guess==rand):
        print("You Guessed Correct Number")
        print("Your Number Is",inp)
        os.system('cls')
        ans=input("Would You Like to play Again (Y/N) : ")
        if ans==Y:
            start()
        else:
            exit

Ten-tools.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, Ten-tools.

 

 


 

[Solved] Property ‘properties’ does not exist on type defined with t.PartialC in react

George Asks: Property ‘properties’ does not exist on type defined with t.PartialC<{}> in react
my object is defined like below and I’m trying to map the object in react but since it is a partialC I’m running into error saying that it doesn’t exist.

Code:
                type: t.Type<import("./runtime").ERC721TokenType, import("./runtime").ERC721TokenType, unknown>;
                data: t.IntersectionC<[t.TypeC<{
                    id: import("io-ts-types").NonEmptyStringC;
                    token_address: t.BrandC<t.StringC, import("./runtime").EthAddressBrand>;
                    quantity: t.BrandC<t.Type<import("@ethersproject/bignumber").BigNumber, import("@ethersproject/bignumber").BigNumber, unknown>, import("./runtime").PositiveBigNumberBrand>;
                }>, t.PartialC<{
                    properties: t.TypeC<{
                        name: t.UnionC<[t.NullC, t.StringC]>;
                        image_url: t.UnionC<[t.NullC, t.StringC]>;
                        collection: t.TypeC<{
                            name: t.StringC;
                            icon_url: t.UnionC<[t.NullC, t.StringC]>;
                        }>;
                    }>;
                }>]>;

    {marketplace.result
    ? marketplace.result.map(item => {
        return(
          <div className="card">
        <img className="card-image" src={item.sell.data.properties.image_url} />
        </div>
        );
      })
    : "Loading..."}

Ten-tools.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, Ten-tools.

 

 


 

[Solved] Using Imagemagick to convert TIFF to PDF

Laurent Richer Asks: Using Imagemagick to convert TIFF to PDF
How can I convert JPG into PDF easily? shows how to use homebrew to install imagemagick and then convert .jpg files into .pdf. I would like to convert many TIFF files to PDF, keeping the same name and changing only the extension.

For JPEG files, the advice was to use the following command:

  1. brew install imagemagick
  2. convert *.jpg output.pdf

I am trying to use the Step 2 command for *.TIFF files into *.PDF.

However, despite using the command line to the letter, I am unable to change my 300 files with this single line. In fact, no file is converted at all.

Would anyone be so kind to provide a helping hand ?

Ten-tools.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, Ten-tools.

 

 


 

[Solved] Care and feeding of the 1st gen Apple Pencil and its battery

swineone Asks: Care and feeding of the 1st gen Apple Pencil and its battery

Background​

I own an iPad Pro 10.5″ and a first-generation Apple Pencil for it.

The Pencil was bought in March 2018. In January 2019, i.e. about 9.5 months later, it had a battery failure and had to be replaced under warranty by Apple. This is not an isolated issue. I’m not looking forward to another failure in less than a year again, except it’ll be out of warranty this time, so I’ll have to pay out of pocket for a repair next time.

It’s well known that batteries are consumables, and it’s not expected that they’ll last forever. On the other hand, to see Pencils failing (such as my own) before the warranty expires suggests that there is a design flaw in the Pencil.

Side note, feel free to skip​

As an electrical engineer with experience designing battery-powered devices, I have a theory regarding this design flaw:

  1. The Pencil’s battery is very small (0.332 Wh, or about 90 mAh).
  2. Point 1 by itself is not a problem, except the Pencil is an always-on device. Its internal accelerometer senses when it’s moved, and it pairs to the iPad. If, like me, you throw the iPad and the Pencil in a backpack which you take around with you all day, it’s going to be waking up quite often, and draining the battery in the process. I don’t care what Jony Ive says, it really needed an on-off switch.
  3. When a Li-Ion battery is drained beyond a certain threshold, it isn’t safe to try to recharge it. Most battery protection ICs include undervoltage protection and turn off the charge MOSFET in series with the battery when this condition is detected.
  4. When the Pencil reaches a low battery state (say at 5%), I assume it enters a very low power mode, disconnecting from the iPad, to save battery (if it doesn’t, and the user doesn’t immediately start recharging the battery, it will be irrecoverably dead in a few hours as per point 3).
  5. However, even in a low power mode, there is some current drain from the battery — unless you use a relay to cut power to the circuit, which Apple certainly didn’t use in the Pencil. A good design might have a leakage current budget of about 10 µA. Unfortunately, going back to point 1, and considering that 5% of 90 mAh is 4.5 mAh (assuming it still holds 90 mAh of charge; over time it will be less, so adjust the figures downward correspondingly), a 10 µA drain would completely drain the battery after 450 hours, or about 19 days (less than 3 weeks).

As a consequence of point 5, if you leave your iPad unattended for a few weeks, you may come back to a dead Pencil. Apple realized this, which is why they made it easier to dock the 2nd generation Pencil to the iPad Pro, which keeps it permanently charged.

Another, completely unrelated issue, but which may also play a part: Apple implemented a fast charging protocol, since it only takes about 15-20 minutes to fully charge the Pencil starting from a discharged state, which suggests a C-rate of about 3C to 4C. This paper shows noticeably reduced battery cycle life at 1.2C and 1.4C compared to 1C, so extrapolating to 3C or 4C rates, I’m frankly surprised the battery lasts more than a few dozen cycles.

It is my theory that these two issues are responsible for most battery-related Apple Pencil failures.

The questions​

All signs point to the Apple Pencil requiring constant attention to avoid killing the battery. On the other hand, I haven’t found any reports of newly-bought Pencils being dead, so clearly they can stay on store shelves for weeks, possibly months, without the battery dying (although it surely helps that they’re sitting still on the shelf before being sold).

What measures can I take to ensure the maximum battery longevity of a Pencil?

In particular, can I revert the Pencil to a factory reset state, in which the battery drain is very low?

Can I “slow”-charge the Pencil (say at 1C rate, therefore not slow at all) so as to prevent the hypothesized deterioration of the battery due to the default fast charge protocol?

Are there apps to remind me to do this if I leave the Pencil paired for more than a few minutes without using it?

Note: I will leave an answer describing the measures I took to try to prolong the lifetime of my current Pencil, although clearly they weren’t enough, seeing as it died after 9.5 months. I’m looking for other measures to take to make sure the replacement lasts longer.

Ten-tools.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, Ten-tools.

 

 


 

[Solved] How to show open tabs on other devices on Mac Safari?

Blaszard Asks: How to show open tabs on other devices on Mac Safari?
I want to show open tabs on other devices that share the same Apple and iCloud account, but for some reasons there is no open tab on Mac Safari when I click the top-right icon (the icon of two tabs overriding).

On my iPhone and iPad I can access the tabs opened on my Mac, but the other direction is not true. How can I open the tabs opened on iOS devices on Mac or maybe is it just a bug?


UPDATE​

I found out that sometimes the tabs appear properly whereas other times they don’t.

UPDATE 2​

This might be a bug, but I think 60~80% of the time the tabs don’t appear. I upgraded to macOS 11.1 but the problem still persists. Any workaround would be appreciated.

Ten-tools.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, Ten-tools.

 

 


 

Share: