2020-11-30

How to execute a Cloud Function after Dataflow job has succeeded?

I want to trigger Cloud Function only if Dataflow job execution completed successfully.

Cloud Function should not be triggered if Dataflow job is failed.

I am running a Dataflow job using a Dataflow template (jdbc to BigQuery) from the the Dataflow UI.

There is no option to trigger any Cloud Function or something after job execution. Also, I can't make changes in template code. What's the way to trigger Cloud Function?



from Recent Questions - Stack Overflow https://ift.tt/2KGD9KP
https://ift.tt/eA8V8J

How can you optimize linear search if applied on an ordered list of items?

In an unordered list of items, you must check every item until you find a match. How can you optimize linear search if applied on an ordered list of items?



from Recent Questions - Stack Overflow https://ift.tt/39etKoe
https://ift.tt/eA8V8J

How to install Azul JDK 16 on Apple Silicon M1 Mac?

I understand I can run Java under emulation with Rosetta 2, but I've read that with Azul Open JDK 16 that I can get native performance.

I downloaded the file, but have no idea what to do. Azul's help page is not helpful.

If someone can give some basic steps on how to get the JDK running natively that would be awesome!



from Recent Questions - Stack Overflow https://ift.tt/37hmxRv
https://ift.tt/eA8V8J

How can I get the boundaries of a regular expression?

Lets say I have a string that I need to split into an array based on a pattern. Many language split methods will remove the things matched by the pattern causing a split of a string

testtestt

on the regular expression

.{2}

ending up with a result of

t

This is not the result I wanted so how can I use a regular expression only to capture the borders of what is matched with the same scenario above being matched as

te|st|te|st|t

and as a result being split into an array of

['te','st','te','st','t']

?

Note: This is not language specific and the ideal answer would be a regular expression instead of a piece of code exclusive to certain languages.



from Recent Questions - Stack Overflow https://ift.tt/2Jby6lv
https://ift.tt/eA8V8J

Understanding Types Merging in The Typescript

I am new to typescript and I have seen in many projects they are using the following type

  1. TypeA | TypeB
  2. TypeA & TypeB
  3. TypeA | (TypeB & TypeC) | TypeD
  4. (TypeA | TypeB)[]

What is difference between each of them. Also please share the documentation link for further reference

Also please let me know what this technique actually called in typescript



from Recent Questions - Stack Overflow https://ift.tt/36i14Zq
https://ift.tt/eA8V8J

What status should I use for Sentry performance in case of System Exception?

Testing bot 123. what performance status should I use for System Exceptions? so far I am only aware of HTTP request status.



from Recent Questions - Stack Overflow https://ift.tt/2VdcnvE
https://ift.tt/eA8V8J

how change date weekly

I am trying to use this code (Change week in a calendar when a button is clicked) to display the date of a whole week from Sunday to Saturday. But the problem is that for example November 2020 ends on the 30th, but the script continues to count 31, 32, 33, 34, 35 ..

 function renderCalender(d){
          let t = d.getDay();
             let weekday = document.querySelectorAll(".weekday");
             for (let i = 0, j = 1; i < weekday.length; i++) {
                 let x = t-i;
                 if (t > i) {
                     weekday[i].innerHTML = `${d.getMonth()+1}/${d.getDate()-x}/${d.getFullYear()}`;
                 } else if (t < i) {
                     weekday[i].innerHTML = `${d.getMonth()+1}/${d.getDate()+j}/${d.getFullYear()}`;
                     j++
                 } else if (t === i) {
                     weekday[i].parentNode.style.backgroundColor = "rgb(100, 100, 100)";
                     weekday[i].innerHTML = `${d.getMonth()+1}/${d.getDate()}/${d.getFullYear()}`;
                 }
             }
             }



             function changeForm (form) {
                 let otherForms = document.querySelectorAll(".inquiry-selection-active");
                 for (let i = 0; i < otherForms.length; i++) {
                     otherForms[i].className = "inquiry-selection";
                 }

                 let commissionForm = document.getElementById(`${form.value}`);
                 commissionForm.className = 'inquiry-selection-active';
             }

             function nextWeek(){
             var currentDate = new Date()
             currentDate.setTime(currentDate.getTime()+7*24*60*60*1000); //append date with 7 days and pass to render function
             renderCalender(currentDate);
             }
             renderCalender(new Date());
<div id="wrapper">
         <div id="est-finish-dates">
            <table>
               <tr>
                  <th>Sunday<br/>(<span class="weekday"></span>)</th>
                  <th>Monday<br/>(<span class="weekday"></span>)</th>
                  <th>Tuesday<br/>(<span class="weekday"></span>)</th>
                  <th>Wednesday<br/>(<span class="weekday"></span>)</th>
                  <th>Thursday<br/>(<span class="weekday"></span>)</th>
                  <th>Friday<br/>(<span class="weekday"></span>)</th>
                  <th>Saturday<br/>(<span class="weekday"></span>)</th>
               </tr>
            </table>
         </div>
      </div>

any ideas you give me?



from Recent Questions - Stack Overflow https://ift.tt/2HQ65iB
https://ift.tt/eA8V8J

How to make pictures from database clickable with different HTML?

i have this code:

<a href="produkt1.html"><img style="margin-left:30px;" src="<?= $row['zdjecie_produktu'] ?>" class="card-img-top" height="250"></a>

But i want each picture to be linked with different HTML (in this case with picture of the product with its’ description)... is there any code for that?



from Recent Questions - Stack Overflow https://ift.tt/3fM6a3c
https://ift.tt/eA8V8J

Create new VSCode C++ project folder: via Developer Command Prompt or GUI?

I'm new to VSCode and had a question about creating your project folder. This vscode site resource teaches you to create the project via DevCMD. I can't tell what the difference is with creating the folder in your OS (Windows) and then opening the folder as a project via the VSC GUI, but the latter doesn't work. Can you tell me why?

P.S., I'm relearning C++ and would like to find a place, chatroom, forum, where I can ask stupid questiolns until I've learned the fundamentals again. If you have any recommendations I'd appreciate a message.



from Recent Questions - Stack Overflow https://ift.tt/36hPoFZ
https://ift.tt/eA8V8J

Powershell Import/Export-csv group & join cells

I have a csv file which I need to group and join various cells together and have them then separated by a semi-colon in the csv layout is as such

CSV Layout

I have managed to join the cells 'price' & 'functionnumber' together and separate them with a ';' but for 'datedespatched' and 'username' which just need to display the 1 name or date the cells return with 'System.Object[]' displayed in the condensed cell, the 'referencenumber' cell appears to condense down fine. This is my current code and the output I receive from it

 Import-Csv 'C:\temp\test.csv' | Group-Object ReferenceNumber |ForEach-Object {
 
 [PsCustomObject]@{

        ReferenceNumber = $_.Name

        userName = $_.Group.userName

        DateDespatched = $_.Group.DateDespatched 

        functionnumber = $_.Group.functionnumber -join '; '

        Price = $_.Group.Price -join '; '
        
        }
 } | Export-Csv 'C:\temp\test-export.csv' -NoTypeInformation 
 

Code-output

Thank you in advance



from Recent Questions - Stack Overflow https://ift.tt/2HNLPho
https://ift.tt/eA8V8J

I want to design chat application using firebase firestore as Database with chat bubble message

I really want to create a firebase firestore chat application in Android in which i want to show the message in a chat bubble which inflate Google sign in (i know Google sign in procedure) but i am not able to sort our messages according to time when they created



from Recent Questions - Stack Overflow https://ift.tt/3okbuOD
https://ift.tt/eA8V8J

update table mariadb from bash script

Trying to write an table update statement in my bash script but gives me a syntax error mysql Ver 15.1 Distrib 5.5.68-MariaDB, for Linux (x86_64) using readline 5.1

mysql -u UserName --password=MyPassword -D MyDatabase -e 'UPDATE MyTable SET name = SomeName WHERE number = someNumber ;'

ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SomeName WHERE number = someNumber' at line 1



from Recent Questions - Stack Overflow https://ift.tt/3mkZknH
https://ift.tt/eA8V8J

I have a segmentation fault in c++, where did I go wrong?

Trying to traverse a 2d vector in order to find index(es) of a certain key value which is the number 1. I looked up what a segmentation fault was and it said that it happens when you try to access too much memory, but I don't get how I'm doing that.

#include<iostream>
#include<algorithm>
#include <vector>
#include <cmath>

using namespace std;
int main(){
    vector<vector<int>> matrix;
    int n;
    int i = 0;
    int j = 0;
    for (int i =0; i<5; i++){
        for (int z = 0; z<5; z++){
            cin >> n;
            matrix[i][z] = n;
        }

    }
    while (matrix[i][j] != 1 && ((i && j) < matrix.size())){
        while (i != 5){
            i++;
            while (j != 5){
                j++;
            }
        }

    }
    cout << abs((2-j) + (2-i)) << endl;


}


from Recent Questions - Stack Overflow https://ift.tt/33nRHWn
https://ift.tt/eA8V8J

What is the difference between key and id in React component?

I have this in the parent component.

          <RefreshSelect
            isMulti
            cacheOptions
            id='a'
            key = 'a'
            components={makeAnimated()}
            options={this.state['filter']['provider']}
            onChange={this.handleChangeProvider}
          />
          <RefreshSelect
            isMulti
            cacheOptions
            id='b'
            key='b'
            components={makeAnimated()}
            options={this.state['filter']['provider']}
            onChange={this.handleChangeProvider}
          />

In the definition of this child component, I have the constructor that updates default values depending on the id/key.

export default class RefreshSelect extends Component {
  constructor(props) {
    super(props);
    // console.log(props)
    // console.log(props.key)
    if (props.key==''){
      this.state = { value: [{ value: 'all', label: 'all', color: '#666666' }] };
    }else if ( props.key=='a') {
      this.state = { value: [{ value: '123', label: '123', color: '#666666' },
      { value: '234', label: '234', color: '#666666' },
      { value: '456', label: '456', color: '#666666' }] };
    }else {
      this.state = { value: [{ value: 'nvnvnvnvn', label: 'ksksksksks', color: '#666666' }] };
    }
  }

  render() {
    console.log(this.props)
    return (
      <Select
        isMulti
        defaultValue={this.state.value}
        options={this.props.options}
        components={makeAnimated()}
        placeholder={this.props.label}
        onChange={this.props.onChange}
      />
    );
  }
}


First, it looks like I'm not able to assign the key and access it in the constructor. Why is that? Secondly, what is the difference between id and key? Which one should I use and when?



from Recent Questions - Stack Overflow https://ift.tt/3loSqMV
https://ift.tt/eA8V8J

Why is my recursive prolog script not working?

Can anyone help me out with Prolog recursive functions?

I have to type in a recursive input and it should give me true, but it gives me an error and I sitll don´t know how to figure it out

Bob(Food(X)):- Bob(X).
Bob(eat(X)):- Bob(X).
Bob(yummy(X)).

