Sunday, March 13, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


how to add a dateAndTime to form component in react native

Posted: 13 Mar 2022 03:50 AM PDT

i need to add a dateAndTime to react native form component I would love to hear ideas if there any custom method to add a button to show the date time or textfield that should be show the datetimepicker to the form the be able to the submit button react-native-form-component thanksss for helpppppppppppppppppp.

import React, { useState } from 'react';  import { Text, Button,View,SafeAreaView } from 'react-native';  import { Form, FormItem, Picker } from 'react-native-form-component';  import DateTimePicker from '@react-native-community/datetimepicker';          const AddCourseForm = ({ route, navigation }) => {          const [courseName, setCourseName] = useState('')          const [gender, setGender] = useState('')          const [maxUsers, setMaxUsers] = useState('')          const [date, setDate] = useState(new Date(Date.now()))          const [mode, setMode] = useState('date');          const [show, setShow] = useState(false);                const showMode = (currentMode) => {              setShow(true);              setMode(currentMode);          };          const onChange = (event, selectedDate) => {              const currentDate = selectedDate || date;              setShow(Platform.OS === 'ios');              setDate(currentDate);          };                const showDatepicker = () => {              showMode('date');          };                const showTimepicker = () => {              showMode('time');          };          const customFields = {              'Button': {                controlled: true,              }            }          return (              <SafeAreaView>                              <Form buttonText="save" onButtonPress={() => console.warn("hii")} customFields={customFields}>                      <FormItem                          label="course name"                          isRequired                          placeholder="course name"                          value={courseName}                          onChangeText={(courseName) => setCourseName(courseName)}                          maxLength={30}                          asterisk                      />                      <Picker                          items={[                              { label: 'male', value: 1 },                              { label: 'female', value: 2 },                          ]}                          placeholder="gender"                          label="gender"                          selectedValue={gender}                          onSelection={(item) => setGender(item.value)}                      />                      {show && (                          <DateTimePicker                              testID="dateTimePicker"                              value={date}                              mode={mode}                              is24Hour={true}                              display="default"                              minimumDate={new Date(Date.now())}                              onChange={onChange}                          />                      )}                  <Button type="Button" name="myButton" onPress={showDatepicker} title="ggg" />                  </Form>                                </SafeAreaView>                );            }      export default AddCourseForm;  

How to prevent findOneAndUpdate update certain keywords to a column?

Posted: 13 Mar 2022 03:50 AM PDT

I have a user management system where admin has the rights to update the role of their users, how to prevent admin from updating a document with roles higher than him? Example, order of authority in descending order: 1: superadmin 2: admin 3: supervisor 4: user

Now I have a code which updates the role of a user as:

router.post('/changeRole', async (req, res) => {    const { email } = req.body;    const updatedUser = await Users.findOneAndUpdate({ email }, { $set: { role } }, { new: true });    }  );  

By the above code admin could make anyone a superdmin and it would give that user every access. Is there a way something like this below to prevent that in query?

router.post('/changeRole', async (req, res) => {    const { email } = req.body;    const updatedUser = await Users.findOneAndUpdate({ email }, { $set: { role !== "superadmin" } }, { new: true });    }  );    

How do I fix comment showing on code in javascript?

Posted: 13 Mar 2022 03:49 AM PDT

Im trying to download jQuery into my document via my js file. when i do document.write however, the "https://" is marked as a comment.

function downloadjQuery() {      document.open();      document.write("<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>");      document.close();  }  

how to create smoothed matrix?

Posted: 13 Mar 2022 03:49 AM PDT

I need your help. I have task that has next formulation:

Matrix of real numbers "Smooth": The new value of each of its item becomes average arithmetic values of elements adjacent to it (vertically and horizontally). do not create new matrices, but you can use additional rows or columns.

My code:

void Smooth(double **mat, int R, int C)  {    mat[0][0] = (mat[R - 2][0] + mat[0][C - 2]) / 2;    mat[0][C - 1] = (mat[0][C - 2] + mat[C - 1][0]) / 2;    for(int i = 1; i < R - 1; i++)    {      mat[0][i] = (mat[0][i - 1] + mat[0][i + 1] + mat[1][i]) / 3;    }    mat[R - 1][0] = (mat[R - 1][1] + mat[R - 2][0]) / 2;    mat[R - 1][C - 1] = (mat[R - 1][C - 2] + mat[R - 2][C - 1]) / 2;   for(int i = 1; i < R - 1; i++)   {     mat[R - 1][i] = (mat[R - 1][i - 1] + mat[R - 1][i+1] + mat[R - 2][i]) / 3;    }  }  

I don't know really how to do it shorter. Please help me solve this problem. It is only piece of code

Response doesn't wait for async function

Posted: 13 Mar 2022 03:49 AM PDT

I found the aproach how to put the async function into a router endpoint and tried to implement it but not suceed. E.g. this link zellwk.com

