Monday, May 16, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


parameterized C++ nested struct array initialization

Posted: 16 May 2022 10:21 AM PDT

I've checked posts here that I can use template for nested struct. But when I'm trying to initialize an array inside a nested struct, there seems problem during initialization. In the following example, the array size is one of the parameters of the nested struct so Visual Studio complained that the array size is illegal. Here is the definition:

template<typename U, typename T>  struct A {      struct B {          struct C {              vector<U> count[T];    // count needs to have variable size               C() {                          count = new U[T];  // allocate size. Not work              }          C c;      };      B b;  };  

Did I do anything wrong when using the template and initialize the array?

Thanks

Flutter : Search modal animations like Booking.com app

Posted: 16 May 2022 10:21 AM PDT

I use Flutter.

I wish to have the same behaviors / transitions as app search "bookin.com".

Use case :

  • Make a first search on "bookin.com" application with a device. And then the result of the search appears
  • Click on the search in the resutl page and the topsheet resizes as well as the content (form) together.

Thank you in advance for your help :)

I work from this example code from @Hamed that works :

    import 'package:flutter/material.dart';    class SampleWidget extends StatefulWidget {    const SampleWidget({Key? key}) : super(key: key);      @override    State<SampleWidget> createState() => _SampleWidgetState();  }    class _SampleWidgetState extends State<SampleWidget>      with TickerProviderStateMixin {    late TabController _tabController;    bool _isFilterEnabled = false;      @override    void initState() {      _tabController = new TabController(length: 3, vsync: this, initialIndex: 0);      super.initState();    }      TabBar getTabBar() {      return TabBar(        indicatorColor: Colors.white,        controller: _tabController,        tabs: [          Container(            padding: EdgeInsets.only(top: 20),            height: 65,            child: Tab(              child: Row(                mainAxisAlignment: MainAxisAlignment.spaceEvenly,                children: const [                  Icon(                    Icons.import_export,                    color: Colors.grey,                  ),                  Text(                    "Trier",                    style: TextStyle(                      color: Colors.grey,                    ),                  ),                ],              ),            ),          ),          Container(            padding: const EdgeInsets.only(top: 20),            height: 50,            child: Tab(              child: Row(                mainAxisAlignment: MainAxisAlignment.spaceEvenly,                children: const [                  Icon(                    Icons.tune,                    color: Colors.grey,                  ),                  Text(                    "Filter",                    style: TextStyle(                      color: Colors.grey,                    ),                  ),                ],              ),            ),          ),          Container(            padding: const EdgeInsets.only(top: 20),            height: 50,            child: Tab(              child: Row(                mainAxisAlignment: MainAxisAlignment.spaceEvenly,                children: const [                  Icon(                    Icons.map,                    color: Colors.grey,                  ),                  Text(                    "Carte",                    style: TextStyle(                      color: Colors.grey,                    ),                  ),                ],              ),            ),          ),        ],      );    }      @override    Widget build(BuildContext context) {      return Stack(        children: [          Scaffold(            appBar: AppBar(              automaticallyImplyLeading: false,              backgroundColor: const Color(0xFF013580),              bottom: PreferredSize(                preferredSize: getTabBar().preferredSize,                child: ColoredBox(                  color: Colors.white,                  child: getTabBar(),                ),              ),            ),            body: TabBarView(              controller: _tabController,              children: [                ListView.builder(                  itemBuilder: (index, context) => const ListTile(                    leading: Icon(Icons.abc),                  ),                  itemCount: 20,                ),                ListView.builder(                  itemBuilder: (index, context) => const ListTile(                    leading: Icon(Icons.access_alarm),                  ),                  itemCount: 20,                ),                ListView.builder(                  itemBuilder: (index, context) => const ListTile(                    leading: Icon(Icons.ac_unit),                  ),                  itemCount: 20,                )              ],            ),          ),          Material(            color: Colors.transparent,            child: InkWell(              splashColor: Colors.transparent,              onTap: () {                print("container is pressed");                setState(() {                  _isFilterEnabled = !_isFilterEnabled;                });              },              child: Container(                height: 60,                child: Row(                  children: const [                    Icon(                      Icons.chevron_left,                      color: Colors.grey,                    ),                    SizedBox(width: 20),                    Text(                      "Sample Text text",                      style: TextStyle(                        color: Colors.grey,                        fontSize: 18,                        decoration: TextDecoration.none,                      ),                    )                  ],                ),                margin: const EdgeInsets.only(                    left: 20, right: 20, bottom: 20, top: 5),                decoration: BoxDecoration(                  color: Colors.white,                  borderRadius: BorderRadius.circular(5),                  border: Border.all(color: Colors.amber, width: 4),                ),              ),            ),          ),          if (_isFilterEnabled)            Material(              elevation: 5,              color: Colors.transparent,              child: Container(                color: Colors.white,                child: Column(                  mainAxisSize: MainAxisSize.min,                  children: [                    const SizedBox(height: 10),                    Row(                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,                      children: [                        InkWell(                          onTap: () {                            setState(() {                              _isFilterEnabled = !_isFilterEnabled;                            });                          },                          child: Icon(                            Icons.close,                          ),                        ),                        Text(                          "Modifiez Votre recherche",                          style: TextStyle(                              color: Colors.black,                              fontSize: 20,                              decoration: TextDecoration.none,                              fontWeight: FontWeight.w600),                        )                      ],                    ),                    const SizedBox(height: 10),                    Container(                      margin: EdgeInsets.all(10),                      decoration: BoxDecoration(                        color: Colors.white,                        borderRadius: BorderRadius.circular(5),                        border: Border.all(color: Colors.amber, width: 4),                      ),                      child: Column(                        children: [                          Container(                            padding: const EdgeInsets.only(                              top: 8,                              bottom: 5,                            ),                            child: Row(                              children: const [                                SizedBox(width: 10),                                Icon(Icons.search),                                SizedBox(width: 10),                                Text("France")                              ],                            ),                          ),                          const Divider(color: Colors.black38),                          Container(                            padding: const EdgeInsets.only(                              top: 8,                              bottom: 5,                            ),                            child: Row(                              children: const [                                SizedBox(width: 10),                                Icon(Icons.search),                                SizedBox(width: 10),                                Text("France")                              ],                            ),                          ),                          const Divider(color: Colors.black38),                          Container(                            padding: const EdgeInsets.only(                              top: 8,                              bottom: 8,                            ),                            child: Row(                              children: const [                                SizedBox(width: 10),                                Icon(Icons.search),                                SizedBox(width: 10),                                Text("France")                              ],                            ),                          ),                          Container(                            color: Color(0xFF0171c2),                            height: 50,                            width: double.infinity,                            child: const Center(                              child: Text(                                " Recharge",                                style: TextStyle(                                  color: Colors.white,                                  fontSize: 18,                                  fontWeight: FontWeight.bold,                                ),                              ),                            ),                          )                        ],                      ),                    ),                    const SizedBox(height: 10),                  ],                ),              ),            )        ],      );    }  }  

Shade of colour detection

Posted: 16 May 2022 10:21 AM PDT

I'm working on shade of colour detection. I have this kind of images :

Picture 1 Picture 2

First I don't want to take holes in account. In these two examples we can see that there is two shades of colour in the picture. Firstly I want that ImageJ detect the two shades and then I want to have the occupied area by the two differents shades. If we manually make the macros for these 2 pictures it will work for my whole sample. I tried to make the macro but i lost myself in too many options.

Then as you can see the shade aren't the same on the two pictures. But the difference is on the center every time. So the next step will be to analyze the colour of some points in and out of the center and make decision :

If the points in and out have the same colour don't analyze. if the points in and out doesn't have the same colour, I analyze with the good macro. For example if I make 2 macros for the two differents example picture ImageJ could choose the good one. First we can focus on the shape detection for one of the picture.

( Sorry for my English )

Have a nice day,

DG

Pandas SettingWithCopyWarning with np.where

Posted: 16 May 2022 10:20 AM PDT

I have a pandas data frame that has a column containing a bunch of correlations (all float values). I'm trying to create another column to categorise these correlations into three distinct categories (high/medium/low). I do this using np.where:

df['Category'] = np.where(df['Correlation'] >= 0.5, 'high',                                      np.where(data['Correlation'] >= 0.3, 'medium','low'))  

When I try doing this, I always get the SettingWithCopyWarning (it seems to work though). I have read up on the difference between copies and views, and even seen recommendations to use .where over other methods to avoid any confusion (and the SettingWithCopyWarning). I still can't quite wrap my head around why I get the warning with this method, can someone explain?

Pandas Apply - is there a faster way?

Posted: 16 May 2022 10:20 AM PDT

I have some code like so in pandas to get the number of times a person switches restaurants:

df['SwitchCount'] = df.groupby('PersonId')['RestaurantName'].transform(lambda x: x.shift().ne(x).sum()-1)  

How can I optimize this code? My understanding is that transform is very computationally expensive. how can I change this code to be faster but do the same logic?o

Creating Trigger using javascript and django

Posted: 16 May 2022 10:20 AM PDT

I want to make a trigger using javascript. This is my trigger in js : setInterval(function(){ $.ajax({ type: 'GET', url : "{% url 'update_state' %}", success: function(response){

                console.log('Updated');                },              error: function(response){                  console.log('An error occured')              }          });      },60000);  

And this is my view :

def update_state(request):      requests = Request.objects.all()      for req in requests:          d = Request.objects.filter(id=req.id)          dd = d.get()          if dd.delay == timedelta(minutes=0):              pass          else:              d_del = dd.delay - timedelta(minutes=1)              d.update(delay=d_del)      return HttpResponse('ok')  

In my db sometimes the delay decrease but some time don't decrease. I don't know where is the problem.

Nest JS Circular dependency Can't resolve in context

Posted: 16 May 2022 10:20 AM PDT

Hihi

I have a Contract service that look like this

//contract.service.ts  export class ContractExtService {      constructor(      private readonly contractAttachmentService: ContractAttachmentExtService,    ) {}    ...  }  

And I can attach files to it

@Injectable()  export class ContractAttachmentExtService {      constructor(      private readonly contractService: ContractExtService,    ) {}      get user(): User {      return this.request.user;    }    ...  }  

I have a circular dependency because of other features that we have and other functionalities.

My contract.module looks like this

@Module({    imports: [      TypeOrmModule.forFeature([Contract]),      forwardRef(() => ContractAttachmentModule),    ],    controllers: [ContractExtController],    providers: [ContractExtService],    exports: [TypeOrmModule, ContractExtService],  })  export class ContractModule {}  

and the attachments like this

@Module({    imports: [      forwardRef(() => ContractModule),    ],    controllers: [ContractAttachmentExtController],    providers: [      ContractAttachmentExtService,    ],    exports: [ContractAttachmentExtService],  })  export class ContractAttachmentModule {}  

But I'm still getting this wild error

Nest can't resolve dependencies of the ContractExtService (?). Please make sure that the argument dependency at index [0] is available in the ContractModule context.  

Does this have a solution?

I already tried with

// @Inject(forwardRef(() => ContractAttachmentExtService))  

in BOTH constructors but what started happening was that all the rest of the injected dependencies were undefined

How To Code A UDP C# Server To Listen For Incoming Connections Rather Then Sending One?

Posted: 16 May 2022 10:19 AM PDT

so I am writing a C# UDP chat program where the server will listen for incoming connections from clients and then accept the connection form the client. The problem though it appears the server is instead sending the request to connect to the client and then waiting for it to start searching, where as I want it to listen for incoming connections on the servers IP address:

Here is the code :

bool done = false; bool exception_thrown = false;

        MessageBox.Show("Now listening on port 8001.");          Socket sending_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);          IPAddress send_to_adress = IPAddress.Parse(ipv4.Text);          IPEndPoint sending_end_point = new IPEndPoint(send_to_adress, 8001);             Console.WriteLine("Now sending attack information to listening computers. Attack command sent: " + satt.Text);                while (!done)          {              Console.WriteLine("Enter text to send and blank line to quit. ");              string text_to_send = satt.Text;              if (text_to_send.Length == 0)              {                  done = true;              }              else              {                  byte[] send_buffer = Encoding.ASCII.GetBytes(text_to_send);                    Console.WriteLine("Sending the information to the IP: {0} port: {1}",                      sending_end_point.Address,                      sending_end_point.Port);                  const int listenPort = 8001;                  UdpClient listener = new UdpClient(listenPort);                  IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);                  string data_recieved;                  byte[] recieve_byte_array;                  recieve_byte_array = listener.Receive(ref groupEP);                  data_recieved = Encoding.ASCII.GetString(recieve_byte_array, 0, recieve_byte_array.Length);                  Console.WriteLine("Number of searches by the listening computers: " + data_recieved);  

How can this be reworked for the server to listen on its own ip rather then sending a request? Thank you.

Calling parent constructor with props for react states

Posted: 16 May 2022 10:19 AM PDT

    class Example extends React.Component {        constructor(props) {          super(props);          this.state = {count: 0};        }       ....     }  

In the code above:

Why do we have to call both the constructor and super with props to use the state property ? Because i may not use this.props in the constructor of the inherited component. Just the state initialization.

AWS Lambda function access control

Posted: 16 May 2022 10:19 AM PDT

I am trying to restrict access to my Lambda function so that only the API server can make calls to it and no other application , how would I go about doing this ?

Unable to switch between environment in karate feature file

Posted: 16 May 2022 10:20 AM PDT

As per KARATE documentatoion we should use System.setProperty() to set env in test case level, But that option is not working in karate 1.1.0 (Didn't verify in previous versions)

Feature

  Feature: Testing env changing    Scenario: Reading base url of different env    * print 'Before changing env...---> '+ karate.env    * print 'Testing karate...'    * print baseUrl    * java.lang.System.setProperty("karate.env","STAGE")    * def newevn = java.lang.System.getProperty('karate.env')    * print 'After changing env...---> '+ newevn    * def fun = call read('file:karate-config.js')     * print 'Changed env...---> '+ fun.baseUrl  

Karate-Config.js file-

function fn() {    karate.configure('connectTimeout', 5000);    karate.configure('readTimeout', 5000);    var env = karate.env;    karate.log('karate.env system property was:', env);      var baseUrl = 'testingbase.com';    karate.log('Env---->' + env)    var port = karate.properties['demo.server.port'] || '8080';    var protocol = 'http';      var config = {      env: env,      baseUrl: 'https://localapi.abc123.example.com/api/v1/validate/customerid',      apiKey: ''    }    if (karate.properties['demo.server.https'] === 'true') {      protocol = 'https';      karate.configure('ssl', true);    }    var config = { demoBaseUrl: protocol + '://127.0.0.1:' + port };    if (env== 'mock') {      // karate.configure('callSingleCache', { minutes: 1 });      // 'callSingle' is guaranteed to run only once even across all threads      //var result = karate.callSingle('classpath:demo/headers/common-noheaders.feature', config);      // and it sets a variable called 'authInfo' used in headers-single.feature     // config.authInfo = { authTime: result.time, authToken: result.token };    }    else if(env=='BETA'){   config.baseUrl='tetsing.beta.base.com';      }    else if(env=='STAGE'){  config.baseUrl='tetsing.stage.base.com';      }    return config;  }    

html:Button thats supposed to do create a rectangle does nothing

Posted: 16 May 2022 10:19 AM PDT

Yes, I asked a similar question already, but I have to ask it again, 'cause I'm a slow learner.:( So the good thing is: I don't get 'a few(read:"a lot")' of Errors raining down at me. The bad thing is: I don't get anything... The button just does nothing! It's supposed to modify the size of a rectangle! I tried to make it execute this function:

  function a(){  class Rectangle{    constructor(height, width){      this.height = height;      this.width = width;      function createRectangle(height, width){      var input1 = document.getElementbyId("1stinput").value;      var input2 = document.getElementbyId("2ndinput").value;      var input1int = parseFloat(input1);      var input2int = parseFloat(input2);      const Rectangle1 = Rectangle(width="${input1int}",height="${input2int}");      document.querySelector("#svg").setAttribute("width", parseFloat(Rectangle1.width));      document.querySelector("#svg").setAttribute("height", parseFloat(Rectangle1.height));  };};};};  

Those are the input fields for the size:

<input type="text" name="" value="" id="1stinput">  <input type="text" name="" value="" id="2ndinput">  

And this is the rectangle:

<svg width=0 height=0 id="svg">    <rect width=0 height=0 style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" id="Rectangle"/>  </svg>  

Alright could someone please help me,I don't know what to do here,thanks for all the help! Bye!

How to set input value base on useState in react-admin v4?

Posted: 16 May 2022 10:19 AM PDT

I'm moving in react-admin v4. In my v3 (3.19.11), I have a with an initialValue equals to state. By default this state is an empty string and when I complete some other fields, it's updated and the value of the TextInput too.

But in v4 initialValue doesn't exist anymore and I would like to know if there is a simple way to do the same thing than v3 without to create a custom form with useForm/useController.

I tried to do that with a TextInput, a TextField and a native input. My issue is that either I don't have the input value updated, or it's updated but the input is not submitted in the form.

Code example in my v3 :

const [channelName, setChannelName] = useState<string>('');  const [partnerName, setPartnerName] = useState<string>('');  const [campaignName, setCampaignName] = useState<string>('');    useEffect(() => {      const fillCampaignName = () => {        const campaignValues: string[] = [];          campaignValues.push(channelName, partnerName);          const campaignValuesString = campaignValues          .filter((item) => item !== '')          .join('_');          setCampaignName(campaignValuesString);      };        fillCampaignName();    }, [channelName, partnerName]);    <Create {...props}>    <SimpleForm>      <AutocompleteInput variant="standard" source="channel" choices={channels} onChange={(channel: string) => setChannelName(channel)} />      <AutocompleteInput variant="standard" source="partner" choices={partners} onChange={(partner: string) => setPartnerName(partner)} />      <TextInput disabled source="name" variant="standard" label="Campaign name" initialValue={campaignName} />    </SimpleForm>  </Create>  

Thanks for your help.

Get unique elements for each grouping and write to column in Pandas Python

Posted: 16 May 2022 10:21 AM PDT

I have a data frame like so:

Input:

year ip   type  2020 101  Missing  2021 101  Type 1  2022 101  Type 2  2020 102  Missing  2021 102  Missing  2020 103  Missing  2021 103  Type 2  2021 104  Type 1  2022 104  Type 2  2022 104  Type 2  

How can I convert my data frame to the following:

Expected Output:

ip  type  101 Missing/Type 1/Type 2  102 Missing  103 Missing/Type 2  104 Type 1/Type 2  

Where I get all unique types for each IP. How can I do this in python pandas?

The best way to query by location in firestore

Posted: 16 May 2022 10:21 AM PDT

I am using Firebase 8.10.0 with Vue js 2.6.14

I am trying to query in Firestore about the documents that are less than 3 km away from my location And discovered that I could not do this query in firestore, I was frankly disappointed Then after watching a video by Frank van Puffelen on YouTube "Querying Firebase and Firestore"1 I understood that the best way to do this query is through Geohash So now I'm using ngeohash to convert lat long to geohash code then geofirestore to query ( i am not using geofirestore to add the data to firestore because i don't find a way to add doc with specific id or update an existing doc with geofirestore )

convert lat long to geohash code

import geohash from "ngeohash";    const ask = async () => {    try {      const loc = await new Promise((resolve, reject) => {        navigator.geolocation.getCurrentPosition(resolve, reject, {          enableHighAccuracy: true,        });      });      const { latitude, longitude, accuracy } = loc.coords;        return {        lat: latitude,        lng: longitude,        accuracy: accuracy,        geohash: geohash.encode(latitude, longitude)      };    } catch (err) {      console.log(err);    }  };  

add data to firestore

ref.set({    g: {      geopoint: new db.GeoPoint(lat, lng),      geohash: geohash    },    ...data  }, { merge: true }).then(() => {    console.log("Done");  });  

query from firestore

let query = geocollection.near({ center: new db.GeoPoint(lat, lng), radius: 3 });  query.get().then((data) => {    console.log(data.size);  });  

Is what I'm doing right is this the best way to query by location in firestore? and does geofirestore increase the number of readings because I made a query a while ago and the result was only 5 from 1000 documents, but I found that more than 60 readings were recorded in the Firebase console. Is this normal or was it only supposed to be 5 readings?

How to extract a specific item from a array of Typescript objects?

Posted: 16 May 2022 10:19 AM PDT

I am new to Typescript, can you help me with this-

I have an array of objects, -

[{Name: a,    Age: 1   },   {Name: b,    Age: 2   }  ]  

I want an array which should be - [a, b]

I tried with the following but I am not getting the expected result-

for (int i=0; i< treeData.length; i++) {      finalArray.push(treeData[i][0]);  }  console.log(finalArray);  

Can anyone please help me out. Thanks in advance..

How do I create a matrix counting how many times a value in a list is in another list from a list of lists? [closed]

Posted: 16 May 2022 10:21 AM PDT

I would like to create a matrix counting how many times a value is in the same list of another one.

Let me explain better:

  • I have 47 categories, labeled from 0 to 46
  • I have a list of lists of this kind: myList = [[0, 46, 2], [0, 46, 5], [1, 46, 2], ..., [22, 33, 2]]
  • The numerical values cannot be repeated inside the smaller lists, hence [46, 46, 3] is not a valid list

For example, let's consider the first list [0, 46, 2]:

  1. 0 appears two times in the lists containing 0, indeed [0,46,2], [0, 46, 2] --> +2
  2. 46 appears two times in the lists containing 0, indeed [0, 46, 2] and [0, 46, 5] --> +2
  3. 2 appears one time in the lists containing 0, indeed [0, 46, 2] --> +1
         0 |  1  |  2 |  3 |  4 |  5 |  .....  | 46  0     |  2 |     |  1 |    |    |  1 |    |    | 2  1     |  1 |  1  |  1 |    |    |    |    |    | 1  2     |  1 |  1  |    |    |    |    |    |    |  3     |    |     |    |    |    |    |    |    |  4     |    |     |    |    |    |    |    |    |  5     |  1 |     |    |    |    |    |    |    |  ....  |    |     |    |    |    |    |    |    |  46    |  2 |  1  |    |    |    |    |    |    |  

Unable to join tables from 2 tables with one to many condition

Posted: 16 May 2022 10:20 AM PDT

I have this diagram below, I am trying to first computes the total number of suppliers supplying the specified part then extracts the supplier's information supplying the specified part.

SELECT count(*) totalCount, s_suppkey, s_name                                                 FROM supplier INNER JOIN part ON s_suppkey = p_suppkey  WHERE p_partkey = 123  GROUP BY s_suppkey, s_name;  

enter image description here

But i keep getting this error ORA-00904: "P_SUPPKEY": invalid identifier

How to get a subquery to work within a case statement using not in operator

Posted: 16 May 2022 10:19 AM PDT

I'm trying to use a subquery within a case statement using 'not in' operator and its not working as expected:

SELECT item, MAX(CASE WHEN store NOT IN (TRIM((SELECT GROUP_CONCAT(CONCAT('''',store,   '''' )) FROM tblstore))) THEN price END) "other"   FROM TT GROUP BY item ;  

I'm expecting to see an output of null values by row. The case statement works if I manually input the values, but not with the subquery. Shown in the 2nd and 3rd examples on the TT table in the fiddle below. The subquery works as expected if run by itself shown in first example on the tblstore.

Please help with what I'm doing wrong. Thank you in advance.

https://dbfiddle.uk/?rdbms=mariadb_10.6&fiddle=cab0054e872cd52ff60b344a403b9723

Haskell Strict MVar with Bang pattern

Posted: 16 May 2022 10:20 AM PDT

The following code example takes approx 2 seconds to execute. When the bang pattern in line 14 is removed however, it takes 60s. Can anyone explain what is going on?

I am using strict MVar so whatever is put into the MVar, should be fully evaluated to normal form. I would not expect a Bang pattern before inserting into the MVar to have any noticable effect.

{-# LANGUAGE BangPatterns #-}    import           Control.Concurrent.MVar.Strict  import qualified Data.Text as T  import           Data.Text.Encoding    main :: IO ()  main = do      mvar <- newMVar T.empty        let bsArr = map (\i -> encodeUtf8 $ T.pack $ "some strange string " ++ show i) [0 .. 30000 :: Int]          mvarWriter =              \lbs ->                  let !decoded = decodeUtf8 lbs                  in  modifyMVar_ mvar (\oldText -> return $ oldText <> decoded)        mapM_ (\lbs -> mvarWriter lbs) bsArr      print . T.length =<< readMVar mvar  

How can i link my front-end to my back-end to create a new column in a table

Posted: 16 May 2022 10:19 AM PDT

I am using reactjs,nodejs and my sql to develop a web application . I am writing the code to add a new column to a table ,this is my backend code

//this is written in a file companies.js  router.post('/companies', companiesController.createCompany);      //create company  in compnaniescontroller.js file  const createCompany = async function(req, res, next) {    try {      const {        CompanyName      } = req.body;        const sqlInsert =        'INSERT INTO infos_stations.Companies ' +        '(CompanyName) ' +        'VALUES (?)';        database.query(sqlInsert, [CompanyName], (error, result) => {        if (error) throw error;          return res.status(201).json({});      });    } catch (err) {      return res.status(500).send({        code: 500,        status: false,        data: "Internal Server Error"      });    }  };

This is part of the code in my front-end

axios  .post("('/companies', companiesController.createCompany);", {   Compagnie,   })

What should i write inside in the front-end code .post(...) to link my front-end to my back-end since it's not working the way i'm writing it

Is there a way in python to plot date ranges of grouped by object on a timeseries plot?

Posted: 16 May 2022 10:20 AM PDT

I have following data frame with the country names as index and dates in 'start' and 'end' columns.

          start       end  
Argentina   2021-01-31  2021-05-31  Australia   2021-02-28  2021-06-30  Brazil      2021-03-31  2021-07-31  Canada      2021-04-30  2021-08-31  

I am looking for a way to plot the date range between the 'start' and 'end' dates for each of the countries like shown in the image below. Is there some way to do this in python? I would like country names from my data frame to appear where the crop names appear in the image below. And I don't care about the legend at the moment.

countries = ['Argentina', 'Australia', 'Brazil', 'Canada']    start = pd.date_range(start='2021-01', end ="2021-05", freq='M')    end = pd.date_range(start='2021-05', end ="2021-09", freq='M')    df= pd.DataFrame({'start':start,'end':end}, index=countries)  

illustrative picture with different categories

Powershell script fails after invoking 'Start-Transcript'

Posted: 16 May 2022 10:21 AM PDT

I have a simple powershell script that checks network availability by making routine checks that bbc.co.uk is available.

The script has been working fine (and logging without issue), for many weeks, but has recently stopped working. Basically, the script gets to Start-Transcript, creates the logfile, makes an initial entry into the log file, and then quits (i.e. the powershell console blinks out of existence, no errors, no messages, no warnings, and nothing further in the log file.)

If I comment out the Start-Transcript line then it works fine (minus the logging). the only difference I'm aware of is that last time it was working on I was using PSVersion: 5.1.19041.1320 which has since been upgraded to PSVersion: 5.1.22000.653.

Here it is.

Set-PSDebug -Strict    $ErrorActionPreference = "stop"  $DebugPreference = "Continue"  Write-Debug "Debug is set on"    Write-Debug "switching on logging to $($($PSCommandPath).Replace("ps1","$pid")+".log")...."  Start-Transcript -Append $($($PSCommandPath).Replace("ps1","$pid")+".log") # Use the name of this script, plus the pid as the name of the file to log to  Write-Debug "logging on"    [bool]$result=$true  [bool]$prevResult=$false    function fnTestForCtrlC  {     ## Stops Ctrl+C from exiting this function     [console]::TreatControlCAsInput = $true       if ($Host.UI.RawUI.KeyAvailable -and (3 -eq [int]$Host.UI.RawUI.ReadKey("AllowCtrlC,IncludeKeyUp,NoEcho").Character))     {        Write-Debug ""        Write-Debug "fnTestForCtrlC() - @<$(get-date -Format "HH:mm:ssL") ($((get-date).ToUniversalTime().ToString("HH:mm:ssZ")))> Ctrl+C Pressed! Ending procesing. Attempting a tidy shutdown"        Stop-Transcript # Stop logging        exit # quit     }  }      while($true)   {      fnTestForCtrlC    try    {      $result = $(Test-Connection -ComputerName www.bbc.co.uk -Quiet)    }    catch    {      $ErrMess = $_.Exception.Message      Write-Debug "Test-connecion raised following following error=<$ErrMess>. "    }        fnTestForCtrlC      if ($result -ne $prevResult)    {      if ($result -eq $true)      {        Write-Host -NoNewline " @<$(get-date -Format 'HH:mm:ss')> network Up ^"      }      else      {        Write-Host -NoNewline " @<$(get-date -Format 'HH:mm:ss')> network Down v"      }    }    else    {      if ($result -eq $true)      {        Write-Host -NoNewline "^"      }      else      {        Write-Host -NoNewline "v"      }    }    $prevResult = $result      Start-Sleep 1       fnTestForCtrlC      Start-Sleep 1   }  

The OS is windows 11, the log file looks like this....

**********************  Windows PowerShell transcript start  Start time: 20220516163045  Username: PRIVATESERVER\Anon  RunAs User: PRIVATESERVER\Anon  Configuration Name:   Machine: PRIVATESERVER (Microsoft Windows NT 10.0.22000.0)  Host Application: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoExit -command &c:\pwrShl\netTest.ps1  Process ID: 4676  PSVersion: 5.1.22000.653  PSEdition: Desktop  PSCompatibleVersions: 1.0, 2.0, 3.0, 4.0, 5.0, 5.1.22000.653  BuildVersion: 10.0.22000.653  CLRVersion: 4.0.30319.42000  WSManStackVersion: 3.0  PSRemotingProtocolVersion: 2.3  SerializationVersion: 1.1.0.1  **********************  

Ok, think I've fixed it. For historic reasons (i.e. I never got round to changing it) the shortcut I was using to run this script had this target

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoExit -command "&c:\pwrShl\netTest.ps1"  

If I change it to this it works...

"%SystemRoot%\syswow64\WindowsPowerShell\v1.0\powershell.exe " -NoExit -command "&c:\pwrShl\netTest.ps1"  

How to override global style from a child component and scope the change only under that component in angular

Posted: 16 May 2022 10:19 AM PDT

I have declared some css styling in global style.css file which is src/style.css in my angular project. In one of my component I want to override some styling and scope it only for that component. Currently, I can able to do that by using ::ng-deep, but, problem is, while I am changing global style from my child component using ::ng-deep it also alter the styling in global.scss as a result rest of my component also affecting for this. So what I want is, when I am changing this global style from that child component I just want to scope that change under that component.

The CSS class I declare in Src/Style.css is:

.main-content {    width: 100%;    padding: 24px;  }  

I applied following attempts which did override the global styling, however, it also keep the change as a result other components also get affected by that change.

Attempt 1:

I apply encapsulation: ViewEncapsulation.None in the component and apply following in component scss file:

.main-content {    padding: 24px 0px !important;  }  

It worked, means, it does override the global style but the change doesn't scope only for this component.

Attempt 2:

I remove encapsulation for the component and apply ::ng-deep like below:

::ng-deep .main-content {     padding: 24px 0px !important;  }  

it also do the same as attempt 1.

Attempt 3:

I also found that if I use ::ng-deep with :host it scope the change only for that component. However, I couldn't able to make it working when I am using :host. Like the following piece of code doesn't do anything for my case:

:host ::ng-deep .main-content {    padding: 24px 0px !important;  }  

In this situation, how can I achieve overriding global css and scope it only for that component?

React updating single object of an array of objects - map vs entire array

Posted: 16 May 2022 10:19 AM PDT

I have a component with an array of objects in local state:

    const [myState, setState] = useState<SomeObjectType[]>([]);  

I can update a single object in that array by making a copy of the entire array and then update the property of the single object I wish to update:

OPTION 1

      const state = [...myState];      state[id].description = description;      setState(state);    

Or I can use map:

OPTION 2

    const newState = talkingPoints.map(el => {        // 👇️ if id equals, update description property        if (el.id === id) {          return {...el, description};        }          // 👇️ otherwise return as is        return el;      });        setData(newState);  

Or can I do this (since I am 100% certain the id exists in the array)?

OPTION 3

  const handleUpdate = () => {      setState(prevState => ({        ...prevState,        prevState[id].description = description      }))    }  

For cases where I am not 100% certain I can use map and find it:

OPTION 4

  const handleUpdate = () => {      setState(prevState => ({        myState: prevState.myState.map(el => el.id === id ? { ...el, description } : el)      }))    }  

What is recommended/best practice? Is Option 1 (fully array copy) faster than using map?

How to change a UI's color when its being hovered over

Posted: 16 May 2022 10:20 AM PDT

I'm trying to make a UI that changes to a lighter color when its hovered over (roblox's default is darker)

MouseEnter and MouseLeave have already been tested and don't work the way I want it to. MouseEnter keeps the darkening and makes my target color darker than it should be.

Is this possible, if so, how would it be used?

Bayesian ANN regression using pyro

Posted: 16 May 2022 10:19 AM PDT

I have the below data where I am trying to fit the column 'Diff_t+1' with the 12 input parameters.

enter image description here

I want to implement Bayesian method using Pyro for the same. I don't want to use PyroModule and PyroSample. I have written the below code:

import numpy as np  import pandas as pd  import torch  import pyro  import pyro.distributions as dist  from pyro.nn import PyroModule, PyroSample  import torch.nn as nn  from pyro.infer.autoguide import AutoDiagonalNormal  from pyro.infer import SVI, Trace_ELBO, Predictive  from tqdm.auto import trange, tqdm    # import data and creating train and test data  df = pd.read_csv('data_model.csv', header=0, parse_dates=[0])  df_cleaned = df.dropna()  X_scale_dataset = df_cleaned.iloc[:,1:-1].to_numpy()  y_dataset = df_cleaned.iloc[:,-1].to_numpy()  X_train, X_test, y_train, y_test = train_test_split(X_scale_dataset, y_dataset, train_size=0.7, random_state=42, shuffle=False)  data_target = y_train  data_feature = X_train    # creating pytorch ANN class for regression along with pyro distribution  class ANNModel(nn.Module):      def __init__(self, input_dim=12, hidden_dim=20, output_dim=1):          super(ANNModel, self).__init__()          self.fc1 = nn.Linear(input_dim, hidden_dim)          self.fc1.weight = pyro.sample("fc1_weight", dist.Normal(0., 1.).expand([hidden_dim, 12]).to_event(2))          self.fc1.bias = pyro.sample("fc1_bias", dist.Normal(0., 1.).expand([hidden_dim]).to_event(1))          self.fc2 = nn.Linear(hidden_dim, hidden_dim)          self.fc2.weight = pyro.sample("fc2_weight", dist.Normal(0., 1.).expand([hidden_dim, hidden_dim]).to_event(2))          self.fc2.bias = pyro.sample("fc2_bias", dist.Normal(0., 1.).expand([hidden_dim]).to_event(1))          self.fc3 = nn.Linear(hidden_dim, output_dim)            self.fc3.weight = pyro.sample("fc3_weight", dist.Normal(0., 1.).expand([1, hidden_dim]).to_event(2))          self.fc3.bias = pyro.sample("fc3_bias", dist.Normal(0., 1.).expand([1]).to_event(1))          self.relu = nn.ReLU()            def forward(self, x, y=None):          x = x.reshape(-1, 12)          x = self.relu(self.fc1(x))          x = self.relu(self.fc2(x))          mu = self.fc3(x).squeeze()          sigma = pyro.sample("sigma", dist.Uniform(0., 1.))          with pyro.plate("data", x.shape[0]):              obs = pyro.sample("obs", dist.Normal(mu, sigma), obs=y)          return mu        # defining model  model = ANNModel()  guide = AutoDiagonalNormal(model)  adam = pyro.optim.Adam({"lr": 1e-3})  svi = SVI(model, guide, adam, loss=Trace_ELBO())    # executing pyro bayesian model matching  pyro.clear_param_store()  bar = trange(8000)  x_train = torch.from_numpy(data_feature).float()  y_train = torch.from_numpy(data_target).float()  for epoch in bar:      loss = svi.step(x_train, y_train)      bar.set_postfix(loss=f'{loss / x_train.shape[0]:.3f}')  

When I am running the above code I am getting the below error: cannot assign 'torch.FloatTensor' as parameter 'weight' (torch.nn.Parameter or None expected)

Pls help to resolve the issue.

ImageMagick: Put curved text over image

Posted: 16 May 2022 10:19 AM PDT

I want to use ImageMagick to annotate images with curved text. Creating curved text on a plain image works:

convert -size 600x500 xc:white -pointsize 72 -fill red -annotate +100+200 "C H E S S" -distort Arc 100 test.png  

plain image with curved text

But when I try to put the text on top of another image, the background image gets curved as well:

convert checker.png \( -pointsize 72 -fill red -annotate +100+200 "C H E S S" -distort Arc 100 \) test.png  

enter image description here

How can I avoid curving the background image and only curve the text?

Update: GeeMack's answer suggested something like this:

convert \  -pointsize 72 -fill red -background none label:"C H E S S" \  -virtual-pixel none -distort Arc 100 \  checker.png +swap \  -gravity center -geometry +0-100 -composite result.png  

But now, I get white text instead of red:

enter image description here

Scrapy merge subsite-item with site-item

Posted: 16 May 2022 10:20 AM PDT

Im trying to scrape details from a subsite and merge with the details scraped with site. I've been researching through stackoverflow, as well as documentation. However, I still cant get my code to work. It seems that my function to extract additional details from the subsite does not work. If anyone could take a look I would be very grateful.

# -*- coding: utf-8 -*-  from scrapy.spiders import Spider  from scrapy.selector import Selector  from scrapeInfo.items import infoItem  import pyodbc      class scrapeInfo(Spider):      name = "info"      allowed_domains = ["http://www.nevermind.com"]      start_urls = []        def start_requests(self):            #Get infoID and Type from database          self.conn = pyodbc.connect('DRIVER={SQL Server};SERVER=server;DATABASE=dbname;UID=user;PWD=password')          self.cursor = self.conn.cursor()          self.cursor.execute("SELECT InfoID, category FROM dbo.StageItem")            rows = self.cursor.fetchall()            for row in rows:              url = 'http://www.nevermind.com/info/'              InfoID = row[0]              category = row[1]              yield self.make_requests_from_url(url+InfoID, InfoID, category, self.parse)        def make_requests_from_url(self, url, InfoID, category, callback):          request = Request(url, callback)          request.meta['InfoID'] = InfoID          request.meta['category'] = category          return request        def parse(self, response):          hxs = Selector(response)          infodata = hxs.xpath('div[2]/div[2]')  # input item path            itemPool = []            InfoID = response.meta['InfoID']          category = response.meta['category']            for info in infodata:              item = infoItem()              item_cur, item_hist = InfoItemSubSite()                # Stem Details              item['id'] = InfoID              item['field'] = info.xpath('tr[1]/td[2]/p/b/text()').extract()              item['field2'] = info.xpath('tr[2]/td[2]/p/b/text()').extract()              item['field3'] = info.xpath('tr[3]/td[2]/p/b/text()').extract()              item_cur['field4'] = info.xpath('tr[4]/td[2]/p/b/text()').extract()              item_cur['field5'] = info.xpath('tr[5]/td[2]/p/b/text()').extract()              item_cur['field6'] = info.xpath('tr[6]/td[2]/p/b/@href').extract()                # Extract additional information about item_cur from refering site              # This part does not work              if item_cur['field6'] = info.xpath('tr[6]/td[2]/p/b/@href').extract():                  url = 'http://www.nevermind.com/info/sub/' + item_cur['field6'] = info.xpath('tr[6]/td[2]/p/b/@href').extract()[0]                  request = Request(url, housingtype, self.parse_item_sub)                  request.meta['category'] = category                  yield self.parse_item_sub(url, category)              item_his['field5'] = info.xpath('tr[5]/td[2]/p/b/text()').extract()              item_his['field6'] = info.xpath('tr[6]/td[2]/p/b/text()').extract()              item_his['field7'] = info.xpath('tr[7]/td[2]/p/b/@href').extract()                      item['subsite_dic'] = [dict(item_cur), dict(item_his)]                itemPool.append(item)              yield item          pass            # Function to extract additional info from the subsite, and return it to the original item.          def parse_item_sub(self, response, category):              hxs = Selector(response)              subsite = hxs.xpath('div/div[2]')  # input base path                category = response.meta['category']                for i in subsite:                          item = InfoItemSubSite()                      if (category == 'first'):                      item['subsite_field1'] = i.xpath('/td[2]/span/@title').extract()                                  item['subsite_field2'] = i.xpath('/tr[4]/td[2]/text()').extract()                      item['subsite_field3'] = i.xpath('/div[5]/a[1]/@href').extract()                  else:                      item['subsite_field1'] = i.xpath('/tr[10]/td[3]/span/@title').extract()                                  item['subsite_field2'] = i.xpath('/tr[4]/td[1]/text()').extract()                      item['subsite_field3'] = i.xpath('/div[7]/a[1]/@href').extract()                  return item              pass  

I've been looking at these examples together with a lot of other examples (stackoverflow is great for that!), as well as scrapy documentation, but still unable to understand how I get details send from one function and merged with the scraped items from the original function.

how do i merge results from target page to current page in scrapy? How can i use multiple requests and pass items in between them in scrapy python

Basic AWS S3 PHP setup

Posted: 16 May 2022 10:19 AM PDT

I've been trying for a while to setup just a basic PHP implementation of an upload form to upload to Amazon's S3 service, but I can't get anything to work.

Reading through their docs, their examples all seem different. What is the correct way to provide credentials and upload a file?

On their github repo, it says:

// Require the Composer autoloader.  require 'vendor/autoload.php';    use Aws\S3\S3Client;    // Instantiate an Amazon S3 client.  $s3 = new S3Client([      'version' => 'latest',      'region'  => 'us-west-2'  ]);    try {      $s3->putObject([          'Bucket' => 'my-bucket',          'Key'    => 'my-object',          'Body'   => fopen('/path/to/file', 'r'),          'ACL'    => 'public-read',      ]);  } catch (Aws\Exception\S3Exception $e) {      echo "There was an error uploading the file.\n";  }  

On http://docs.aws.amazon.com/aws-sdk-php/v2/guide/service-s3.html they say:

use Aws\S3\S3Client;    $client = S3Client::factory(array(      'profile' => '<profile in your aws credentials file>'  ));    // Upload an object by streaming the contents of a file  // $pathToFile should be absolute path to a file on disk  $result = $client->putObject(array(      'Bucket'     => $bucket,      'Key'        => 'data_from_file.txt',      'SourceFile' => $pathToFile,      'Metadata'   => array(          'Foo' => 'abc',          'Baz' => '123'      )  ));    // We can poll the object until it is accessible  $client->waitUntil('ObjectExists', array(      'Bucket' => $this->bucket,      'Key'    => 'data_from_file.txt'  ));  

Can anyone who has been able to do this recently shed some light on the setup here?

No comments:

Post a Comment