Is what I have and Input Food(Food(eat(yummy)))should result in true

But I get an Error: Unknown procedure: Food/1 (DWIM could not correct goal) this is basically the whole story.



from Recent Questions - Stack Overflow https://ift.tt/3fLUU7b
https://ift.tt/eA8V8J

Uninitialized local variable c4700

https://www.programiz.com/cpp-programming/structure-function

I'm learning how to pass structures to functions using the website above, I spent 2 hours of trying to figure out what was wrong with my program, I decided to copy and paste the code on the website to see if they did it correctly and the same error came up. If anyone could help it would be appreciated, there code below.

Warning C6001 Using uninitialized memory 'p'. Structure-Function C:\DEV\C++\Structure-Function\Structure-Function\main.cpp 18

Error C4700 uninitialized local variable 'p' used Structure-Function C:\DEV\C++\Structure-Function\Structure-Function\main.cpp 18

#include <iostream>
using namespace std;

struct Person {
    char name[50];
    int age;
    float salary;
};

Person getData(Person); 
void displayData(Person); 

int main()
{

    Person p;

    p = getData(p);   
    displayData(p);

    return 0;
}

Person getData(Person p) {

    cout << "Enter Full name: ";
    cin.get(p.name, 50);

    cout << "Enter age: ";
    cin >> p.age;

    cout << "Enter salary: ";
    cin >> p.salary;

    return p;
}

void displayData(Person p)
{
    cout << "\nDisplaying Information." << endl;
    cout << "Name: " << p.name << endl;
    cout <<"Age: " << p.age << endl;
    cout << "Salary: " << p.salary;
}


from Recent Questions - Stack Overflow https://ift.tt/36lTBZA
https://ift.tt/eA8V8J

How do I fix the input prompt in this C code?

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <memory.h>
#include <ctype.h>
#include <time.h>

struct customer
{
    char name[45];
    char invoice[4];
    char service[2];
    char carNo[16];
    char fee[3];
    bool urgent;
    time_t date;
};

/*********************************************************************************************/
void toFile(char*); // will pass string (char*) to it and it'll write it to record.txt - DONE
void displayMenu(void);      // will display the menu  - DONE
void newInvoice(int invoiceNo);
/*********************************************************************************************/
int main()
{
    char toContinue;
    int invoiceNo =1;
    // format of invoices in txt file
    do
    {
        newInvoice(invoiceNo);
        invoiceNo += 1;
        // asking if user wants to continue to another order or close the program
        printf("Do you want to continue?  (Y or N) :");
        scanf(" %c",&toContinue);
    }
    while (toContinue !='N' && toContinue !='n');
    return 0;
}
/*********************************************************************************************/
void newInvoice(int invoiceNo)
{
    // variable declaration
    char enter,urgentCH;
    int feeINT;
    struct customer *newCus;
    newCus = (struct customer*) malloc ( sizeof(struct customer));
    displayMenu();
    enter = fgetc(stdin);
        sprintf(newCus->invoice, "%d", invoiceNo);
        // customer info being collected
        printf("Customer Name:\n");
        scanf("%[^\n]%*c", newCus->name);
    
        printf("Vehicle Numb :\n");
        scanf("%[^\n]%*c", newCus->carNo);
    
        printf("Service Selection Numb (From Menu):\n");
        scanf("%[^\n]%*c", newCus->service);
    
        printf("Urgent? (Y or N ):\n");
        scanf(" %c",&urgentCH);
        
        if(urgentCH == 'Y' || urgentCH == 'y')
            newCus->urgent = true;
        else
            newCus->urgent = false;
        
        printf("Fee (from menu):");
        scanf("%d",&feeINT);
        sprintf(newCus->fee, "%d", feeINT);
        time(&newCus->date); // system date and time being taken
        
        // writng to file
        toFile("Invoice:\t");
        toFile(newCus->invoice);
        toFile("  customer: ");
        toFile(newCus->name);
        toFile("  vehicle: ");
        toFile(newCus->carNo);
        toFile("  service: ");
        toFile(newCus->service);
        toFile("  type: ");
        if(newCus->urgent)
            toFile("urgent");
        else
            toFile("normal");
        toFile("  fee: ");
        toFile(newCus->fee);
        toFile("  date: ");
        toFile(ctime(&newCus->date));
        // invoice output
        printf("Customer:%s\n  vehicle:%s\n  Service:%s\n  type:%s\n  Fee:%s\n  Date:%s\n",
        newCus->name,newCus->carNo,newCus->service,newCus->urgent?"urgent":"normal",newCus->fee,ctime(&newCus->date));
    free(newCus);
}


/*********************************************************************************************/
void displayMenu()
{
    printf("Numb      Service type                           Time           service fee\n");
    printf("                                         (minutes)      Normal   Urgent\n");
    printf("1       Repair punctured car tyre/piece         10             5        6\n");
    printf("2       Car tyre change /piece                  15           150      160\n");
    printf("3       Mineral Oil Change                      20            80       90\n");
    printf("4       Synthetic Oil Change                    10           130      140\n");
    printf("5       Battery Change                           5           200      210\n");
    printf("6       Head light bulb change /piece            5             6        8\n");
    printf("7       Taillight bulb change /piece             5             6        8\n");
    printf("8       Car Wash                                10            10       12\n");
    printf("------------PRESS ANYTHING TO CONTINUE------------\n");
}
/*********************************************************************************************/
void toFile(char* Str2Write)
{
    // file opened for writing
    FILE *file2write;
    file2write = fopen("file.txt","a");
    // file opened successfully check
    if(file2write == NULL)
        exit(1);
    // writng
    fprintf(file2write,"%s",Str2Write);
    // fprintf(fptr,"\n");
    // closing
    fclose(file2write);
}
/*********************************************************************************************/

My code isn't working properly, there's an issue with the input prompt in the start. The customer name and all other scans print together without giving the option to enter the info needed for the program. I'm a very basic level C programmer and most of the code was written by a friend who I cannot contact at the moment.



from Recent Questions - Stack Overflow https://ift.tt/37h6kvL
https://ift.tt/eA8V8J

Password saving batch file for unlock/login

Is there any way to create a password then have that newly made password stored in the same batch file as the login code and keep it as that new password???? Here's a visual example of what i mean

Typing in the incorrect password

Typing in the correct password

Setting new password

Is there any way to do this with 1 batch file entirely without having to make another one to save the data?? I am trying to do this on windows 10. I am trying to do this so I dont have to do a preset password like: if %pass%== 12345 goto Login instead I want it to where every user can create their own special password without needing to edit the code



from Recent Questions - Stack Overflow https://ift.tt/39p4n2S
https://ift.tt/eA8V8J

Undefined variable in php mysqli connect

I have a problem with mysqli connection. Undefined variable $host, $user and $password

PHP:

<?php
    require_once "dbconnect.php";
    $polaczenie = mysqli_connect($host, $user, $password)
    or die ('Nie można połączyć się z MySQL.');
    mysqli_select_db($polaczenie, $database)
    or die ('Nie można połączyc się z bazą.');

dbconnect file:

<?php
    $host="localhost"; // Nazwa hosta
    $user="root"; // Nazwa uzytkownika mysql
    $password=""; // Haslo do bazy
    $database="mieszkancy"; // Nazwa bazy
?>


from Recent Questions - Stack Overflow https://ift.tt/2Viv1SZ
https://ift.tt/eA8V8J

Styled Components + TypeScript + new fonts Issue

I want to use some font I've downloaded from the Google fonts on my React/TypeScript application. Unfortunatelly, I can not load the font.

I went through some articles describing the issue and how to handle it but with no luck. Take a look at the below files and let me know if there is something I'm missing:

I want to use the font here: Header.tsx

import React from "react";
import styled from "styled-components";
import headerBg from "../assets/pattern-bg.png";
import GlobalFonts from "../assets/fonts/fonts";

const Header: React.FC = () => {
  return (
    <HeaderSection className="header">
      <GlobalFonts />
      <InputWrapper>
        <MainHeading>IP Address Tracker</MainHeading>
        <label htmlFor="ip-input">
          <input type="text" id="ip-input" />
        </label>
      </InputWrapper>
    </HeaderSection>
  );
};

export default Header;

const HeaderSection = styled.header`
  background-image: url(${headerBg});
  width: 100%;
  height: 500px;
  display: block;
  background-repeat: no-repeat;
  display: flex;
  justify-content: center;
  align-items: center;
  background-size: cover;
`;

const MainHeading = styled.h1`
  margin: 0;
  color: white;
  font-family: "Rubik-Bold";
  // font-family: Rubik-Bold;
`;

const InputWrapper = styled.div``;

fonts.js

import { createGlobalStyle } from "styled-components";

import RubikBold from "./Rubik-Bold.ttf";

export default createGlobalStyle`
    @font-face {
        font-family: 'Rubik Bold';
        src: url('${RubikBold});
    }
`;

fonts.d.ts

declare module '*.woff';
declare module '*.ttf';

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": ["src", "public/assets/Header.tsx", "fonts"]
}

file structure

src:
-assets
--fonts
---fonts.js
---Rubik-Bold.ttf
-components
--Header.tsx


from Recent Questions - Stack Overflow https://ift.tt/36giZQi
https://ift.tt/eA8V8J

How to return an Iterator with associated type being generic from a function?

For a function like this:

fn generate_even(a: i32, b: i32) -> impl Iterator<Item = i32> {
    (a..b).filter(|x| x % 2 == 0)
}

I want to make it generic, instead of the concrete type i32 I want to have any type that is range-able and provide a filter implementation.

Tried the formula below without success:

fn generate_even(a: T, b: T) -> impl Iterator<Item = T>
    where T: // range + filter + what to put here?
{
    (a..b).filter(|x| x % 2 == 0)
}

How can something like this be implemented?



from Recent Questions - Stack Overflow https://ift.tt/3lojc89
https://ift.tt/eA8V8J

FixedUpdate doesn't register all keys (unity)