The server sends only empty string instead of a huge string that is on snippet.host.

    async function downloadData(url) {          const options = {              'method': 'GET', 'url': url, 'headers': {}, formData: {}          };          let result = '';          await request(options, function (error, response) {              if (error) throw new Error(error);              console.log(response.body)              result = response.body          });          return {error: 0, text: result}      }  
    app.get('/token/:token', jsonParser, async function (req, res) {          console.log(req.params.token) //Don't mind this token          try {              let message = await downloadData('https://snippet.host/xgsh/raw')              res.send(message)          } catch (e) {              console.log(e);              res.sendStatus(500);          }      });  

How to make it wait for the download?

Unity Moving bodies rest relative to each other

Posted: 13 Mar 2022 03:48 AM PDT

I Have one cube with hingejoint and motor on it, then I dump on it another cube with rigidbody, So I need to know when the top cube will stop at the bottom

At first I thought of using a velocity-to-radius ratio: linear velocity v = angular velocity w * radius r, so v2/v1 = r2/r1, but in unity it doesn't work, because w of two rigidbodies isn't the same. For example i have speed ratio of two fixed cubes == 3.15 for r1=1 and r2=3 (it should be 3)Here's what it looks like

I really have no idea how can i resolve it. Maybe there is some local analogue(In a moving coordinate system) of rigidbody.isSleeping or something ?

Emulate BTreeMap::pop_last in stable Rust

Posted: 13 Mar 2022 03:48 AM PDT

In the current stable Rust, is there a way to write a function equivalent to BTreeMap::pop_last?

The best I could come up with is:

fn map_pop_last<K, V>(m: &mut BTreeMap<K, V>) -> Option<(K, V)>  where      K: Ord + Clone,  {      let last = m.iter().next_back();      if let Some((k, _)) = last {          let k_copy = k.clone();          return m.remove_entry(&k_copy);      }      None  }  

It works, but it requires that the key is cloneable. BTreeMap::pop_last from Rust nightly imposes no such constraint.

If I remove the cloning like this

fn map_pop_last<K, V>(m: &mut BTreeMap<K, V>) -> Option<(K, V)>  where      K: Ord,  {      let last = m.iter().next_back();      if let Some((k, _)) = last {          return m.remove_entry(k);      }      None  }  

it leads to

error[E0502]: cannot borrow `*m` as mutable because it is also borrowed as immutable    --> ...     |  .. |     let last = m.iter().next_back();     |                -------- immutable borrow occurs here  .. |     if let Some((k, _)) = last {  .. |         return m.remove_entry(k);     |                ^^------------^^^     |                | |     |                | immutable borrow later used by call     |                mutable borrow occurs here  

Is there a way to work around this issue without imposing additional constraints on map key and value types?

How do I match user input to the name of a pre-defined array? [duplicate]

Posted: 13 Mar 2022 03:48 AM PDT

I'm trying to create a game that takes a user input and then updates the player_class array with the values from another pre-set array.

class1 = [5,10,15]  class2 = [6,12,18]  player_class = [0,0,0]    class_choice = input("enter class name")  

In this code, I would like the input from the class_choice input statement to correspond to one of the already defined arrays, and then copy the values from that array to the player_class array, but am unsure how to implement it. I know it looks like a waste of time with just two arrays, but with hundreds of them I think this must be a more efficient way. Thanks!

Changing the value of an element in a struct

Posted: 13 Mar 2022 03:48 AM PDT

I'm new to structs. I am trying to write a program that has a struct, and the struct is supposed to store a character array and its length. I want to be able change the length's value as I would be creating functions like trimming/concatenating the array. Here is a code I wrote:

#include <stdio.h>  #include <stdlib.h>  struct strstruct{  unsigned int length;  char string[20];  };  typedef struct strstruct stru;  int strleng(stru A){    int i=0;    while(A.string[i]!='\0'){      i++;    }    A.length =i;    return i;  }  int main(){      stru A = {1,   {'a','b','c','d','e','f'}    };        printf("%d %d\n",strleng(A),A.length);    return 0;  }  

Clearly, the value of A.length is not changing inspite of calling strleng.
(i)Why?
(ii) Is there another way to do it?

Php Sql query with 2 where conditions, one being a $_SESSION variable

Posted: 13 Mar 2022 03:48 AM PDT

Morning everyone, can someone please point out to me where i am going wrong. I have a table of users and a table of artists, and a table of user_artists which has only 2 columns - user_id(int type) & artist_id(varchar type).

i am trying to do a sql query in php to find matches for both fields. I am using -

 $favouriteQuery = "SELECT * FROM user_artists      WHERE artist_id = '".$artist_id." '      AND user_id = '".$_SESSION['id']."'";        $favourite = $conn->query($favouriteQuery);        $row_cnt = $favourite->num_rows;  

i have tried running the same query while replacing the session id with '1' which is a valid user id and the query works, i have also echoed the $_SESSSION['id'] in a line before the query so i know the value of it definetely is set. However when i run the query with the sesssiona variable in it i get -

Notice: Undefined variable: _SESSION in C:\xampp\htdocs\topalbums\artist.php on line 49    Notice: Trying to access array offset on value of type null in C:\xampp\htdocs\topalbums\artist.php on line 49  

I would really appreciate it if someone could shed some light on this for me!Thanks in advance.

How Can I Unit Test DOS Attack on a NodeJS Server

Posted: 13 Mar 2022 03:48 AM PDT

i would like to understand DOS (denial-of-service) attacks better and I would like to know what my options are for learning about it with an example.

i have a basic express server.

app.get('/ping', (req, res) => {    res.send({ pong: 'pong', time: new Date().valueOf(), memory: process.memoryUsage()})  })  

I will separately create some javascript code that with make multiple requests to the server. but I don't know to devise strategies to try and bring down the server (consider that this is all running on localhost)

I want to see what the upper limit of making requests is possible when locally testing this. i am experiencing what is described here: Sending thousands of fetch requests crashes the browser. Out of memory

... the suggestions on that thread are more along the lines of "browser running out of memory" and that I should "throttle requests".... but I am actively trying to max out the requests the browser can make without crashing. so far my observations are that the server does not have any difficulty. (so maybe I should also make requests from my phone and tablet?)

the code have run on the browser isn't much more than:

    const makeRequestAndAlogTime = () => {      const startTime = new Date().valueOf();      fetch('http://localhost:4000/ping')        .then(async (response) => {          const { time, memory } = await response.json();          console.log({            startTime: 0,            processTime: time - startTime,            endTime: new Date().valueOf() - startTime,            serverMemory: memory,            browserMemory: performance['memory']          })        })    }        for(let x = 0; x < 100; x++) {        makeRequestAndAlogTime()      }  

but depending on what value I put in for the number of times to go through the for loop, performance is slower and eventually crashes (as expected)... but I want to know if there is a way I could automate determining the upper limit of requests that I can make on my browsers?

how to calculate asymptotic complexity of a for loop with a fixed number of iterations?

Posted: 13 Mar 2022 03:49 AM PDT

def find1(L, ele):

"""L a list of ints, ele is an int"""

for i in range(100):     for e1 in L:       if e1 == ele:         return True  return False  

def find2(L, ele): """L a list of ints, ele is an int"""

for i in range(ele):    for e1 in L:     if e1 == ele:       return True  return False  

above are two functions,for find2 function i understand time complexity is O(n^2) for find1 the first for loop has fixed number 100 iterations,how to calculate complexity for find1 function

Flutter - Instance of future<String>

Posted: 13 Mar 2022 03:50 AM PDT

I know why it returns this but I don't know how to get the actual value that I want

Future<String> _getAddress(double? lat, double? lang) async {  if (lat == null || lang == null) return "";  GeoCode geoCode = GeoCode();  Address address =  await geoCode.reverseGeocoding(latitude: lat, longitude: lang);  return "${address.streetAddress}, ${address.city}, ${address.countryName}, ${address.postal}";  

}

Text(_getAddress(lat, lon).toString())  

How to subtract minutes from string in Delphi

Posted: 13 Mar 2022 03:49 AM PDT

I have time like that in 24 hour format

Time a = 2315 which is string type and I want to subtract time b = 45 minute from it.

When I tried it I am getting invalid time error so I tried time a:='23:15' and time b :='00:45' (due to error I made it format like that otherwise 45 is in minute) result is 22:30 which is right

Time c:=(strtodatetime(a))-(strtodatetime(b));  

Output is 2230

Problem starts when a:=00:15 (midnight) and b:=00:45 (minutes).

My expected output should be 11:30 not 0030

I feel it happened due to date change.

Any other way to sort it?

ANSWERED: Linking SDL2 Libraries in CLion 2021.3.3 Windows CMAKE Visual Studio

Posted: 13 Mar 2022 03:49 AM PDT

I've poured over countless Q/A's and cannot get this to work.

I have:

1. The PATH Environment Variable pointing to the Folder where the .libs are -> System Path Variable (image)

2. Placed the SDL2.dll in my project folder with the main.cpp source

3. Copied the "SDL include headers" into the "VisualC include path

C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.31.31103\include

It compiles and runs through Visual Studio fine... If you could tell me what I'm missing here I'd be very thankful!

CMakeLists.txt:

cmake_minimum_required(VERSION 3.21)  project(HelloSDL VERSION 0.10)  set(CMAKE_CXX_STANDARD 14)  add_executable(HelloSDL main.cpp)  add_executable(main main.cpp)  target_link_libraries(HelloSDL SDL2.lib SDL2main.lib)  target_link_libraries(main SDL2.lib SDL2main.lib)  

Build, Execution, Deployment > CMake (Settings Dialog) image

main.cpp:

#include "SDL.h"  #include "stdio.h"    const int SCREEN_WIDTH = 640;  const int SCREEN_HEIGHT = 480;    int main( int argc, char* args[] ) {      //The window we'll be rendering to      SDL_Window *window = NULL;        //The surface contained by the window      SDL_Surface *screenSurface = NULL;        //Initialize SDL      if (SDL_Init(SDL_INIT_VIDEO) < 0) {          printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError());      } else {          //Create window          window = SDL_CreateWindow("SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH,                                    SCREEN_HEIGHT, SDL_WINDOW_SHOWN);          if (window == NULL) {              printf("Window could not be created! SDL_Error: %s\n", SDL_GetError());          } else {              //Get window surface              screenSurface = SDL_GetWindowSurface(window);                //Fill the surface white              SDL_FillRect(screenSurface, NULL, SDL_MapRGB(screenSurface->format, 0xFF, 0xFF, 0xFF));                //Update the surface              SDL_UpdateWindowSurface(window);                //Wait two seconds              SDL_Delay(2000);          }      }      //Destroy window      SDL_DestroyWindow(window);        //Quit SDL subsystems      SDL_Quit();        return 0;  }  

Now, it builds and compiles however, it is giving me garbage results...

Run Terminal Output (image)

Running the executable HelloSDL.exe it throws an Application Error Dialog box at me.

Application Error (image)

I can get it to run fine through Visual Studio 2022 however I prefer the CLion Editor and I've paid for it.

So if anyone can help get me building in CLion I would very much appreciate it!

Many Thanks in advance

React: fetch-mock: No fallback response defined for GET

Posted: 13 Mar 2022 03:49 AM PDT

I had recently given a HackerRank test. It had a react question, Please find the codesandbox to the solution. https://codesandbox.io/s/quizzical-carlos-k5i4en

My output is as expected in the question. However still my 3 test cases are failing, I am not able to figure out why.

My solution:

import React from "react";  import "./index.css";    export default function StockData() {          const [date, setDate] = React.useState('');    const [open, setOpen] = React.useState('');    const [close, setClose] = React.useState('');    const [high, setHigh] = React.useState('');    const [low, setLow] = React.useState('');    const [status, setStatus] = React.useState(-1);      const fetchData = () => {      const Url = 'https://jsonmock.hackerrank.com/api/stocks/?date=' + date;      fetch(Url)        .then(res => res.json())        .then((result) => {          if (result.data[0]) {            setStatus(1);            setOpen(result.data[0].open);            setClose(result.data[0].close);            setHigh(result.data[0].high);            setLow(result.data[0].low);          }          else {            setStatus(0)          }        }        )        .catch(error => setStatus(-1));    }      return (      <div className="layout-column align-items-center mt-50">        <section className="layout-row align-items-center justify-content-center">          <input            value={date}            onChange={(e) => setDate(e.target.value)}            type="text"            className="large"            placeholder="5-January-2000"            id="app-input"            data-testid="app-input" />          <button            onClick={fetchData}            className=""            id="submit-button"            data-testid="submit-button">Search</button>        </section>        {status == 1 &&          <ul className="mt-50 slide-up-fade-in styled" id="stockData" data-testid="stock-data">            <li className="py-10">Open: {open}</li>            <li className="py-10">Close: {close}</li>            <li className="py-10">High: {high}</li>            <li className="py-10">Low: {low}</li>          </ul>        }        {          status == 0 &&          <div className="mt-50 slide-up-fade-in" id="no-result" data-testid="no-result">No Results Found</div>        }      </div>    );  }  

Test Case:

test('search is made on by clicking on search button and result found - test 2', async () => {    let {getByTestId, queryByTestId} = renderApp();    let input = getByTestId('app-input');    let searchButton = getByTestId('submit-button');      const url = 'https://jsonmock.hackerrank.com/api/stocks?date=5-January-2001';    fetchMock.getOnce(url, JSON.stringify({      page: 1,      per_page: 10,      total: 0,      total_pages: 0,      data: [{"date": "5-January-2001", "open": 4116.34, "high": 4195.01, "low": 4115.35, "close": 4183.73}]    }));    fireEvent.input(input, {      target: {value: '5-January-2001'}    });    fireEvent.click(searchButton);  

Failing test case output:

  search is made on by clicking on search button and result found - test 1  fetch-mock: No fallback response defined for GET to https://jsonmock.hackerrank.com/api/stocks/?date=5-January-2000      16 |   const fetchData = () => {    17 |     const Url = 'https://jsonmock.hackerrank.com/api/stocks/?date=' + date;  > 18 |     fetch(Url)       |     ^    19 |       .then(res => res.json())    20 |       .then((result) => {    21 |         if (result.data[0]) {      at Object.<anonymous>.FetchMock.executeRouter (node_modules/fetch-mock/cjs/lib/fetch-handler.js:152:9)    at Object.fetch [as fetchHandler] (node_modules/fetch-mock/cjs/lib/fetch-handler.js:84:21)    at fetchData (src/components/stock-data/index.js:18:5)    at HTMLUnknownElement.callCallback (node_modules/react-dom/cjs/react-dom.development.js:188:14)    at Object.invokeGuardedCallbackDev (node_modules/react-dom/cjs/react-dom.development.js:237:16)    at invokeGuardedCallback (node_modules/react-dom/cjs/react-dom.development.js:292:31)    at invokeGuardedCallbackAndCatchFirstError (node_modules/react-dom/cjs/react-dom.development.js:306:25)    at executeDispatch (node_modules/react-dom/cjs/react-dom.development.js:389:3)    at executeDispatchesInOrder (node_modules/react-dom/cjs/react-dom.development.js:414:5)    at executeDispatchesAndRelease (node_modules/react-dom/cjs/react-dom.development.js:3278:5)    at executeDispatchesAndReleaseTopLevel (node_modules/react-dom/cjs/react-dom.development.js:3287:10)    at forEachAccumulated (node_modules/react-dom/cjs/react-dom.development.js:3259:8)    at runEventsInBatch (node_modules/react-dom/cjs/react-dom.development.js:3304:3)    at runExtractedPluginEventsInBatch (node_modules/react-dom/cjs/react-dom.development.js:3514:3)    at handleTopLevel (node_modules/react-dom/cjs/react-dom.development.js:3558:5)    at batchedEventUpdates$1 (node_modules/react-dom/cjs/react-dom.development.js:21871:12)    at batchedEventUpdates (node_modules/react-dom/cjs/react-dom.development.js:795:12)    at dispatchEventForLegacyPluginEventSystem (node_modules/react-dom/cjs/react-dom.development.js:3568:5)    at attemptToDispatchEvent (node_modules/react-dom/cjs/react-dom.development.js:4267:5)    at dispatchEvent (node_modules/react-dom/cjs/react-dom.development.js:4189:19)    at unstable_runWithPriority (node_modules/scheduler/cjs/scheduler.development.js:653:12)    at runWithPriority$1 (node_modules/react-dom/cjs/react-dom.development.js:11039:10)    at discreteUpdates$1 (node_modules/react-dom/cjs/react-dom.development.js:21887:12)    at discreteUpdates (node_modules/react-dom/cjs/react-dom.development.js:806:12)    at dispatchDiscreteEvent (node_modules/react-dom/cjs/react-dom.development.js:4168:3)    at node_modules/@testing-library/dom/dist/events.js:25:20    at node_modules/@testing-library/react/dist/pure.js:65:16    at batchedUpdates$1 (node_modules/react-dom/cjs/react-dom.development.js:21856:12)    at act (node_modules/react-dom/cjs/react-dom-test-utils.development.js:929:14)    at Object.eventWrapper (node_modules/@testing-library/react/dist/pure.js:64:28)    at fireEvent (node_modules/@testing-library/dom/dist/events.js:16:35)    at Function.fireEvent.<computed> [as click] (node_modules/@testing-library/dom/dist/events.js:124:36)    at Function.click (node_modules/@testing-library/react/dist/fire-event.js:18:52)    at Object.<anonymous> (src/App.test.js:57:13)  

Please run npm install, npm start, npm test for corresponding outputs.

Remove word from string with one condition

Posted: 13 Mar 2022 03:49 AM PDT

If match part of word in string, how to remove that entire word?

  • Input: "This is a beautiful text in string."
  • Rule: If in string exist "autif", then delete "beautiful"
  • Result: "This is a text in string."

C program to traverse a singly linked lisk

Posted: 13 Mar 2022 03:48 AM PDT

I have written a C program to implement the concept of traversing a singly linked list. The program first creats the list by asking for the user input and then displays/ traverses through the created list. When i run this code, it sucessfully creates the linked list, but on displaying the created list, it produces an infinite loop. `

#include<stdio.h>  #include<stdlib.h>  struct node{      int data;      struct node *next;  } *head;    int main(){      struct node *newNode, *temp;      int n;      printf("Enter number of Nodes: ");      scanf("%d",&n);      head = (struct node *)malloc(sizeof(struct node));      if(head == NULL){          printf("No Memory Allocation");          exit(0);          }          else{              printf("Node Data 1: ");              scanf("%d",&head -> data);              head -> next = NULL;              temp = head;              }      newNode = (struct node *)malloc(sizeof(struct node));      if(newNode == NULL){          printf("No Memory Allocation");          exit(0);          }          else{          for(int i = 2; i <= n; ++i){              printf("Node Data %d: ",i);              scanf("%d",&newNode -> data);              newnode -> next = NULL;               temp -> next = newnode;                temp = temp -> next;                            }          }                //Traversal                 struct node *ptr;               ptr = head;             if(ptr == NULL)            {                printf("Empty list..");            }            else            {                 while (ptr != NULL){                    printf("\n%d",ptr->data);                    ptr = ptr -> next;                }            }                  return 0;  }`   

how to match the keys of a dictionary and return their values?

Posted: 13 Mar 2022 03:50 AM PDT

I have two dictionaries:

x= {'албански': 'Albanian', 'елзаски': 'Alsatian', 'арагонски': 'Aragonese',   'арберешки': 'Arberesh'}    y={'елзаски': 477, 'арагонски': 0, 'арберешки': 1,'албански': 1}  

Both dictionaries contains the same amount of key_value pairs. In dictionary x, the key is the translation in Bulgarian of names of languages and the values are the names of the same languages in English.

in dictionary y, the keys are the name of the languages in Bulgarian and the values are their frequency counts.

All languages present in Dic x are present in dic y, but they are in different orders.

What I need to do is to return the names of the languages in English and their corresponding counts. For this I first need to search for the keys in dic x in dic y and when they match return the values in x and values in y. How to do this?

I have tried the following code, but does not work and even if it worked I think I would not get what I need.

x=dict(zip(lang_lists['languages_bulgarian'],lang_lists['languages_english']))  y=dict(zip(lang_lists['report_lang_list'], lang_lists['counts']))    for i in x:    for j in y:      if j == y:        print(x[i], y[j])      else:        pass  

My idea was to search the corresponding keys between the two dictionarys and when they match return the values of one dictionary (languages in English) and the values in the other dictionary (frequency counts). my desired output is something like:

{Albanian: 1, Aragonese: 0, Arberesh: 1, Alsatian: 477}  

Values in a dataframe column will not change

Posted: 13 Mar 2022 03:48 AM PDT

I have a data frame where I want to replace the values '<=50K' and '>50K' in the 'Salary' column with '0' and '1' respectively. I have tried the replace function but it does not change anything. I have tried a lot of things but nothing seems to work. I am trying to do some logistic regression on the cells but the formulas do not work because of the datatype. The real data set has over 20,000 rows.

Age   Workclass   fnlwgt  education   education-num   Salary   39  state-gov    455    Bachelors      13            <=50K   25   private     22      Masters       89             >50K  
df['Salary']= df['Salary'].replace(['<=50K'],'0')  df['Salary']  

This is the error i get when i try to do smf.logit(). See below code. I don't understand why i get an error because Age and education-num are both int64.

mod = smf.logit(formula = 'education-num ~ Age', data= dftrn)    resmod = modelAdm.fit()  

ValueError: endog has evaluated to an array with multiple columns that has shape (26049, 16). This occurs when the variable converted to endog is non-numeric (e.g., bool or str).

How can I add automatic marking to my text redactor in python?

Posted: 13 Mar 2022 03:50 AM PDT

I want to create a function, which will help me redacting game scripts. For example, I need to mark tags (e.g. "<p>", "<b>" etc.). I create a button, which calls a Mark function, and that Mark function calls other functions, e.g. person. But everything I tried didn't work for me. What should I do? My code:

from tkinter import *  import tkinter.filedialog   #модуль filedialog для диалогов открытия/закрытия файла    def Mark():      person.start()    def person():      personlabel = Label(text="<p>", bg="red")      text.window_create(INSERT, window=personlabel)    def Quit(ev):      global root      root.destroy()        def LoadFile(ev):      ftypes = [('Все файлы', '*'), ('txt файлы', '*.txt'), ('Файлы Python', '*.py'), ('Файлы html', '*.html')] # Фильтр файлов      fn = tkinter.filedialog.Open(root, filetypes = ftypes).show()            if fn == '':          return      textbox.delete('1.0', 'end')    # Очищаем окно редактирования      textbox.insert('1.0', open(fn).read())   # Вставляем текст в окно редактирования             global cur_path      cur_path = fn # Храним путь к открытому файлу       def SaveFile(ev):      fn = tkinter.filedialog.SaveAs(root, filetypes = [('Все файлы', '*'), ('txt файлы', '*.txt'), ('Файлы Python', '*.py'), ('Файлы html', '*.html')]).show()      if fn == '':          return      open(fn, 'wt').write(textbox.get('1.0', 'end'))    root = Tk()   # объект окна верхнего уровня создается от класса Tk модуля tkinter.   #Переменную, связываемую с объектом, часто называют root (корень)              root.title(u'AA1 scripts redactor')      panelFrame = Frame(root, height = 60, bg = 'gray')  textFrame = Frame(root, height = 340, width = 600)    panelFrame.pack(side = 'top', fill = 'x')   #упакуем с привязкой к верху  textFrame.pack(side = 'bottom', fill = 'both', expand = 1)      textbox = Text(textFrame, font='Arial 14', wrap='word')  #перенос по словам метод wrap  scrollbar = Scrollbar(textFrame)    scrollbar['command'] = textbox.yview  textbox['yscrollcommand'] = scrollbar.set    textbox.pack(side = 'left', fill = 'both', expand = 1)  #текстбокс слева  scrollbar.pack(side = 'right', fill = 'y')    #расположим скролбар (лифт) справа    loadBtn = Button(panelFrame, text = 'Load')  saveBtn = Button(panelFrame, text = 'Save')  markBtn = Button(panelFrame, text = 'Mark')  quitBtn = Button(panelFrame, text = 'Quit', bg='#A9A9A9',fg='#FF0000')    markBtn.bind("<Button-1>", Mark)  loadBtn.bind("<Button-1>", LoadFile)  saveBtn.bind("<Button-1>", SaveFile)  quitBtn.bind("<Button-1>", Quit)    loadBtn.place(x = 10, y = 10, width = 130, height = 40)  saveBtn.place(x = 150, y = 10, width = 130, height = 40)  markBtn.place(x = 290, y = 10, width = 100, height = 40)  quitBtn.place(x = 430, y = 10, width = 100, height = 40)    root.mainloop()  

UPD: Python everytime gives me an error "TypeError: [function]() takes 0 positional arguments but 1 was given".

Find value unequal to any value from a given set of distinct values at compile time

Posted: 13 Mar 2022 03:48 AM PDT

Question: how to implement a macro E that expands to an integer constant expression such that ...

(E != (X) && E != (Y) && E != (Z))  

... evaluates to 1 for every choice of X, Y, and Z as integer constant expressions with distinct, nonnegative values?

Example:

#define X               13  #define Y               45  #define Z               76  #define E               FUNC(X,Y,Z)  #define FUNC(X,Y,Z)     ??    E /* evaluates to any number distinct from all of 13, 45, and 76 */  

Which formula to use? Any ideas?

Airflow how to import python script?

Posted: 13 Mar 2022 03:50 AM PDT

I have a file survey_monkey.py and a directory surveymonkey in the dag folder. There is a python script named surveys.py in the directory surveymonkey.

from surveys import Surveys    # defining DAG arguments    # You can override them on a per-task basis during operator initialization  default_args = {      'owner': 'survey_monkey',      'start_date': days_ago(0),      'email': ['xxxx@xxxx.com'],      'email_on_failure': False,      'email_on_retry': False,      'retries': 1,      'retry_delay': timedelta(minutes=5),  }  

This givs me an error saying

Broken DAG: [/home/ubuntu/airflow/dags/survey_tools/survey_monkey.py] Traceback (most recent call last):    File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed    File "/home/ubuntu/airflow/dags/survey_tools/survey_monkey.py", line 11, in <module>      from surveys import Surveys  ModuleNotFoundError: No module named 'surveys'  

How can I fix it?

Select total hours of first-in and last out in 1 day. then total hours in next day should count. to sum total hours in multiple days

Posted: 13 Mar 2022 03:50 AM PDT

How to code a query i need to show total hours of one day from first-in to last-out. then total hours for next day.

For example I in (2022-02-01 07:39:12) then i out 2022-02-01 19:39:12 So its 13. hrs in 1 day.

Then next day in 2022-02-02 09:00:12, out 2022-02-02 19:00:12 12 and its 11 hrs.

So Total hours would be 24hrs.

[EmployeeID]   [Att_Date]   11            2022-02-01 07:39:12   11            2022-02-01 19:39:12   11            2022-02-02 09:00:12   11            2022-02-02 19:00:12   33            2022-02-03 08:00:12   33            2022-02-03 19:00:12   33            2022-02-04 08:00:12   33            2022-02-04 19:39:12...  

I tried this code below but wrong result, it just minus/subract from first-in of day 1 to last in of day 2.

SELECT EmployeeID,   TIMESTAMPDIFF(hour, MIN(Att_Date),MAX(Att_Date)) AS Total_Hours  FROM att_details   GROUP BY EmployeeID  

enter image description here

Shadow DOM innerHTML with slots replaced by assignedNodes()

Posted: 13 Mar 2022 03:50 AM PDT

I'm working with a customElement using Shadow DOM like:

<hello-there><b>S</b>amantha</hello-there>  

And the innerHTML (generated by lit/lit-element in my case) is something like:

<span>Hello <slot></slot>!</span>  

I know that if const ht = document.querySelector('hello-there') I can call .innerHTML and get <b>S</b>amantha and on the shadowRoot for ht, I can call .innerHTML Hello !`. But...

The browser essentially renders the equivalent of <span>Hello <b>S</b>amantha!</span>. Is there a way to get this output besides walking all the .assignedNodes, and substituting the slot contents for the slots? Something like .slotRenderedInnerHTML?

(update: I have now written code that does walk the assignedNodes and does what I want, but it seems brittle and slow compared to a browser-native solution.)

class HelloThere extends HTMLElement {     constructor() {        super();        const shadow = this.attachShadow({mode: 'open'});        shadow.innerHTML = '<span>Hello <slot></slot>!</span>';     }  }    customElements.define('hello-there', HelloThere);
<hello-there><b>S</b>amantha</hello-there>  <div>Output: <input type="text" size="200" id="output"></input></div>  <script>  const ht = document.querySelector('hello-there');  const out = document.querySelector('#output');    </script>  <button onclick="out.value = ht.innerHTML">InnerHTML hello-there</button><br>  <button onclick="out.value = ht.outerHTML">OuterHTML hello-there</button><br>  <button onclick="out.value = ht.shadowRoot.innerHTML">InnerHTML hello-there shadow</button><br>  <button onclick="out.value = ht.shadowRoot.outerHTML">OuterHTML hello-there shadow (property does not exist)</button><br>  <button onclick="out.value = '<span>Hello <b>S</b>amantha!</span>'">Desired output</button>

Buttons that change the default order of items. How can this work?

Posted: 13 Mar 2022 03:49 AM PDT

I am trying to make these two buttons in the index.html to function.

<div class="align-buttons">      <a class="btn btn-primary btn-sm mt-1 mb-1" href="{{ url_for('root', ordering_by='rating') }}">Ordering by rating</a>      <a class="btn btn-primary btn-sm mt-1 mb-1" href="{{ url_for('root', ordering_by='release_year') }}">Ordering by release year</a>  </div>`   

What changes do I have to make? The default ordering is date_created and I need ordering_by=rating and ordering_by=release_year.

    @app.route("/home/")      @app.route("/")      def root():              page = request.args.get('page', 1, type=int)          movies = Movie.query.order_by(Movie.date_created.desc()).paginate(per_page=5, page=page)          return render_template("index.html", movies=movies)`   

chalk - Error [ERR_REQUIRE_ESM]: require() of ES Module

Posted: 13 Mar 2022 03:49 AM PDT

Hi tried to install chalk on my very simple app and then i got error:

Error [ERR_REQUIRE_ESM]: require() of ES Module my-file-is-here  and chalk\node_modules\chalk\source\index.js from my-file-is-here not supported.  Instead change the require of index.js in my-file-is-here to a dynamic import() which is available in all CommonJS modules.      at Object.<anonymous> (`my-file-is-here`) {    code: 'ERR_REQUIRE_ESM'  }  

thats my code:

const os = require("os")  const chalk = require("chalk")    console.log("app running")  

contextBridge.exposeInMainWorld and IPC with Typescript in Electron app: Cannot read property 'send' of undefined

Posted: 13 Mar 2022 03:49 AM PDT

I defined contextBridge ( https://www.electronjs.org/docs/all#contextbridge ) in preload.js as follows:

const {    contextBridge,    ipcRenderer  } = require("electron")    contextBridge.exposeInMainWorld(    "api", {        send: (channel, data) => {            ipcRenderer.invoke(channel, data).catch(e => console.log(e))        },        receive: (channel, func) => {          console.log("preload-receive called. args: ");          ipcRenderer.on(channel, (event, ...args) => func(...args));        },        // https://www.electronjs.org/docs/all#ipcrenderersendtowebcontentsid-channel-args        electronIpcSendTo: (window_id: string, channel: string, ...arg: any) => {          ipcRenderer.sendTo(window_id, channel, arg);        },        // https://github.com/frederiksen/angular-electron-boilerplate/blob/master/src/preload  /preload.ts        electronIpcSend: (channel: string, ...arg: any) => {          ipcRenderer.send(channel, arg);        },        electronIpcSendSync: (channel: string, ...arg: any) => {          return ipcRenderer.sendSync(channel, arg);        },        electronIpcOn: (channel: string, listener: (event: any, ...arg: any) => void) => {          ipcRenderer.on(channel, listener);        },        electronIpcOnce: (channel: string, listener: (event: any, ...arg: any) => void) => {          ipcRenderer.once(channel, listener);        },        electronIpcRemoveListener:  (channel: string, listener: (event: any, ...arg: any) =>   void) => {          ipcRenderer.removeListener(channel, listener);        },        electronIpcRemoveAllListeners: (channel: string) => {          ipcRenderer.removeAllListeners(channel);        }    }  )  

I defined a global.ts :

export {}  declare global {    interface Window {      "api": {        send: (channel: string, ...arg: any) => void;        receive: (channel: string, func: (event: any, ...arg: any) => void) => void;        // https://github.com/frederiksen/angular-electron-boilerplate/blob/master/src/preload  /preload.ts        // https://www.electronjs.org/docs/all#ipcrenderersendtowebcontentsid-channel-args        electronIpcSendTo: (window_id: string, channel: string, ...arg: any) => void;        electronIpcSend: (channel: string, ...arg: any) => void;        electronIpcOn: (channel: string, listener: (event: any, ...arg: any) => void) => void;        electronIpcSendSync: (channel: string, ...arg: any) => void;        electronIpcOnce: (channel: string, listener: (event: any, ...arg: any) => void) =>   void;        electronIpcRemoveListener:  (channel: string, listener: (event: any, ...arg: any) =>   void) => void;        electronIpcRemoveAllListeners: (channel: string) => void;      }    }  }  

and in the renderer process App.tsx I call window.api.send :

window.api.send('open-type-A-window', '');   

The typescript compilation looks fine:

yarn run dev  yarn run v1.22.5   $ yarn run tsc && rimraf dist && cross-env NODE_ENV=development webpack --watch --progress   --color  $ tsc  95% emitting emit(node:18180) [DEP_WEBPACK_COMPILATION_ASSETS] DeprecationWarning:        Compilation.assets will be frozen in future, all modifications are deprecated.    BREAKING CHANGE: No more changes should happen to Compilation.assets after sealing the   Compilation.      Do changes to assets earlier, e. g. in Compilation.hooks.processAssets.      Make sure to select an appropriate stage from Compilation.PROCESS_ASSETS_STAGE_*.  (Use `node --trace-deprecation ...` to show where the warning was created)  asset main.bundle.js 32.6 KiB [emitted] (name: main) 1 related asset  asset package.json 632 bytes [emitted] [from: package.json] [copied]  cacheable modules 26.2 KiB    modules by path ./node_modules/electron-squirrel-startup/ 18.7 KiB      modules by path ./node_modules/electron-squirrel-startup/node_modules/debug/src/*.js 15   KiB 4 modules      ./node_modules/electron-squirrel-startup/index.js 1 KiB [built] [code generated]      ./node_modules/electron-squirrel-startup/node_modules/ms/index.js 2.7 KiB [built] [code   generated]    ./src/main/main.ts 6.82 KiB [built] [code generated]    ./node_modules/file-url/index.js 684 bytes [built] [code generated]  external "path" 42 bytes [built] [code generated]  external "url" 42 bytes [built] [code generated]  external "electron" 42 bytes [built] [code generated]  external "child_process" 42 bytes [built] [code generated]  external "tty" 42 bytes [built] [code generated]  external "util" 42 bytes [built] [code generated]  external "fs" 42 bytes [built] [code generated]  external "net" 42 bytes [built] [code generated]  webpack 5.21.2 compiled successfully in 4313 ms    asset renderer.bundle.js 1000 KiB [emitted] (name: main) 1 related asset  asset index.html 196 bytes [emitted]  runtime modules 937 bytes 4 modules  modules by path ./node_modules/ 990 KiB    modules by path ./node_modules/scheduler/ 31.8 KiB 4 modules    modules by path ./node_modules/react/ 70.6 KiB 2 modules    modules by path ./node_modules/react-dom/ 875 KiB 2 modules    modules by path ./node_modules/css-loader/dist/runtime/*.js 3.78 KiB 2 modules    ./node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js 6.67 KiB [built]   [code generated]    ./node_modules/object-assign/index.js 2.06 KiB [built] [code generated]  modules by path ./src/ 5 KiB    modules by path ./src/app/styles/*.less 3.16 KiB      ./src/app/styles/index.less 385 bytes [built] [code generated]      ./node_modules/css-loader/dist/cjs.js!./node_modules/less-loader/dist/cjs.js!./src/app  /styles/index.less 2.78 KiB [built] [code generated]    ./src/renderer/renderer.tsx 373 bytes [built] [code generated]    ./src/app/components/App.tsx 1.48 KiB [built] [code generated]  webpack 5.21.2 compiled successfully in 4039 ms  

But I get Cannot read property 'send' of undefined

enter image description here

If I set in App.tsx :

const sendProxy = window.api.send;  

I get the same error and the window is not rendered :

enter image description here

What am I doing wrongly with Typescript and with Electron IPC? Looking forward to your kind help

How can I convert Long[] to IEnumerable<long?>

Posted: 13 Mar 2022 03:49 AM PDT

I am getting an exception of

Cannot implicitly convert type 'long[]' to 'System.Collections.Generic.IEnumerable<long?>'

How can I resolve this issue?

I have tried this but doesnot work.

the AssignedPlayerSites is an IList property.

IEnumerable<long?> multipleSelectedSites = cmsUser.AssignedPlayerSites.Select(ps => ps.Id).AsEnumerable<long?>();  

is there a function in dlg class as getdocument()?

Posted: 13 Mar 2022 03:49 AM PDT

I want to get a doc* in dlg class, and i know in view class we can get doc* like

doc* pdc=getdocument();  

But how can i do it in dlg class?

No comments:

Post a Comment