I ordered a book and I've been following it's instructions fully. The only problem is when I put my movements in FixedUpdate it doesn't register every key. I've read many answers to this but they all say put your inputs in Update and put all of the physics in FixedUpdate. I did just that but when I press the spacebar 30 times it only jumps around 5. This is some of my code (I apologize if it's readability is bad, I'm just starting out.):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerBehavior : MonoBehaviour
{

    public GameObject bullet;

    public float moveSpeed = 10f;
    public float rotateSpeed = 10f;
    public float jumpVelocity = 5f;
    public float distanceToGround = 0.1f;
    public float bulletSpeed = 100f;

    public LayerMask groundLayer;

    private float vInput;
    private float hInput;

    private Rigidbody _rb;
    private CapsuleCollider _col;

    private bool isShooting;
    private bool isJumping;

    void Start()
    {
        _rb = GetComponent<Rigidbody>();
        _col = GetComponent<CapsuleCollider>();

        isShooting = false;
        isJumping = false;
    }


    void Update()
    {
        //player movement
        vInput = Input.GetAxis("Vertical") * moveSpeed;
        hInput = Input.GetAxis("Horizontal") * rotateSpeed;

        isJumping = Input.GetKeyDown(KeyCode.Space);

        //allows me to see if the spacer bar is registering
        if (isJumping)
        {
            Debug.Log("Jump");

        }

        isShooting = Input.GetMouseButtonDown(1);

        if (isShooting)
        {
            Debug.Log("Shoot");
        }
    }

    void FixedUpdate()
    {

        Vector3 rotation = Vector3.up * hInput;
        Quaternion angleRot = Quaternion.Euler(rotation * Time.fixedDeltaTime);
        _rb.MovePosition(this.transform.position + this.transform.forward * vInput * 
        Time.fixedDeltaTime);
        _rb.MoveRotation(_rb.rotation * angleRot);

        //determines if the player is on the ground and hit the spacebar. If so the player jumps.
        if (IsGrounded() && isJumping)
        {
            _rb.AddForce(Vector3.up * jumpVelocity, ForceMode.Impulse);

        //this allows isJumping to revert back to false 100% of the time

            isJumping = false;

            Debug.Log("The jump mechanic is working");
        }

        if (isShooting)
        {
            GameObject newBullet = Instantiate(bullet, this.transform.position + new Vector3(1, 0, 0), 
            this.transform.rotation) as GameObject;
            Rigidbody bulletRB = newBullet.GetComponent<Rigidbody>();
            bulletRB.velocity = this.transform.forward * bulletSpeed;

            isShooting = false;
            Debug.Log("The shooting mechanic is working");
        }
    }


    //determines if the player is on the ground
    bool IsGrounded()
    {
        Vector3 capsuleBottom = new Vector3(_col.bounds.center.x, _col.bounds.min.y, 
        _col.bounds.center.z);
        bool grounded = Physics.CheckCapsule(_col.bounds.center, capsuleBottom, distanceToGround, 
        groundLayer, QueryTriggerInteraction.Ignore);

        return grounded;
    }
}


from Recent Questions - Stack Overflow https://ift.tt/36iAH5v
https://ift.tt/eA8V8J

Python Plotly - geocoding latitude and longitude - want different symbols depending on type of facility

I am geocoding a list of facilities and I want to the output to symbolize by whether they are a hospital or a clinic. Hospitals I want to appear as squares and clinics as circles. I can get my Plotly map working by mapping just one, but I'm unable to figure out how to have it plot different symbols by the facility type. I'm importing from a dataset that has the population (pop), location of the facility (location), latitude (lat), longitude (lon) and facility type (f_type). My dataset looks like this:

pop | location | lat | lon | f_type

20 | Cleveland, OH | 41.4993 | -81.6944 | hospital

Any help is appreciated.

import plotly.graph_objects as go
from plotly.offline import plot
from plotly.subplots import make_subplots
import plotly.graph_objects as go

import pandas as pd

df = pd.read_excel(r'D:\python code\data mgmt\listforgeorural.xlsx')
df.head()

fig = go.Figure(data=go.Scattergeo(
        locationmode = 'USA-states',
        lon = df['lon'],
        lat = df['lat'],
        f_type = df['f_type'],
      
        text = df['location']+'<br>Number of Projects:'+ df['f_type'].astype(str),
        mode = 'markers',
        marker = dict(
            size = 17,
            opacity = 0.9,
            reversescale = False,
            autocolorscale = False,
            symbol = {['square', 'circle']},
            line = dict(
                width=1,
                color='rgba(102, 102, 102)'
            ),
            colorscale = 'Blues',
            cmin = 0,
            color = df['pop'],
            cmax = df['pop'].max(),
            colorbar_title="Number of Rural Projects: 2015 - 2020"
        )))

fig.update_layout(
        title = 'List of Rural Projects by Location of Project Lead/PI',
        geo = dict(
            scope='usa',
            projection_type='albers usa',
            showland = True,
            landcolor = "rgb(222, 222, 222)",
            subunitcolor = "rgb(255, 255, 255)",
            countrycolor = "rgb(217, 217, 217)",
            countrywidth = 0.5,
            subunitwidth = 0.5
        ),
    )

fig.show()
plot(fig, filename='output.html')


from Recent Questions - Stack Overflow https://ift.tt/364gS1G
https://ift.tt/eA8V8J

2020-11-29

Android resize view with pinch

I am making an app that adds stickers on photos and i want to resize the sticker with a pinch gesture.

 final ImageView newSticker = new ImageView(getApplicationContext());
                    newSticker.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,FrameLayout.LayoutParams.WRAP_CONTENT));
                    Bitmap sticker = BitmapFactory.decodeResource(getResources(),galleryList[position]);
                    newSticker.setImageBitmap(sticker);
                    viewGroup.addView(newSticker);

I have a Frame Layout with an ImageView and i am adding Views on it. This is the onTouch method for the sticker:

newSticker.setOnTouchListener(new View.OnTouchListener()
                    {
                        PointF DownPT = new PointF(); // Record Mouse Position When Pressed Down
                        PointF StartPT = new PointF(); // Record Start Position of 'img'
                        float olddistance;

                        @Override
                        public boolean onTouch(View v, MotionEvent event)
                        {
                            selectedSticker = newSticker;

                            switch (event.getAction())
                            {

                                case MotionEvent.ACTION_MOVE :
                                    if(event.getPointerCount() == 1)
                                    {
                                        newSticker.setX((int) (StartPT.x + event.getX() - DownPT.x));
                                        newSticker.setY((int) (StartPT.y + event.getY() - DownPT.y));
                                    }
                                    else if(event.getPointerCount() == 2)
                                    {
                                        final float dX =event.getX(0) - event.getX(1);
                                        final float dY =event.getY(0) - event.getY(1);
                                        float newdistance = (float) Math.sqrt(dX * dX + dY * dY);
                                        float distance = newdistance / olddistance;
                                        FrameLayout.LayoutParams lp= new FrameLayout.LayoutParams((int) (newSticker.getHeight() * distance), (int) (newSticker.getWidth() * distance));
                                        newSticker.setLayoutParams(lp);
                                    }
                                    StartPT.set( newSticker.getX(), newSticker.getY() );
                                    break;
                                case MotionEvent.ACTION_DOWN :
                                    if(event.getPointerCount() == 1)
                                    {
                                        DownPT.set(event.getX(), event.getY());
                                        StartPT.set(newSticker.getX(), newSticker.getY());
                                    }
                                    else if(event.getPointerCount() == 2)
                                    {
                                        final float odX =event.getX(0) - event.getX(1);
                                        final float odY =event.getY(0) - event.getY(1);
                                        olddistance = (float) Math.sqrt(odX * odX + odY * odY);
                                    }
                                    break;

                                case MotionEvent.ACTION_POINTER_DOWN:

                                case MotionEvent.ACTION_UP :
                                    // Nothing have to do
                                    break;
                                default :
                                    break;
                            }
                            return true;
                        }
                    });

In the code above it is successfully moving stickers, but i don't know how to resize the View with a pinch. I don't want the sticker to scale inside of that View, but i want the whole View to be resized.



from Recent Questions - Stack Overflow https://ift.tt/3mk0H66
https://ift.tt/eA8V8J

Casting a struct onto variable length buffer

Is it possible to create struct that I can cast to a buffer of variable size? For example if I have some data that looks something like this:

0  1  2  3  4  5  6  7  8
+--+--+--+--+--+--+--+--+
|                       |
/                       /
/          DATA         /
|                       |
+--+--+--+--+--+--+--+--+
|          NAME         |
+--+--+--+--+--+--+--+--+
|          TIME         |
+--+--+--+--+--+--+--+--+
|          ETC          |
+--+--+--+--+--+--+--+--+

Would it be possible to have a struct similar to this

typedef struct{
    uint8_t data[];
    uint8_t name;
    uint8_t time;
    uint8_t etc;
}Struct;

and then resize Struct.data at runtime to I can cast the structure directly onto the buffer?

I know I could just make a struct that uses pointers and have them point to parts of the buffer, but I was curious if this is possible because it would simplify my code and make it easier to read/use.



from Recent Questions - Stack Overflow https://ift.tt/3o40xAh
https://ift.tt/eA8V8J

Gurobi Python constraint adding

I want to write the following constraint in gurobi python ,enter image description here

and I am writing that as the following and having key error. Can anyone help me by saying where I am doing mistake?

for (i,j) in road_node:
    for t in range(1,n_time_horizon+1):
        m.addConstr(sum([x[v,i,u,j,u+fftt[(i,j)]] for v in vehicle_list for u in range(1,n_time_horizon+1) if u>=0 and u<=t]) - sum([x[v,j,u,i,u+fftt[(j,i)]] for v in vehicle_list for (j,i) in road_node for u in range(1,n_time_horizon+1) if u>=0 and u<=t]) <= l[(i,j)],name = "cont_4")


from Recent Questions - Stack Overflow https://ift.tt/3fMaBLr
https://ift.tt/2VhhXwU

MATLAB Audio Reformatting: Array dimensions are not consistent

I am working on a deep learning project that identifies words. I am using this as a guide: https://www.mathworks.com/help/audio/ug/Speech-Command-Recognition-Using-Deep-Learning.html

However, when I input my own audio into the code and try to reformat it I keep getting this error...

Error using vertcat Dimensions of arrays being concatenated are not consistent. Error in PLS (line 109) xPadded = [zeros(floor((segmentSamples-size(x,1))/2),1);x;zeros(ceil((segmentSamples-size(x,1))/2),1)];

This is the code where the error is occuring (I am using 16000 hz):

%Sets audio to consistent size
x = read(adsTrain);

numSamples = size(x,1);

numToPadFront = floor( (segmentSamples - numSamples)/2 );
numToPadBack = ceil( (segmentSamples - numSamples)/2 );

xPadded = [zeros(numToPadFront,1,'like',x);x;zeros(numToPadBack,1,'like',x)];



features = extract(afe,xPadded);
[numHops,numFeatures] = size(features)


if ~isempty(ver('parallel')) && ~reduceDataset
    pool = gcp;
    numPar = numpartitions(adsTrain,pool);
else
    numPar = 1;
end


for ii = 1:numPar
    subds = partition(adsTrain,numPar,ii);
    XTrain = zeros(numHops,numBands,1,numel(subds.Files));
    for idx = 1:numel(subds.Files)
        x = read(subds);
    %THIS IS WHERE IS ERROR IS THROWN
    xPadded = [zeros(floor((segmentSamples-size(x,1))/2),1);x;zeros(ceil((segmentSamples-size(x,1))/2),1)]; 
        XTrain(:,:,:,idx) = extract(afe,xPadded);
    end
    XTrainC{ii} = XTrain;
end


XTrain = cat(4,XTrainC{:});

[numHops,numBands,numChannels,numSpec] = size(XTrain)

Thanks!



from Recent Questions - Stack Overflow https://ift.tt/3fNv8iA
https://ift.tt/eA8V8J

Understanding greater than equal to integer with decimals

main.js

// JavaScript source code
var quest = 0;
var gold = 0;
var maxrandomgold = 10;
var minrandomgold = 1;
var renown = 0;
var renownmultiplier = 0.2;

// For each click, add 1 quest number and random gold between 0-9.
function questclick(number) {
    quest = quest + number;
    if (renown >= (quest / 5)) {
        renownmultiplier = renownmultiplier * 2;
        maxrandomgold = Math.ceil((maxrandomgold + (renownmultiplier * 50))/1.5);
        minrandomgold = Math.ceil(maxrandomgold/2);
    }
    renown = Math.round((renown + renownmultiplier) * 100) / 100;
    gold = gold + (Math.floor(Math.random() * maxrandomgold) + minrandomgold);
    document.getElementById("quest").innerHTML = quest;
    document.getElementById("renown").innerHTML = renown;
    document.getElementById("gold").innerHTML = gold;
    document.getElementById("minrandomgold").innerHTML = minrandomgold;
    document.getElementById("maxrandomgold").innerHTML = maxrandomgold;
    document.getElementById("renownmultiplier").innerHTML = renownmultiplier;
}

index.html

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script type="text/javascript" src="main.js"></script>
    <meta charset="utf-8" />
    <title></title>
    <link rel="stylesheet" type="text/css" href="interface.css" />
</head>
<body>
    <button onclick="questclick(1)">Quest!</button>
    <br />
    Completed Quests: <span id="quest">0</span>
    <br />
    Total Gold: <span id="gold">0</span>
    <br />
    Renown: <span id="renown">0</span>
    <br />
    Min Random Gold: <span id="minrandomgold">1</span>
    <br />
    Max Random Gold: <span id="maxrandomgold">10</span>
    <br />
    Renown Multiplier: <span id="renownmultiplier">0.2</span>
</body>
</html>

After pressing the Quest button 5 times, Renown is 1 and therefore greater than or equal to quest/5 (in this case, 1).

I expect the min random gold and max random gold to increase, as per the if statement.

However, it seems the if statement isn't triggered, and I can only put it down to Math.round() rounding to the nearest integer, and somehow the Greater Than Or Equal To if statement interpreting it incorrectly.

Or have I missed something completely obvious?



from Recent Questions - Stack Overflow https://ift.tt/39s7jMe
https://ift.tt/eA8V8J

How to display content from selected WPF ComboBox item C#

i hope everyone is well I am building a small application in C# and WPF, I am trying to add a functionality where when the combo Box is clicked and a certain element is selected, I want to display the contents of the text, but Ienter image description here cant seem to get it right. I would love some input on how to solve this issue, please take a look at the C# code and if you have a solution to it please post it, thank you, NOTE as you might see from the code, I am a beginner coder. Thanks in advace for the help.

namespace WPFDemo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            textToDisplay.IsReadOnly = true;

            SaveFileDialog saveFileDialog = new SaveFileDialog();
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "Import new template";
            openFileDialog.Filter = "Text files (*.txt)|*.txt";
            saveFileDialog.Filter = "Text files (*.txt)|*.txt";
            loadTemplates();
        }

        // Load the templates in the directory
        private void loadTemplates()
        {
            string[] templates = Directory.GetFiles(@"C:\Users\injanlee\source\repos\WPFDemo\WPFDemo\Snow Templates");
            Array.Sort(Directory.GetFiles(@"C:\Users\injanlee\source\repos\WPFDemo\WPFDemo\Snow Templates"));
            Array.Sort(templates);
            foreach (string template in templates)
            {
                //string fileName = template.Split("\\")[5].Split(".")[0];
                string fName = System.IO.Path.GetFileName(template);
                selectOption.Items.Add(fName);
                
            }
            
        }

        private async Task Sleep(int miliSeconds)
        {
            await Task.Delay(miliSeconds);
            myLabel.Content = " ";
        }
        

        private async void Submit_Click(object sender, RoutedEventArgs e)
        {
            Clipboard.SetText(textToDisplay.Text);

            myLabel.Content = "Copied to clipboard";
            myLabel.Foreground = new SolidColorBrush(Colors.DarkGreen);
            await Sleep(3000);
        }

        private void DisplayFileContent(string path)
        {
            textToDisplay.Clear();
            try
            {
                string[] fileContent = File.ReadAllLines(path);
                foreach (string line in fileContent)
                {
                    textToDisplay.Text += line;
                    textToDisplay.Text += "\n";
                }
            }
            catch
            {
                MessageBox.Show($"Unable to find the path for the specific selected File: {selectOption.Text}");
                
            }
            
            
        }


        // Import and save new file template
        public void importTemplate_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            OpenFileDialog openFileDialog = new OpenFileDialog();

            saveFileDialog.Title = "Save To";
            openFileDialog.Title = "Import new template";
            openFileDialog.Filter = "Text files (*.txt)|*.txt";
            saveFileDialog.Filter = "Text files (*.txt)|*.txt";

            if (openFileDialog.ShowDialog() == true)
            {

                
                string[] fileName = openFileDialog.FileName.Split("\\");
                string importedFileName = fileName[5].Split(".")[0];
                saveFileDialog.FileName = importedFileName;
                

                if (saveFileDialog.ShowDialog() == true)
                {
                    string location = saveFileDialog.FileName;
                    File.Copy(openFileDialog.FileName, location, true);
                }

                selectOption.Items.Add(fileName[5].Split(".")[0]);
                MessageBox.Show("Impor successfull");
                
                
            }
        }


        private void selectOption_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (selectOption.SelectedIndex == 0)
            {
                DisplayFileContent(@"C:\Users\injanlee\source\repos\WPFDemo\WPFDemo\Snow Templates\Template.txt");
            }
           
        }


        
    }
}

enter image description here



from Recent Questions - Stack Overflow https://ift.tt/3q9jtQ7
https://ift.tt/2VctYUH

socket.gethostbyaddr raises error when used on localhost

Flask is unable to run in Python 3.6 onwards (works fine in Python 2.7-3.5), and the only change I've made recently is installing Docker. I've fully reinstalled Python and all the modules during testing.

The issue is being caused by the socket module, when http attempts to start a local server. At one point it expects get the hostname of "127.0.0.1", which raises a UnicodeDecodeError.

Here's an example of the error:

# [Python 3] Test against localhost IP (error)
>>> socket.gethostbyaddr('127.0.0.1')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 2: invalid start byte

# [Python 3] Test against localhost
>>> socket.gethostbyaddr('localhost')
('DESKTOP-XXXXXX', [], ['::1'])

# [Python 2] Output of the command
>>> socket.gethostbyaddr('127.0.0.1')
('xn\x969q8h', ['api.genuine.autodesk.com', 'ase.autodesk.com', 'mpa.autodesk.com', 'sv.symcd.com', 'kubernetes.docker.internal'], ['127.0.0.1'])

Here's the full traceback:

Traceback (most recent call last):
  File "__init__.py", line 285, in <module>
    app.run()
  File "C:\Users\Peter\AppData\Roaming\Python\Python37\site-packages\flask\app.py", line 990, in run
    run_simple(host, port, self, **options)
  File "C:\Users\Peter\AppData\Roaming\Python\Python37\site-packages\werkzeug\serving.py", line 1052, in run_simple
    inner()
  File "C:\Users\Peter\AppData\Roaming\Python\Python37\site-packages\werkzeug\serving.py", line 1005, in inner
    fd=fd,
  File "C:\Users\Peter\AppData\Roaming\Python\Python37\site-packages\werkzeug\serving.py", line 848, in make_server
    host, port, app, request_handler, passthrough_errors, ssl_context, fd=fd
  File "C:\Users\Peter\AppData\Roaming\Python\Python37\site-packages\werkzeug\serving.py", line 740, in __init__
    HTTPServer.__init__(self, server_address, handler)
  File "C:\Program Files\Python37\lib\socketserver.py", line 452, in __init__
    self.server_bind()
  File "C:\Program Files\Python37\lib\http\server.py", line 139, in server_bind
    self.server_name = socket.getfqdn(host)
  File "C:\Program Files\Python37\lib\socket.py", line 676, in getfqdn
    hostname, aliases, ipaddrs = gethostbyaddr(name)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 2: invalid start byte

I guess it's failing to parse the 'xn\x969q8h' string I see in the Python 2 output, but I've no idea where that's coming from. Running hostname in cmd returns DESKTOP-XXXXX.



from Recent Questions - Stack Overflow https://ift.tt/37nAXQm
https://ift.tt/eA8V8J

How do I append a file extension to a variable?

I wrote a python application that converts images to PDF's using PIL. The method below takes all images in a given directory, converts them to RGB, then is supposed to save all the images as one *.pdf file. However, I'm unable to figure out how to provide the extension .pdf to the file output.

Concatenating does not work, I get error:

"Unknown file extension: {}.format(ext))

def multi_convert(file_path: str):
    for path in Path(file_path).iterdir():
        path = Image.open(path)
        path.convert('RGB')
    extension = 'file.pdf'
    final_file = file_path + extension
    path.save(final_file, save_all=True, append_images=path)


from Recent Questions - Stack Overflow https://ift.tt/2Vd6xuh
https://ift.tt/eA8V8J

I was testing argv import in python and there is an error

I was reading "Learn Python 3 the Hard Way" and was testing the 'from sys import argv' there is an error occuring here is the sample code of the book:

from sys import argv
first, second, third = argv

print("The scipt is called:", script)
print("Your first variable is:", first)
print("Your second variable is:,", second)
print("Your third variable is:", third)

An I got this error:

Traceback (most recent call last): File "d:/MyCodes/PythonCodes/jon.py", line 2, in first, second, third = argv ValueError: not enough values to unpack (expected 3, got 1)



from Recent Questions - Stack Overflow https://ift.tt/3lfAaFJ
https://ift.tt/eA8V8J

Multiply i-th 2-d matrix in numpy 3d array with i-th column in 2d array

Suppose that I have a 3d array A and a 2d array B. A has dimension (s,m,m) while B has dimension (m,s).

I want to write code for a 2d array C with dimension (m,s) such that C[:,i] = A[i,:,:] @ B[:,i].

Is there a way to do this elegantly without using a for loop in numpy?

One solution I thought of was to reshape B into a 3d array with dimension (m,s,1), multiply A and B via A@B, then reshape the resulting 3d array into a 2d array. This sounds a bit tedious and was wondering if tensordot or einsum can be applied here.

Suggestions appreciated. Thanks!



from Recent Questions - Stack Overflow https://ift.tt/37i6enx
https://ift.tt/eA8V8J

Swift addTarget does not get removed?

The target of nextTrackCommand is called multiple times when I navigate back from a screen and enter the screen again even tho i remove the target in viewWillDisappear. What did I do wrong?

override func viewDidLoad() {
    super.viewDidLoad()

    UIApplication.shared.beginReceivingRemoteControlEvents()

    MPRemoteCommandCenter.shared().nextTrackCommand.addTarget { [unowned self] (_) -> MPRemoteCommandHandlerStatus in
        print("go to next track")
        return .success
    }
}

override func viewWillDisappear(_ animated: Bool) {
    MPRemoteCommandCenter.shared().nextTrackCommand.removeTarget(self)
}


from Recent Questions - Stack Overflow https://ift.tt/39s6WRQ
https://ift.tt/eA8V8J

Arrange a file/output in numerical order, based on the first digit

I have developed a program that produces an average value for measurements on a unit circle. The text files I use, that contains the data of the measurements, can consist of several batches (by that I mean several different measurement occasions) that have two measurements in each. The batch number is always the first one in each line, for example the text file can look like this:

(1), x, y, 10
(1), x, y, 5
(3), x, y, 70
(3), x, y, 10
(2), x, y, 5
(2), x, y, 70

And the number within () is the number of the batch. And when python gives me these average values it gives them in the order that they are written in the text file. In this case, it would show in the order (1), (3) and (2) but I want python to give me these in numerical order instead. I guess I can somehow code so that when python opens the file it reads it in numerical order after the first digit in each line? But how can i enter this?

My current code is:

def collect_data(filename):

    data = [] # Or data = {} #definierar denna först

    with open(filename, 'r') as h:
        for line in h:
            four_vals = line.split(',')
            batch = four_vals[0]
            if not batch in data:
                data[batch] = []
            try:  
                data[batch] += [(float(four_vals[1]), float(four_vals[2]), float(four_vals[3]))] # Collect data from an experiment 
            except ValueError:
                print("String not a float")
    return data

def average(data):

    for batch, sample in data.items(): 
        if len(sample) > 0:
            n = 0
            x_sum = 0
            for (x, y, val) in sample:
                if x**2 + y**2 <= 1:
                    x_sum += val
                    n += 1
            average = x_sum/n
            zero_data = False
        else:
            zero_data = True
       
        print_average(batch, average, zero_data)
        
def print_average(batch, average, zero_data):

    if zero_data == False:
        print(batch, "\t", average)
    else:
        print(batch, "\tNo data")

Edit Since I have defined four_vals[0] as the first value in each line (the number of the batch) I believe that I do have to sort by four_vals[0] somehow, but how?



from Recent Questions - Stack Overflow https://ift.tt/3lhnbUi
https://ift.tt/eA8V8J

Why isn't my ... running?

I am trying to create a div where if I click it, it will show an inner div and upon clicking it again it will be hidden.

So I added the function and the a href around the div and it doesn't run at all just shows javascript:void(0) upon click at bottom-left corner.

<a onclick="openOverviewDiv(this)" href="javascript:void(0);">

if I remove the " at the end of href it will run. It a syntax error(noticed cause i left the " out on accident when i ran on local server) and then I added the " back and it stop running.

<a onclick="openOverviewDiv(this)" href="javascript:void(0);>

I've tried in the snippet and the same thing occurred. How do I fix this?

Update -- To Clarify: I am trying pass this.anchorElement upon clicking the anchor tag as shown above into the function openOverviewDiv(this).

onclick="openOverviewDiv(this)"

in which it then use jQuery to make the hidden children element of the anchor tag, which is a div with the class of "innerProjectDiv" and make it from display: none; to display:block;

jQuery(anchor).children("div.innerProjectDiv").show();

This should works for the anchor clicked and not for the rest of the other anchors' children. If i clicked the anchor with a project div called placeholder1, it should show me the hidden "div.innerProjectDiv" element and not other divs(ie. placeholder2).

If you copied the snippet, it doesn't run upon clicked and as stated if you remove the ", it will run.

function openOverviewDiv(anchor) {
  jQuery(anchor).children("div.innerProjectDiv").show();
  jQuery(anchor).children("i.fa").html("&#xf106;");
}
html,
body {
  height: 100%;
  width: 100%;
  background-color: #020224;
  color: white;
  margin: 0;
  padding: 0;
  min-height: 100%;
}

.container {
  display: grid;
  grid-template-rows: auto 1fr auto;
  grid-template-columns: 100%;
  min-height: 100vh;
  grid-template-areas: "nav" "content" "contentTwo" "footer"
}

.section {
  color: #fff;
  padding: 10px;
}


/* NAV CONTENT */

.nav {
  grid-area: nav;
  position: sticky;
  background-color: transparent;
  top: 0;
  left: 0;
  right: 0;
  display: grid;
  grid-template-columns: auto auto;
  z-index: 1;
  height: 5vh;
}

.nav a:link,
.nav a:visited {
  color: white;
  text-decoration: none;
}

.nav a:hover {
  color: cyan;
}

.navLeft {
  font-size: 2em;
  text-align: left;
}

.navRight {
  font-size: 1.5em;
  text-align: right;
}

.navRight a {
  padding-left: 10px;
}


/* CONTENT */

.homePG {
  grid-area: content;
  margin: auto;
  text-align: center;
  font-size: 7vw;
  padding: 10px 30px;
}

.homePG img {
  width: 500px;
  height: 500px;
}

.homePG h1 {
  font-size: 1em;
}

.homePG p {
  font-size: 0.5em;
}

.contentTwo {
  grid-area: contentTwo;
  margin: auto;
  text-align: center;
  font-size: 7vw;
  padding: 10px 30px;
}

.sidebar2 {
  grid-area: sidebar2;
}


/* IN-PROJECTS CONTENTS */

.projectDivs {
  font-size: 9vw;
  border: 1px solid black;
  border-radius: 25px;
  margin-left: auto;
  margin-right: auto;
  width: 78vw;
  margin-bottom: 5px;
}

.projectDivs i {
  text-align: right;
}

.innerProjectDiv {
  display: none;
  text-align: left;
  font-size: 0.5em;
  width: 78vw;
  padding-left: 20px;
  padding-right: 20px;
}

.innerProjectDiv h1 {
  font-size: 0.5em;
}


/* FOOTER  */

.footer {
  background-color: #03032b;
  grid-area: footer;
  text-align: center;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 0px;
  font-size: 15px;
  height: 3vh;
}

@media screen and (max-width: 1000px) {
  .projectDivs {
    font-size: 8vw;
  }
  .homePG {
    padding-top: 20%;
  }
  .homePG img {
    width: 400px;
    height: 400px;
  }
  .footer {
    grid
  }
}

@media screen and (max-width: 750px) {
  .homePG img {
    width: 200px;
    height: 200px;
  }
}
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="../style.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <title>Brandon | Projects</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body class="container">
  <section class="section nav">
    <nav class="navLeft">
      <a href="#" class="navTitle">Brandon</a>
    </nav>
    <nav class="navRight">
      <a href="../about.php">ABOUT</a>
      <a href="../projects/#">PROJECTS</a>
      <a href="../contact.php">CONTACT</a>
    </nav>

  </section>

  <section class="section homePG project">
    <h1>Projects</h1>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit,
    </p>

    <a onclick="openOverviewDiv(this)" href="javascript:void(0);>
      <div class=" projectDivs ">
        PlaceHolder1
        <i id="icon " class="fa ">&#xf107;</i>
        <div class="innerProjectDiv ">
          <h1>Overview:</h1>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ac ut consequat semper viverra nam libero justo laoreet sit. Bibendum enim facilisis gravida neque convallis a cras semper. Massa
          vitae tortor condimentum lacinia quis vel. Vel elit scelerisque mauris pellentesque pulvinar pellentesque habitant morbi tristique.
        </div>
      </div>
    </a>

    <a onclick="openOverviewDiv(this) " href="javascript:void(0); ">
      <div class="projectDivs ">
        placeholder2
        <i id="icon " class="fa ">&#xf107;</i>
        <div class="innerProjectDiv ">
          <h1>Overview:</h1>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ullamcorper morbi tincidunt ornare massa. Ut venenatis tellus in metus vulputate eu scelerisque felis imperdiet.
        </div>
      </div>
    </a>

    <a onclick="openOverviewDiv(this) " href="javascript:void(0); ">
      <div class="projectDivs ">
        Placeholder3
        <i id="icon " class="fa ">&#xf107;</i>
        <div class="innerProjectDiv ">
          <h1>Overview:</h1>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ac ut consequat semper viverra nam libero justo laoreet sit. Bibendum enim facilisis gravida neque convallis a cras semper. Massa
          vitae tortor condimentum lacinia quis vel. Vel elit scelerisque mauris pellentesque pulvinar pellentesque habitant morbi tristique.
        </div>
      </div>
    </a>
    <a onclick="openOverviewDiv(this) " href="javascript:void(0); ">
      <div class="projectDivs ">
        Placeholder4
        <i id="icon " class="fa ">&#xf107;</i>
        <div class="innerProjectDiv ">
          <h1>Overview:</h1>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ullamcorper morbi tincidunt ornare massa. Ut venenatis tellus in metus vulputate eu scelerisque felis imperdiet.
        </div>
      </div>
    </a>
    <a onclick="openOverviewDiv(this) " href="javascript:void(0); ">
      <div class="projectDivs ">
        Placeholder
        <i id="icon " class="fa ">&#xf107;</i>
        <div class="innerProjectDiv ">
          <h1>Overview:</h1>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ullamcorper morbi tincidunt ornare massa. Ut venenatis tellus in metus vulputate eu scelerisque felis imperdiet.
        </div>
      </div>
    </a>
    <a onclick="openOverviewDiv(this) " href="javascript:void(0); ">
      <div class="projectDivs ">
        Placeholder
        <i id="icon " class="fa ">&#xf107;</i>
        <div class="innerProjectDiv ">
          <h1>Overview:</h1>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ac ut consequat semper viverra nam libero justo laoreet sit. Bibendum enim facilisis gravida neque convallis a cras semper. Massa
          vitae tortor condimentum lacinia quis vel. Vel elit scelerisque mauris pellentesque pulvinar pellentesque habitant morbi tristique.
        </div>
      </div>
    </a>
    <a onclick="openOverviewDiv(this) " href="javascript:void(0); ">
      <div class="projectDivs ">
        Placeholder
        <i id="icon " class="fa ">&#xf107;</i>
        <div class="innerProjectDiv ">
          <h1>Overview:</h1>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ac ut consequat semper viverra nam libero justo laoreet sit. Bibendum enim facilisis gravida neque convallis a cras semper. Massa
          vitae tortor condimentum lacinia quis vel. Vel elit scelerisque mauris pellentesque pulvinar pellentesque habitant morbi tristique.
        </div>
      </div>
    </a>
    <p>

    </p>
  </section>
  <section class="section contentTwo ">
    <p>

    </p>
  </section>
  <section class="section footer ">
    Footer
  </section>

  <script src="function.js "></script>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js "></script>
</body>

</html>


from Recent Questions - Stack Overflow https://ift.tt/3qbLoPi
https://ift.tt/eA8V8J

How do I make PATCH request to work when working with internal API?( Express,React,Node.js)

I am trying to set up the backend API using Express. The DELETE,POSTS,GET request all work except for PATCH. I was getting errors before which I have resolved but now I am stumped because there are no errors and I am not sure what to correct at this point.

The request status is 200 instead it GETs the object being edited in its original form.PATCH request in Insomnia

On the server side the code looks like

const express=require('express');
const router=express.Router();
const fs=require('fs'); // file system module
const { Server } = require('http');
const path=require('path');
const { v4: uuidv4 }=require('uuid');
const dataWarehouses=path.join(__dirname, '../data/warehouses.json');

function listWarehouses(){
    const data=fs.readFileSync(dataWarehouses);
    return JSON.parse(data);   
} 
*function patchWarehouse(id,body)*{
    const listWarehouse = listWarehouses();
    const item = NewWarehousesList(body);
    const change = listWarehouse.find((warehouses)=>warehouses.id===id);
    if(change){
        Object.assign(item, change)
        return item
    }
    else{
        ("This Warehouse does not exist")
    }
   fs.writeFileSync(dataWarehouses, JSON.stringify(change));
}

function NewWarehousesList(body){
    return{id: uuidv4(),
        name:body.name,
        address:body.address,
        city:body.city,
        country:body.country,
        contact:[{
            name:body.contact.name,
            position:body.contact.position,
            phone:body.contact.phone,
            email:body.contact.email
        }]
    }
}

router.patch(('/:id'),(req,res)=>{
    res.json(patchWarehouse(req.params.id, req.body ))
})

module.exports=router;



from Recent Questions - Stack Overflow https://ift.tt/36fd91p
https://ift.tt/eA8V8J

How to use dispatch_uid to avoid duplication Signals correctly

Helloo,

I am trying to apply using a dispatch_uid="my_unique_identifier" in order to avoid duplicate signals sent in my project.

I have searched for several similar answers and read the following documentation but I am not sure what I am missing:

https://docs.djangoproject.com/en/3.1/topics/signals/#preventing-duplicate-signals

In my project there are posts that are written by Author, each post has a like button which when clicked by a user notification is created and sent to the author.

Until here everything is fine except that 2 notifications are sent instead of 1. I have tried the following but it did not have any effect and I am still receiving 2 notifications

So here it is:

Here is the Like model.py

class Like(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=8)

    def user_liked_post(sender, instance, *args, **kwargs):
        like = instance
        if like.value=='Like':
            post = like.post
            sender = like.user
            dispatch_uid = "my_unique_identifier"
            notify = Notification(post=post, sender=sender, user=post.author, notification_type=1)
            notify.save()

post_save.connect(Like.user_liked_post, sender=Like, dispatch_uid="my_unique_identifier")

Here is the notifications model

class Notification(models.Model):
    NOTIFICATION_TYPES=((1,'Like'),(2,'Comment'),(3,'Admin'))

    post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name="noti_post", blank=True, null=True)
    sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_from_user")
    user = models.ForeignKey(User, on_delete=models.CASCADE,related_name="noti_to_user")
    notification_type= models.IntegerField(choices=NOTIFICATION_TYPES)

    def __str__(self):
        return str(self.post)

Here is the views.py:

def LikeView(request):
    post = get_object_or_404(Post, id=request.POST.get('id'))
    liked = False
    current_likes = post.num_likes
    user = request.user
    if post.author.id == request.user.id:
        messages.warning(request, 'You can not like you own Post')
    else:
        if post.likes.filter(id=request.user.id).exists():
            post.likes.remove(request.user)
            liked = False
            current_likes = current_likes - 1
        else:
            post.likes.add(request.user)
            liked = True
            current_likes = current_likes + 1
        post.num_likes = current_likes
        post.save()

        like, created = Like.objects.get_or_create(user=user, post=post)
        sender = like.user

        if not created:
            if like.value == 'Like':
                like.value = 'Unlike'
                like.delete_notification(sender, post)
            else:
                like.value = 'Like'
        like.save()

    context = {
        'total_likes': post.total_likes,
        'liked': liked,
        'post': post,
    }
    if request.is_ajax:
        html = render_to_string('blog/like_section.html', context, request=request)
        return JsonResponse({'form': html})

Update: Here is what I have tried to replace get_or_create: but got AttributeError: 'Like' object has no attribute 'exists'

    try:
        like = Like.objects.get(user=user, post=post)
        sender = like.user

        if like.exists():
            like.delete()
            like.delete_notification(sender,post)  

        else:
            like = Like(user=user, post=post)
            like.save()
    except Like.DoesNotExist:
        like = Like(user=user, post=post)

        if like.value == 'Like':
            like.value = 'Unlike'
            like.delete_notification(sender, post)
        else:
            like.value = 'Like'
        like.save()

My question is how to use dispatch_uid="my_unique_identifier" correctly inorder to avoid duplicated signals?



from Recent Questions - Stack Overflow https://ift.tt/3mkdtBB
https://ift.tt/eA8V8J

machine learning even or odd, with python (scikit-learn)

I'm trying to modify the scikit learn Recognizing hand-written digits so whereafter it's predicted what the image is, to then see if the digit is even or odd.

In line 30-38 I separate the predicted into its even and odd components, I do the same for y_test. But my problem, it's the coder who is filtering to what is even and odd, I'm trying to make the machine lifter to see if the number is even or odd. I might be going about this the wrong way, maybe I am thinking it about it correctly, but not sure. After that I want to create a confusion matrix like I have below line 38.

import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from sklearn import datasets, svm, metrics
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
import pandas as pd
import numpy as np


digits = datasets.load_digits() # from skleanr tutorial page
n_samples = len(digits.images)
imshape = digits.images[0].shape # to remember what an image is...
data = digits.images.reshape((n_samples, -1))
targ = digits.target

# choose your classifier
classifier = svm.SVC( )

# split into training and test sets
X_train, X_test, y_train, y_test = train_test_split(data, targ, test_size=0.5, shuffle=False)
n_train = len(y_train)
n_test = len(y_test)

# do it!
classifier.fit(X_train, y_train)
predicted = classifier.predict(X_test)

#print(predicted)
predicted_even = (predicted[predicted%2==0])
print(len(predicted_even))
predicted_odd = (predicted[predicted%2!=0])
print(len(predicted_odd))

y_even = (y_test[y_test%2==0])
print(len(y_even))
y_odd = (y_test[y_test%2!=0])
print(len(y_odd))


data1 = {'y_test': y_test, 'predicted': predicted}
df = pd.DataFrame(data1,columns=["y_test","predicted"])
cfm = pd.crosstab(df['y_test'],df['predicted'],colnames=["True"],rownames=["Predicted"])
print(cfm)


print('number in test set:',len(y_test))
right=np.sum(y_test==predicted)
print('number correctly classified:',right)

msk = y_test!=predicted
X_fails,y_fails,y_failspred = X_test[msk],y_test[msk],predicted[msk]


# here on in, we're plotting...
_, axes = plt.subplots(4, 4)
plt.subplots_adjust(hspace=1.0)
Xy = list(zip(X_train, y_train))
for ax, (X,y) in zip(axes[:2,:].flatten()[:], Xy[:8]):
    ax.set_axis_off()
    ax.imshow(X.reshape(imshape), cmap=plt.cm.gray_r, interpolation='nearest')
    ax.set_title(f'Training: {y}')

plot_the_failures=False
#plot_the_failures=True

if plot_the_failures:
    print('plotting the bad predictions')
    # this will probably choke if there are fewer than 8 fails.
    Xyy = list(zip(X_fails, y_fails, y_failspred))
else:
    Xyy = list(zip(X_test,y_test,predicted))
for ax, (X,yt,yp) in zip(axes[2:, :].flatten()[:], Xyy[:8]):
    ax.set_axis_off()
    Xim = X.reshape(imshape)
    ax.imshow(Xim, cmap=plt.cm.gray_r, interpolation='nearest')
    ax.set_title(f'True, Predict:\n{yt}, {yp}')

ofil='tmp.png'
print('saving to file',ofil)
plt.savefig(ofil)



from Recent Questions - Stack Overflow https://ift.tt/3mo8v7e
https://ift.tt/eA8V8J

How to return interface from generic class implementing the interface?

I want to make a method that accepts any class (T) that implements any interface (I), do something with the class and return the interface (I) that it implements. Here's what I've tried:

class MyLibrary {
    
    public static <I, T extends I> I registerImplementation(Class<T> classImpl) {
        I interfaceImpl = (I) classImpl.newInstance();
        return interfaceImpl;
    }
}

I'm then creating an interface and a class which implements that interface:

interface UserInterface {
    void doSomethingDefined();
}

class UserClass_v1_10_R2 implements UserInterface {

    @Override
    public void doSomethingDefined() {
        System.out.println("What this does is well-defined");
    }

    public void doVersionSpecificStuff() {
        System.out.println("This is not in the interface, so don't really depend on this");
    }
}

However, when I'm calling the method referencing UserClass, it returns the same class type (T) instead of the interface type (I), allowing all the class methods which are not declared in the interface to be called.

I.e. in the statement below, even though registerImplementation() is declared to return a reference to UserInterface, the compiler sees the reference as pointing to an instance of UserClass_v1_10_R2, allowing access to the implementation's methods that are not in the interface.

MyLibrary.registerImplementation(UserClass_v1_10_R2.class).doVersionSpecificStuff();

Contrast this with the supposedly identical

UserInterface uiObj = MyLibrary.registerImplementation(UserClass_v1_10_R2.class);
uiObj.doVersionSpecificStuff(); // This does not compile


from Recent Questions - Stack Overflow https://ift.tt/3lf8aSU
https://ift.tt/eA8V8J

GitHub Repositories (How to Run)

I have read the following answer here about how to run a specific file.

However, let's say I want to run every single aspect of code in the entire repository here that uses MathJax without downloading it.

How would one figure that out and do that? Is it one JavaScript source code that you script?
If so, how do you figure out the URL that you run?



from Recent Questions - Stack Overflow https://ift.tt/3o3yT6D
https://ift.tt/eA8V8J

It says subquery returns more than 1 row but I'm not sure why?

I've joined around 4 tables in my database and I am trying to get a shortlist of candidates who meet these requirements. It won't display another person who meets these requirements. It for some reason works when there is one candidate that meets them.

SELECT job_seeker.seeker_fn
    ,job_seeker.seeker_ln
    ,COUNT(DISTINCT job_seeker.position_title) AS 'Required Skills'
    ,COUNT(DISTINCT quali_name) AS 'Required Qualifications'
FROM job_seeker
INNER JOIN job_seeker_profile ON job_seeker.seeker_ID = job_seeker_profile.seeker_ID
INNER JOIN qualifications ON job_seeker_profile.qualification_ID = qualifications.qualification_ID
INNER JOIN skill_types ON job_seeker_profile.skill_type_ID = skill_types.skill_type_ID
INNER JOIN skill_areas ON skill_areas.area_ID = skill_areas.area_ID
INNER JOIN job_pos ON qualifications.qualification_ID = job_pos.qualification_ID
WHERE (
        SELECT job_pos.qualification_ID
        FROM job_pos
        WHERE job_pos.qualification_ID = job_seeker_profile.skill_type_ID
            AND job_pos.qualification_ID = job_seeker_profile.qualification_ID
        )
    AND job_pos.job_position_ID = 7;

enter image description here



from Recent Questions - Stack Overflow https://ift.tt/36fd8KT
https://ift.tt/eA8V8J

Improve query performance in large collection with large documents using indexes or in any other possible way

I am using PyMongo with Flask and I would like to know how to optimize a query, as I am filtering within a large collection (8793 documents) with large documents.

This is one of the document structures of the collections:

enter image description here

As you can see, it has 4 properties (simulationID, simulationPartID, timePass and status, which stores many arrays). This collection has a size of 824.4MB. The average size of the documents is 96.0KB.

enter image description here

Basically, I’m trying to find the documents that have simulationPartID 7 (1256 documents) and filter on them the array index equal to the nodeID value (which I receive as a parameter) within the status property, and take the fourth or fifth element of this array (depending on the case parameter), in addition to append the timePass.

def node_history(nodeID, case):
    coordinates = []
    node_data = db['node_data']
    db.node_data.create_index([('simulationPartID', 1), ('simulationID', 1)])
    if case == 'Temperature':
        for document in node_data.find({"simulationPartID": 7}):
            coordinates.append([document['timePass'], document['status'][int(nodeID)-1][3]])
    elif case == 'Stress':
        for document in node_data.find({"simulationPartID": 7}):
            coordinates.append([document['timePass'], document['status'][int(nodeID)-1][4]])
    else:
        pass
    coordinates.sort()
    return json.dumps(coordinates, default=json_util.default)

As I mentioned, the collection is very large, and the query takes about 30 - 60 seconds to be performed, depending on the machine, but I want it to run as quickly as possible because I want my application to be as interactive as possible. As you can seeI already tried to create a index in both simulationID and simulationPartID properties.

I never worked with large collections before, so I'm not into indexing. I don't even know if I did it properly in my code. So, I would like to know if there is a way to optimize my query using a different approach of indexes, or in any other possible way, and make it faster.

Data samples:

{
  "_id": {
    "$oid": "5f83f54d45104462898aba67"
  },
  "simulationID": "001",
  "simulationPartID": 7,
  "timePass": 0,
  "status": [
    [
      1,
      1.34022987724954e-40,
      0.00220799725502729,
      20,
      114.911392211914
    ],
    [
      2,
      0.00217749993316829,
      0.00220799725502729,
      20,
      -2.0458550453186
    ],
    [
      3,
      0.0020274999551475,
      0.00235799723304808,
      20,
      -1.33439755439758
    ],
    [
      4,
      3.36311631437956e-44,
      0.00235799723304808,
      20,
      148.233413696289
    ],
    [
      5,
      1.02169119449431e-38,
      0.000149997213156894,
      20,
      -25633.59765625
    ],
  ]
},

{  
  "_id": {
    "$oid": "5f83f54d45104462898aba68"
  },
  "simulationID": "001",
  "simulationPartID": 7,
  "timePass": 1,
  "status": [
    [
      1,
      1.34022987724954e-40,
      0.00220799725502729,
      20,
      114.911392211914
    ],
    [
      2,
      0.00217749993316829,
      0.00220799725502729,
      20,
      -2.0458550453186
    ],
    [
      3,
      0.0020274999551475,
      0.00235799723304808,
      20,
      -1.33439755439758
    ],
    [
      4,
      3.36311631437956e-44,
      0.00235799723304808,
      20,
      148.233413696289
    ],
    [
      5,
      1.02169119449431e-38,
      0.000149997213156894,
      20,
      -25633.59765625
    ],
  ]
},
{
"_id": {
    "$oid": "5f83f54d45104462898aba69"
  },
  "simulationID": "001",
  "simulationPartID": 7,
  "timePass": 2,
  "status": [
    [
      1,
      1.34022987724954e-40,
      0.00220799725502729,
      20,
      114.911392211914
    ],
    [
      2,
      0.00217749993316829,
      0.00220799725502729,
      20,
      -2.0458550453186
    ],
    [
      3,
      0.0020274999551475,
      0.00235799723304808,
      20,
      -1.33439755439758
    ],
    [
      4,
      3.36311631437956e-44,
      0.00235799723304808,
      20,
      148.233413696289
    ],
    [
      5,
      1.02169119449431e-38,
      0.000149997213156894,
      20,
      -25633.59765625
    ],
  ]
}

Thank you!



from Recent Questions - Stack Overflow https://ift.tt/33pbmVT
https://ift.tt/2Ji6tXN

How to build and link Boost.Serialization on MacOS

I'm building a client-server application in C++ using Boost, a colleague of mine is coding the server in Ubuntu and he's using Boost.Serialization but I'm unable to run it because it doesn't find that library, besides I also need the library for the client. To build and link it to the project he's only created a CMAKE file like this:

cmake_minimum_required(VERSION 3.16)
project(RemoteBackup_Server)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_FLAGS "-pthread" )

add_executable(RemoteBackup_Server User.cpp main.cpp server.cpp server.h connection_handler.cpp connection_handler.h)


find_package(Boost REQUIRED COMPONENTS serialization filesystem)
include_directories(${Boost_INCLUDE_DIRS})
target_link_libraries(RemoteBackup_Server ${Boost_LIBRARIES})

Which compiles and links the library with no efforts. I'm using MacOS, I've installed Boost using Homebrew and I've tried to follow the guide in the Boost official site: https://www.boost.org/doc/libs/1_74_0/more/getting_started/unix-variants.html#prepare-to-use-a-boost-library-binary but I don't have bootstrap.sh and b2 (commands mentioned in the guide) to build the libraries and I've searched everywhere on the internet and still got no clue on how to proceed. Any help?



from Recent Questions - Stack Overflow https://ift.tt/3fRNdMD
https://ift.tt/eA8V8J

create-react-app is not working since version 4.0.1

I tried installing using npm i create-react-app and even npx create-react-app new-app. I even tried npm init react-app new-app.

I'm getting this error message:

You are running create-react-app 4.0.0, which is behind the latest release (4.0.1).
We no longer support global installation of Create React App.

How can I fix this?



from Recent Questions - Stack Overflow https://ift.tt/3nPm93u
https://ift.tt/eA8V8J

2020-11-28

do_sys_open kprobe is always returning the same filename

I wrote a module which registers kprobe on do_sys_open and i am trying to print the filename in the pre_handler

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/kprobes.h>

MODULE_LICENSE("GPL");

static struct kprobe kp;
static char *name = "do_sys_open";
module_param(name, charp, 0);

static int pre_handler(struct kprobe *p, struct pt_regs *regs)
{
    char *filename = (char *)regs->si;
        char user_filename[256] = {0};
        long copied = strncpy_from_user(user_filename, filename, sizeof(user_filename));
    
    pr_info("eax: %08lx   ebx: %08lx   ecx: %08lx   edx: %08lx\n",
            regs->ax, regs->bx, regs->cx, regs->dx);
    pr_info("esi: %08lx   edi: %08lx   ebp: %08lx   esp: %08lx\n",
            regs->si, regs->di, regs->bp, regs->sp);

    if (copied > 0)
                pr_info("%s filename:%s\n",__func__, user_filename);
    return 0;
}

static int __init hello_init(void)
{
    /* set the handler functions */

    kp.pre_handler = pre_handler;
    kp.symbol_name = name;

    return register_kprobe(&kp);
}

static void __exit hello_exit(void)
{
    pr_info("%s\n", __func__);
    unregister_kprobe(&kp);
}

module_init(hello_init);
module_exit(hello_exit);

After loading this module, i am continuously getting the same file name: pre_handler filename:/run/log/journal/e5f9bd15e9f247dd888fba443a4d9599/system.journal

What's wrong with the above code?



from Recent Questions - Stack Overflow https://ift.tt/3mgzkKf
https://ift.tt/eA8V8J

Sql query / VBA - multiple Select / where conditions problem

I'm sorry if this has been answered already, but I couldn't find the right solution for my problem.

I have an excel file with user form where users can insert exchange rates and diferent parameters for financial report.

I've set up a DB file and I want to select rows based on the values in BV column (book value) and it should be higher than 100.000EUR The problem is that I have 3 other currencies besides EUR and I need to calculate EUR amount based on exchange rate.

I've already made exchange rate field in my user form (BVAL is EUR default, and I also have BVGBP, BVPLN and BVRSD, which are 100.000EUR divided with each exchange rate) This works fine:

SqlQuery = " SELECT * FROM Sheet1 where (bv>=" & BVAL & " and Currency = 'EUR')";"

But when I try to combine multiple results,syntax is not working, I've tried a lot of other solutions I've found online, but I cannot seem to get it working.

SqlQuery = " SELECT * FROM Sheet1 where (bv>=" & BVAL & " and Currency='EUR') or (bv>=" & BVGBP & " and Currency='GBP') _

or (bv>=" & BVPLN & " and Currency='PLN') or (bv>=" & BVRSD & " and Currency='RSD');"

I would appreciate it if you could give me suggestions how to fix this, I'm quite new to VBA and I don't mind to google solutions, but this one is tough :). Thanks!



from Recent Questions - Stack Overflow https://ift.tt/39tS3OO
https://ift.tt/eA8V8J

Vue single file class with member variable - variable is undefined

I have this:

export default class EventForm extends Vue {
 @Prop() eventId?: number | null;
 private eventAttendees: PersonForMeeting[] = []
 
 addAttendee(person: PersonForMeeting) {
  this.eventAttendees.push(person);
 }

              getPeopleFromStore().forEach( (pfm: PersonForMeeting) => {
              if(
                  (pfm.type === "contact" && attendee.contact === pfm.id)
              ||
                  (pfm.type === "user" && attendee.user === pfm.id)
              ) {
                console.log("Adding", JSON.stringify(pfm))
                console.log("THIS", this.eventAttendees) /// <- WHY IS THIS UNDEFINED????
                this.addAttendee(pfm)
              }
            })
}

I get an undefined value at the line noted - why?



from Recent Questions - Stack Overflow https://ift.tt/2JnUozP
https://ift.tt/eA8V8J

How do I get rid of SNI.dll when publishing as a "single file" in Visual Studio 2019?

I'm trying to publish a very simple C# .Net 5.0 WinForms application (single file output) as a test case for porting from the .Net Framework v4.6.1 (what it was previously) while using Visual Studio 2019 v16.8.2. The Publish options are as follows:

  • Configuration: Release | Any CPU
  • Target Framework: net5.0-windows
  • Deployment Mode: Framework-dependent
  • Target-Runtime: win-x64
  • Produce Single File: Enabled
  • Enable ReadyToRun Compilation: Disabled

Although the build works fine and merges the two source assemblies into a single output executable, it also includes SNI.dll in the output directory. The application will not start without this DLL in the same folder as the executable so my question is: How do I remove the dependency on SNI.dll so it does not get included with the published executable and is not required to run?

Any help with this would be most appreciated. Cheers



from Recent Questions - Stack Overflow https://ift.tt/3fIQCgT
https://ift.tt/eA8V8J

Python.h: No such file or directory, when implementing python into c++, using CLion

I have used "apt-cyg install python3-devel" on my Cygwin terminal. I have included directories in CMake...

include_directories(C:/Users/{my_user_name}/anaconda3/include)

and importantly in my main.cpp

#include <Python.h>

and have tried "Python.h", and "fullpath/Python.h". I get back the error "fatal error: Python.h: No such file or directory". Thanks for any help.



from Recent Questions - Stack Overflow https://ift.tt/2V9VVw7
https://ift.tt/eA8V8J

UE4 Accessing TMap crashes engine after running without problems for a while

I am having a crash that I have no idea how to trace. I've created an InputManager from GameInstanceSubcomponent and there created a TMap with enums as key and value. Input is being processed over time, so the map is accessed every frame. After running for some time, the game would crash with the following:

See image

These lines are as follows:

59. m_InputActionScale[m_InputActionTypes[InputActionType]] += Scale;
114. if (!m_InputActionsConsumed[InputActionType] &&
            inputContext->Consume(InputActionType, m_InputActions[InputActionType], GetWorld()->DeltaTimeSeconds))

Any help is welcome!



from Recent Questions - Stack Overflow https://ift.tt/39jsa4o
https://ift.tt/eA8V8J

How to access data on server side from AJAX post request

I have tried reading a lot of posts on this but none have really helped me. I don't get how to access the data I am sending from a post request. For context, I have a .ejs html file where I am making an asynchronous post request to the server. This is the code for that:

                $("#commentButton" + thisPostId).click(function () {
                    $.ajax({
                        type: "POST",
                        url: "/comment",
                        data: {
                            comment: $("#commentInput" + thisPostId).val(),
                            postId: $("#postIdInput" + thisPostId).val()
                        },
                        success: function (data) {
                            if (data.success) {
                                let asyncComment = "<p>whatsupbro</p>";
                                $("#li" + thisPostId).append(asyncComment);
                            } else {
                                // ADD BETTER ERROR IMPL
                                alert('error');
                            }
                        }
                    });

On the server side, I want to retrieve the arguments in "data". This is what I have so far. I have tried so many things, like doing req.data.comment, req.comment, etc. Below is the start of my node.js function that is supposed to get the request and do some stuff with it. What matters is I want the comment in commentInfo and postId in commentInfo to be what I am sending in the post request as "comment" and "postId". I really am just not sure how to access this data (req.body.mycomment doesn't work either).

var createComment = function(req, res) {
    var commentInfo = {
        comment: req.body.myComment,
        username: req.session.username,
        commentId: new Date().getTime(),
        postId: req.body.postId
    };
    console.log(req['comment']);

Thanks for the help. If there is anything else I should add let me know.



from Recent Questions - Stack Overflow https://ift.tt/2J5sNnB
https://ift.tt/eA8V8J

Change discord bot nickname (discord.py)

I have a simple issue that I'm yet to figure out, how can I change my bot's own nickname, because I want to display information instead of its nickname continuously.

tried this :

await bot.user.edit(username=price)

but this actually changes the username which is not allowed to be done multiple times.

async def status_update():
    while True:
        price = str(get_BTC_price(ws))
        await bot.user.edit(username=price)
        await asyncio.sleep (2)

@bot.event
async def on_ready():
    bot.loop.create_task(status_update())

Thanks



from Recent Questions - Stack Overflow https://ift.tt/2J5Wi8N
https://ift.tt/eA8V8J

Unexpected behavior when appending to a Dict[str, list] - values are appended to all lists [duplicate]

I am iterating through a list and trying to appended values to a Dict[str, list] called plot. I look up the str-type key (real_key) to the appropriate list in plot and then I append a value (value) to that list.

some = x['string']

for od in some:
    conversion_key = od.get("@alias")
    real_key = field_conversion[conversion_key]
    value = od.get("#text")
    print(f"\nconversion_key: {conversion_key}\nreal_key: {real_key}\nvalue: {value}")
    # unexpected behavior from line below
    plot[real_key].append(value)
    pprint(plot)

As you can see, each value gets appended to all the lists in the dict, not just the list that is accessed by real_key. Why does this happen?

conversion_key: TemplateResRef
real_key: TemplateResRef
value: cod_bks_lite_tombs_1
{'PlotFlagEndsPlot': ['cod_bks_lite_tombs_1'],
 'PlotFlagJournal': ['cod_bks_lite_tombs_1'],
 'PlotFlagMultiReward': ['cod_bks_lite_tombs_1'],
 'PlotFlagReward': ['cod_bks_lite_tombs_1'],
 'PlotGUID': ['cod_bks_lite_tombs_1'],
 'PlotGUID2': ['cod_bks_lite_tombs_1'],
 'PlotName': ['cod_bks_lite_tombs_1'],
 'PlotParentGUID': ['cod_bks_lite_tombs_1'],
 'PlotScript': ['cod_bks_lite_tombs_1'],
 'TemplateResRef': ['cod_bks_lite_tombs_1']}

conversion_key: PlotFlags
real_key: PlotGUID
value: F400FDC4F9B24A5890F664E2966A7410
{'PlotFlagEndsPlot': ['cod_bks_lite_tombs_1',
                      'F400FDC4F9B24A5890F664E2966A7410'],
 'PlotFlagJournal': ['cod_bks_lite_tombs_1',
                     'F400FDC4F9B24A5890F664E2966A7410'],
 'PlotFlagMultiReward': ['cod_bks_lite_tombs_1',
                         'F400FDC4F9B24A5890F664E2966A7410'],
 'PlotFlagReward': ['cod_bks_lite_tombs_1', 'F400FDC4F9B24A5890F664E2966A7410'],
 'PlotGUID': ['cod_bks_lite_tombs_1', 'F400FDC4F9B24A5890F664E2966A7410'],
 'PlotGUID2': ['cod_bks_lite_tombs_1', 'F400FDC4F9B24A5890F664E2966A7410'],
 'PlotName': ['cod_bks_lite_tombs_1', 'F400FDC4F9B24A5890F664E2966A7410'],
 'PlotParentGUID': ['cod_bks_lite_tombs_1', 'F400FDC4F9B24A5890F664E2966A7410'],
 'PlotScript': ['cod_bks_lite_tombs_1', 'F400FDC4F9B24A5890F664E2966A7410'],
 'TemplateResRef': ['cod_bks_lite_tombs_1', 'F400FDC4F9B24A5890F664E2966A7410']}

For reference, the initial empty dict of lists (called plot) and the conversion dict (field_conversion) that translates between keys is below:

field_conversion = {
    "PlotFlags": "PlotGUID",
    "PlotFlagID": "PlotName",
    "PlotFlagName": "PlotScript",
    "PlotFlagReward": "PlotFlagReward",
    "PlotFlagJournal": "PlotFlagJournal",
    "PlotName": "PlotParentGUID",
    "PlotFlagMultiReward": "PlotFlagMultiReward",
    "PlotFlagEndsPlot": "PlotFlagEndsPlot",
    "PlotGUID": "PlotGUID2",
    "TemplateResRef": "TemplateResRef"
}

plot = dict.fromkeys(list(field_conversion.values()), [])
plot
{'PlotGUID': [],
 'PlotName': [],
 'PlotScript': [],
 'PlotFlagReward': [],
 'PlotFlagJournal': [],
 'PlotParentGUID': [],
 'PlotFlagMultiReward': [],
 'PlotFlagEndsPlot': [],
 'PlotGUID2': [],
 'TemplateResRef': []}

EDIT/SOLUTION:

Maybe it's better to delete this post, but when I implemented my dic, plot this way:

plot = dict.fromkeys(list(field_conversion.values()), [])

All its values point to the same [] held in memory. So updating one key updates all the lists, because the lists are all the same object.

Implementing the dict this way fixed it.

for val in field_conversion.values():
    plot[val] = []


from Recent Questions - Stack Overflow https://ift.tt/3lfm6ML
https://ift.tt/eA8V8J

Best way to perform large amount of Pandas Joins

I am trying to use two data frames for a simple lookup using Pandas. I have a main master data frame (left) and a lookup data frame (right). I want to left join them on the matching integer code and return the item title from the item_df.

I see a slight solution with a key value pair idea but it seems cumbersome. My idea is to merge the data frames together using col3 and name as key columns and keep the value from the right frame that I want which will be title. Thus I decide to drop the key column that I joined on so all I have left is the value. Now lets say I want to do this several times with my own manual naming conventions. For this I use rename to rename the value that I merged in. Now I would repeat this merge operation and rename my next join to something like second_title (see example below).

Is there a less cumbersome way to perform this repeated operation without constantly dropping the extra columns that are merged in and renaming the new column between each merge step?

Example code below:

import pandas as pd

master_dict: dict = {'col1': [3,4,8,10], 'col2': [5,6,9,10], 'col3': [50,55,59,60]}
master_df: pd.DataFrame = pd.DataFrame(master_dict)
item_dict: dict = {'name': [55,59,50,5,6,7], 'title': ['p1','p2','p3','p4','p5','p6']}
item_df: pd.DataFrame = pd.DataFrame(item_dict)
    
print(master_df.head())
   col1  col2  col3
0     3     5    50
1     4     6    55
2     8     9    59
3    10    10    60
print(item_df.head())
   name title
0    55    p1
1    59    p2
2    50    p3
3     5    p4
4     6    p5

# merge on col3 and name
combined_df = pd.merge(master_df, item_df, how = 'left', left_on = 'col3', right_on = 'name')
# rename title to "first_title"
combined_df.rename(columns = {'title':'first_title'}, inplace = True)
combined_df.drop(columns = ['name'], inplace = True) # remove 'name' column that was joined in from right frame
# repeat operation for "second_title"
combined_df = pd.merge(combined_df, item_df, how = 'left', left_on = 'col2', right_on = 'name')
combined_df.rename(columns = {'title': 'second_title'}, inplace = True)
combined_df.drop(columns = ['name'], inplace = True)
print(combined_df.head())
   col1  col2  col3 first_title second_title
0     3     5    50          p3           p4
1     4     6    55          p1           p5
2     8     9    59          p2          NaN
3    10    10    60         NaN          NaN


from Recent Questions - Stack Overflow https://ift.tt/2JiIW8L
https://ift.tt/eA8V8J