2021-08-31

How to deep clone the Class that contains DynamicObject in C#?

public class DynamicDictionary : System.Dynamic.DynamicObject
{
    Dictionary<string, object> dictionary = new Dictionary<string, object>();
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        string name = binder.Name;
        return dictionary.TryGetValue(name, out result);
    }
    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        dictionary[binder.Name] = value;
        return true;
    }
    public override System.Collections.Generic.IEnumerable<string> GetDynamicMemberNames()
    {
        return this.dictionary?.Keys;
    }
}
public class SerializeExtensions
{
    public string Name { get; set; }
    public DynamicDictionary DynamicObj { get; set; }
}

Please consider the above like my class.

I have a List of SerializeExtensions collection. Now I have to deep clone this list of collections.

This has been properly cloned when I am using the below code.

JsonConvert.DeserializeObject<List<SerializeExtensions>>(JsonConvert.SerializeObject(collection));

This serialization belongs to Newtonsoft.Json. But I need to System.Text.Json for serialization.

So when I am using System.Text.Json serialization, the DynamicObject field has reset to empty. the below code has used.

JsonSerializer.Deserialize<List<SerializeExtensions>>(JsonSerializer.Serialize(collection));

After the serialization, I am getting the output like below

Name: "John"
DynamicObj: {}

Actually, the DynamicObj count is 4 in my case before serialization.

is there any possible to deep clone this kind of class?



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

rails 6 dynamic bootstrap modal using js.erb error

I'm trying to display bootstrap modal with dynamically, so every time user click on record it shows modal with that record information. I don't want to show modal for all record every time I reload the page.

I got this error in browser console.

SyntaxError: Unexpected token '==='

Controller

events_controller.rb

def pay
  @event = Event.find(params[:id])
  respond_to do |format|
    format.js{}
  end
end

View

index.html.erb

<%= link_to pay_path(id: event.id), remote: true, class: "", method: :patch do %>
  Paid <i class="fe fe-dollar-sign"></i>
<% end %>

Pay view

    _pay.html.erb

    <!-- Modal: pay invoice -->
    <div class="modal fade show" id="pay_invoice" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-dialog-vertical" role="document">
            <div class="modal-content">
                <div class="modal-body">
                  <!-- Modal body -->
                </div>
            </div>
        </div>
    </div>

js.erb

pay.js.erb

document.querySelector("#pay_invoice").insertAdjacentHTML('afterbegin', "escape_javascript(<%= render partial: 'pay', locals: {event: @event} %>)");
document.querySelector("#pay_invoice").modal('show');

Routes

routes.rb

patch "events/:id/pay", to: "events#pay", as: :pay

any help?



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

Insert a level o in the existing data frame such that 4 columns are grouped as one

I want to do multiindexing for my data frame such that MAE,MSE,RMSE,MPE are grouped together and given a new index level. Similarly the rest of the four should be grouped together in the same level but different name

> mux3 = pd.MultiIndex.from_product([list('ABCD'),list('1234')],
> names=['one','two'])###dummy data 
>     df3 = pd.DataFrame(np.random.choice(10, (3, len(mux))), columns=mux3) #### dummy data frame
>     print(df3) #intended output required for the data frame in the picture given below

sample dataframe



from Recent Questions - Stack Overflow https://ift.tt/3kG3xmo
https://ift.tt/3BkwbjI

Keep Jenkins child process running after build completes

I am trying to figure out how to keep a process running after the Jenkins build completes.

I have a build step that is suppose to close the current node.exe process and start it again by calling "npm start". This is the contents of restart_node.bat

Taskkill /IM node.exe /F
cd C:\node
call npm start

I can see that is successfully stops and starts a new process, but as soon as the build completes.. the node.exe process gets killed. How can I leave it running after the build?

enter image description here



from Recent Questions - Stack Overflow https://ift.tt/3t1NxPj
https://ift.tt/38qYSPy

3000 tests - Major performance issues. What can be done?

Our react project has ~3000 jest tests. Most of them are just typical "render without crashing".

When we run npm test, the amount of memory used slowly climbs all the way to 22 Gb.

On machines with only 16 Gb, the tests grind the entire machine to a halt and take a very long time to finish.

What we have tried that has not worked or made the issue worse:

  1. --maxWorkers=50% or --maxWorkers=4 etc
  2. --runInBand (way too slow)
  3. --detectLeaks (half our tests have memory leaks according to this experimental option, but we have no idea what they are or even if they are the cause of this problem)

The only thing that works is running the tests on a machine with a large amount of RAM (>= 32Gb).

Any idea on how we can reduce the amount of memory used by these tests?



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

Unhandled Exception: Null check operator used on a null value in insert method

My app is a todo app, and I need to use a local database, I used sqflite lib and path lib, and i have some obstacles. in the main.dart:

void main() async{
  WidgetsFlutterBinding.ensureInitialized();
  final database=openDatabase(
      join(await getDatabasesPath(),'todo.db'),
    onCreate: (db,version){
        return db.execute('Create table todos(id INTEGER, title TEXT, dateTime DateTime, timeOfDay TimeOfDay)');
    },
    version: 1,
  );
  runApp(MyApp());
} 

in Add Todo screen i have a task title ,a date time and a time of day and i have a button to save this information into the database by this code:

TextButton(
              onPressed: ()async{
                  await insertTodo(Todo(0, 'num1', selectedDate , selectedTime));
                  //save();

              },

selectTime(BuildContext context)async{
    final TimeOfDay? selectedT=await showTimePicker(
        context: context,
        initialTime: selectedTime,

    );
    if(selectedT !=null && selectedT!=selectedTime){
      setState(() {
        selectedTime=selectedT;
      });
    }
    return selectedTime;
  }

  selectDate(BuildContext context)async{
    final DateTime? selected=await showDatePicker(
        context: context,
        initialDate: selectedDate,
        firstDate: DateTime(2010),
        lastDate: DateTime(2025),
    );

    if(selected !=null && selected!=selectedDate){
      setState(() {
        selectedDate=selected;
      });
    }
    return selectedDate;
  }

in todo class :

import 'package:flutter/material.dart';
import 'package:sqflite/sqflite.dart';
import 'package:todo_appv2/addTaskScreen.dart';
import 'package:todo_appv2/addTaskScreen.dart';

class Todo{
   final int id;
   final String title;
   final DateTime? dateTime;
   final TimeOfDay? timeOfDay;

  Todo(this.id, this.title, this.dateTime, this.timeOfDay,);
  
  Map<String,Object> toMap(){
    
    print('this is my $id value');
    return{
      'id':id,
      'title':title,
      'dateTime':dateTime!,
      'timeOfDay':timeOfDay!,
    };
  }

  @override
  String toString(){
    return 'Todo{id: $id, title: $title, dateTime:$dateTime, timeOfDay:$timeOfDay}';
  }

}

Future<void> insertTodo(Todo todo)async{
  final db= database;
  await db!.insert('todos', todo.toMap(),conflictAlgorithm: ConflictAlgorithm.replace);
}

when i run my app and tap to text button there is an error: ==> Unhandled Exception: Null check operator used on a null value the error from insertTodo Function , from todo.toMap() but i don't now why there is an error and how i fix it, please any help :\



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

How to tilt hover in CSS

I use this css style for hover:

.hvr-link{display:inline-block;vertical-align: middle;
  -webkit-transform: perspective(1px) translateZ(0);
  transform: perspective(1px) translateZ(0);
  box-shadow: 0 0 1px rgba(0, 0, 0, 0);
  position: relative;
  -webkit-transition-property: color;
  transition-property: color;
  -webkit-transition-duration: 0.3s;
  transition-duration: 0.3s;
}
.hvr-link:before {
  content: "";
  position: absolute;
  z-index: -1;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: #424141;
  -webkit-transform: scaleY(0);
  transform: scaleY(0);
  -webkit-transform-origin: 50%;
  transform-origin: 50%;
  -webkit-transition-property: transform;
  transition-property: transform;
  -webkit-transition-duration: 0.3s;
  transition-duration: 0.3s;
  -webkit-transition-timing-function: ease-out;
  transition-timing-function: ease-out;
}
.hvr-link:hover, .hvr-link:focus, .hvr-link:active{color: white;}
.hvr-link:hover:before, .hvr-link:focus:before, .hvr-link:active:before{-webkit-transform: scaleY(1); transform: scaleY(1);}

It shows like this.

And i want to make it look like this:

enter image description here

Help will be appreciated.



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

How to destroy Ionic Component on redirect

I have Ionic 4 Angular app. It has a three-tab structure. The tabs router module looks like this:

{
    path: 'tab1',
    loadChildren: () =>
      import('../tab1/tab1.module').then((m) => m.Tab1PageModule),
  },
  {
    path: 'tab2',
    loadChildren: () =>
      import('../tab2/tab2.module').then((m) => m.Tab2PageModule),
  },
  {
    path: 'tab3',
    loadChildren: () =>
      import('../tab3/tab3.module').then((m) => m.Tab3PageModule),
  }

On each tab I have different components which I want to be destroyed by a redirect to another tab. But the Component destroy event doesn't happen.

In my case Tab1 has this list:

  <ion-list>
    <ion-item routerLink="invites">Invites</ion-item>
    <ion-item>Friend Requests</ion-item>
  </ion-list>

'Invites' click takes me to the InvitesComponent. After that, if I click Tab2 InvitesComponent will stay there in its latest state. When I click Tab1 back I expect to see the default Tab1 screen but instead I meet by InvitesComponent opened.

I need somehow to destroy all child components by redirect events. I've already looked for (but no results):

  1. How to destroy angular component by redirect
  2. How to destroy angular component manually (programmatically)
  3. Any types of 'Refs' that could be injected to represent current component entity (to call destroy() manually)


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

Optimize postgres query avg by month

we have a report based on avg prices

basically, we filter those prices based on code and date and use UNION for each month

Table example:

date code price
2020-01-01 'FS-H21' 150
2020-01-01 'FS-G21' 155
2020-01-02 'FS-H21' 151
2020-01-03 'FS-G21' 148

and the query example:

SELECT period, code, avg(closure)
FROM period_prices
WHERE code = 'FS-F21' AND period BETWEEN '2020-01-01' AND '2020-01-31'
GROUP BY period, code

UNION

SELECT period, code, avg(closure)
FROM period_prices
WHERE code = 'FS-F21' AND period BETWEEN '2020-02-01' AND '2020-02-29'
GROUP BY period, code

...

Reproduced table and query at sample query...

I would like some advice on how can i improve the performance of that query, or if there is a better way to achieve this!

thanks



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

How do I get historical foreign exchange data on an hourly basis?

My code works. However, I'm receiving the output for each day. I wanted it to give me data for all business hours

library(priceR)

cur <- historical_exchange_rates("CAD", to = "USD",
                                 start_date = "2010-01-01", end_date = "2021-08-29")

print (cur)

 date one_CAD_equivalent_to_x_USD
1   2010-01-01                    0.956718
2   2010-01-02                    0.956718
3   2010-01-03                    0.956718
4   2010-01-04                    0.960639
5   2010-01-05                    0.962288

I want the output to show date, time and the rate

date        BH       conversion(CAD to USD)
2010-01-01  9:00:00   0.956718


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

Bests fit for a centered child image which parent container dimensions are unknown?

How do I achieve the best fit for a vertically and horizontally centered image which parent container dimensions are unknown?

See the below layouts (codepen for reference):

enter image description here

The child image fits its parent container as expected when at least one dimension of the child exceeds one dimension of the parent, but I cannot get the image to stretch and fill the parent when the image is smaller in both dimensions than its container (see 150x150 and 150x50 cases).

Hod do I achieve best fit for all cases using CSS only?

My css for reference (see link to codepen above):

.parent {
  position: relative;
  background: gray;

  display: inline-block;
}
.square {
  width: 200px;
  height: 200px;
}
.tall {
  width: 200px;
  height: 300px;
}
.wide {
  width: 300px;
  height: 200px;
}
.child {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  left: 0;
  right: 0;
  margin: auto;
  max-width: 100%;
  max-height: 100%;
}


from Recent Questions - Stack Overflow https://ift.tt/3gJ6aCI
https://ift.tt/3BqCYIJ

How to filter and sort nested objects? ReactJS

Data sample:

   const people = [
         1:{
           id : 1,
           name: 'James',
           age: 31,
           toBeDeleted: false,
           position: 2
         },
         2:{
           id : 2,
           name: 'John',
           age: 45,
           toBeDeleted: true,
           position: 3
         },
         3:{
           id : 3,
           name: 'Paul',
           age: 65,
           toBeDeleted: false,
           position: 1
         }
       ];

I try this way, but it doesn't work :

   const sorted = Object.values(people)
       .filter((people) => people.toBeDeleted !== true)
       .sort((a, b) => a.position - b.position);

If I delete the id keys, then my code works.

In result must be array like this :

   const people = [
         {
           id : 3,
           name: 'Paul',
           age: 65,
           toBeDeleted: false,
           position: 1
         },
         {
           id : 1,
           name: 'James',
           age: 31,
           toBeDeleted: false,
           position: 2
         }
       ];

the id keys are used in the project to select the necessary records, so I can't delete them



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

Problems when rotating the view matrix (OpenGL)

Setting: I have a view matrix which in the beginning is the identity matrix. R,U,F = X, Y, Z axes. I rotate the view matrix by creating a matrix from the given X,Y,Z rotation angles.

Problem: When I first rotate the view matrix by some Z angle (e.g. 45°) and subsequently rotate it by some Y angle, my scene doesn't rotate horizontally (e.g. from left to right), but in the direction given by the view matrix' Y axes.

What I had expected was that the view matrix, which is "tilted sideways" 45° whould then be rotated by my Y angle.

Here is some Python code:

viewer = CCamera ()
viewer.UpdateAngles (0,0,45) # bank 45°, i.e. tilt the scene 
viewer.UpdateAngles (0,10,0) # should rotate the scene sideways, simulating a change of heading

What happens is that the scene is rotated diagonally, i.e. around the Y axis of the "tilted" view angle.

import numpy as np

class CCamera:
    def __init__ (self, name = ""):
        self.orientation = CMatrix ()
        self.position = CVector (0,0,0)

    def Radians (self, a):
        if (a < 0):
            a += 360.0
        return a / 180.0 * np.pi

    def UpdateAngles (self, angles):
        m = CMatrix ()
        radX = self.Radians (angles.x)
        radY = self.Radians (angles.y)
        radZ = self.Radians (angles.z)
        m.CreateFromAngles (np.sin (radX), np.cos (radX), np.sin (radY), np.cos (radY), np.sin (radZ), np.cos (radZ))
        self.orientation *= m

CMatrix class:

class CMatrix:
    def __init__ (self):
        self.data = self.Identity ()

    def __getitem__ (self, index):
        return self.data [index]

    def __setitem__ (self, index, value):
        self.data [index] = value

    def Identity (self):
        return np.array ([CVector (1.0, 0.0, 0.0, 0.0), CVector (0.0, 1.0, 0.0, 0.0), CVector (0.0, 0.0, 1.0, 0.0), CVector (0.0, 0.0, 0.0, 1.0)])

    def Create (self, r, u, f):
        self.data = np.array ([r, u, f, CVector (0.0, 0.0, 0.0, 1.0)])
        return self

    def CreateFromAngles (self, sinX, cosX, sinY, cosY, sinZ, cosZ):
        return self.Create (CVector (cosY * cosZ, -cosY * sinZ, sinY),
                            CVector (sinX * sinY * cosZ + cosX * sinZ, 
                                     -sinX * sinY * sinZ + cosX * cosZ, 
                                     -sinX * cosY),
                            CVector (-cosX * sinY * cosZ + sinX * sinZ, 
                                     cosX * sinY * sinZ + sinX * cosZ, 
                                     cosX * cosY))

    def __imul__ (self, other):
        v = CVector (self [0].x, self [1].x, self [2].x)
        self [0].x = v.DotProduct (other [0])
        self [1].x = v.DotProduct (other [1])
        self [2].x = v.DotProduct (other [2])
        v = CVector (self [0].y, self [1].y, self [2].y)
        self [0].y = v.DotProduct (other [0])
        self [1].y = v.DotProduct (other [1])
        self [2].y = v.DotProduct (other [2])
        v = CVector (self [0].z, self [1].z, self [2].z)
        self [0].z = v.DotProduct (other [0])
        self [1].z = v.DotProduct (other [1])
        self [2].z = v.DotProduct (other [2])
        return self

Here are two pictures for illustration:

Rotation around Z axis (bank)

Rotation around Y axis (yaw)

What is my misunderstanding here? Shouldn't the second rotation rotate the tilted view matrix around the "absolute" Y axis?



from Recent Questions - Stack Overflow https://ift.tt/3zyUiee
https://ift.tt/3gMvKqv

Handling Infinity in JavaFX numerical TextField

I have a JavaFX TextField specialized to accept numbers, including scientific notation. It does pretty much everything I want. But, because it accepts scientific notation, it is easy for a user to enter a number beyond the range that can be represented by a double. When they do, the TextField displays "Infinity" (or "-Infinity"). When that happens the field can no longer be edited to correct the problem. The contents cannot be selected and deleted either. Tapping the "Escape" key does not return to the previous contents.

Here is an SSCCE, based closely on the answer by James_D to this question a few years ago.

import java.text.DecimalFormatSymbols;
import java.util.function.UnaryOperator;
import java.util.regex.Pattern;
import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.util.StringConverter;

public class NumericTextFieldDemo extends Application {

    char sep = new DecimalFormatSymbols().getDecimalSeparator();
    String negStarter = new StringBuilder("-").append(sep).toString();
    String posStarter = new StringBuilder("+").append(sep).toString();
    String patternStr = new StringBuilder()
            .append("[+|-]?(([1-9][0-9]*)|0)?(\\")
            .append(sep)
            .append("[0-9]*)?(([e|E][+|-]?[0-9]*)?)")
            .toString();
    Pattern validEditingState = Pattern.compile(patternStr);

    class NumericTextField extends TextField {

        UnaryOperator<TextFormatter.Change> filter = c -> {
            String text = c.getControlNewText();
            if (validEditingState.matcher(text).matches()) {
                return c;
            } else {
                return null;
            }
        };

        StringConverter<Double> converter = new StringConverter<Double>() {

            @Override
            public Double fromString(String s) {
                if (s.isEmpty() || "-".equals(s) || "+".equals(s)
                        || negStarter.equals(s) || posStarter.equals(s)) {
                    return 0.0;
                } else {
                    return Double.valueOf(s);
                }
            }

            @Override
            public String toString(Double d) {
                return d.toString();
            }
        };

        NumericTextField(double initValue) {
            TextFormatter<Double> textFormatter = new TextFormatter<>(converter, initValue, filter);
            textFormatter.valueProperty().addListener((ObservableValue<? extends Double> obs, Double oldValue, Double newValue) -> {
                System.out.println("User entered value: " + newValue);
            });
            setTextFormatter(textFormatter);
        }

        NumericTextField() {
            this(0.0);
        }
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        NumericTextField ntf = new NumericTextField();
        // Setting the font seems to be required on macOS.
        ntf.setFont(new Font("Arial", 14));

        VBox root = new VBox(5, ntf);
        root.setAlignment(Pos.CENTER);
        primaryStage.setScene(new Scene(root, 250, 150));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Is there any way to catch the infinities and leave the TextField in a usable state? Is there some change that could be made to the class to prevent entering such numbers in the first place?



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

Convert date column to columns 'start' and 'end' using regex

I have a pandas DataFrame with some text and dates as strings.

pd.DataFrame({'dates': ['start 01.01.2020',                      # Only start date
                        'start 10.10.2019, end 20.20.2019', 
                        '01.05.2019',                            # Only start date
                        '01.11.2019-04.11.2019']})

I want to create two new columns; start and end. Some rows have both start and end date, but some rows only have start date. For rows with only start date, the start and end date is the same.

The resulting table should look like this:

enter image description here

So far I've tried to extract the dates using regex, but I cannot seem to figure it out.



from Recent Questions - Stack Overflow https://ift.tt/3jv4RJw
https://ift.tt/3sZNLqb

Why mdev or udev does not create disk nodes when used kernel is from any distribution

I created a minimal linux init with just busybox to do experiments or use it to recover my work linux. But i got stuck and was fustruted alot that i could not find any disks in /dev. I tried both mounting udev as devtmpfs and tmpfs with mdev -s. Both none seemed to work. Lickily i tried compiling a kernel and booting it i realised kernel was the issue. I also noticed my pluged mouse light was off as if the pc was turned off

I tried kernel from both debian and ubuntu. But same result.

Now im happy with what i got. But using custom kernel means i cant make use of the already existing drivers on a target linux when i do chroot.

So i wanna know why the kernels that come with distros does not generate disk blocks



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

looping through a list of dataframes, writing each element of that list to a new .csv file on disk

I have a list of dataframes and am attempting to export each using the pandas.df.to_csv method to a folder on disk. However, only the last item in the list of dataframes is being written to disk as a .csv

Please see code below:

import pandas as pd
import os
import datetime
from pathlib import Path

CSV_Folder = Path('C:\PA_Boundaries\Tests')
Output = r'C:/PA_Boundaries/test_output'

today = datetime.date.today()
date = today.strftime('%Y%m%d')

try:
    dfs = []
    for file in os.listdir(CSV_Folder):
        df = pd.read_csv(CSV_Folder / file)
        dfs.append(df)
    
    new_dfs = []
    for df in dfs:
        new_df = pd.DataFrame()
        new_df['Original Addr string'] = df['StreetConc']
        new_df['Addr #'] = df['AddNum']
        new_df['Prefix'] = df['StPreDir']
        new_df['Street Name'] = df['StName']
        new_df['StreetType'] = df['StType']
        new_df['Suffix'] = df['StDir']
        new_df['Multi-Unit'] = ''
        new_df['City'] = df['City']
        new_df['Zip Code'] = df['PostCode']
        new_df['4'] = df['PostalExt']
        new_df['County'] = df['CountyID']
        new_df['Addr Type'] = ''
        new_df['Precint Part Name'] = ''
        new_df['Lat'] = df['X']
        new_df['Long'] = df['Y']
    
    
        replaced_address_names = []
        for index, row in new_df.iterrows():
            new_row = row['Original Addr string'].replace(',', ' ')
            replaced_address_names.append(new_row)
        
        
        new_df['Original Addr string'] = replaced_address_names
        
        county_id = df.iloc[0, 37]
    
        new_dfs.append(new_df)
        
    for i in range(len(new_dfs)):
        new_dfs[i].to_csv(f'{Output}\ADDR_{county_id}_{date}.csv', index=False)

except FileNotFoundError:
    print(f'{file} not found in {CSV_Folder}')

except PermissionError:
    print('Check syntax of paths')

else:
    print('Process Complete')

new_dfs contains the correct number of dataframes. However, when looping through the new list of dataframes and calling .to_csv on each item in the list, only the last item in the list is written to the disk.



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

Render component of logged client type using React Hooks

I am new to react and react hooks. I am currently working on a coupon project with a back end using spring boot.

I am able to be using a login form using react hooks which successfully logs in with credentials.

My issue is how do I redirect to the specific component once logged in depending on the client type.

e.g if I log in as a CUSTOMER. react will redirect me to Customer component.

In my project I have 3 different client types. ADMINISTRATOR COMPANY CUSTOMER

I am not entirely sure on what approach I should use for this method

Login form:

import { Button } from "../Button/Button";
import "./Login.scss";
import loginImage from "../Assets/login.png";
import { NavLink, useHistory } from "react-router-dom";
import { useForm } from "react-hook-form";
import Select from 'react-select';
import CredentialsModel from "../../Models/CredentialsModel";
import axios from "axios";
import globals from "../../Services/Globals";
import notify, { SccMsg } from "../../Services/Notifications";
import CompanyModel from "../../Models/CouponModel";
import { loginAction } from "../../Redux/AuthState";
import store from "../../Redux/Store";
import UserModel from "../../Models/UserModel";
import Customer from "../CustomerArea/Customer/Customer";

const colourStyles = {
    control: (styles: any) => ({
        ...styles,
        backgroundColor: 'white', borderColor: 'black'
    }),
}

function Login(): JSX.Element {

    const history = useHistory(); 
    const { register, handleSubmit, formState: { errors } } = useForm<CredentialsModel>();

    const options = [
        { value: 'Select Type', label: 'Select Type', isDisabled: true },
        { value: 'Administrator', label: 'Administrator' },
        { value: 'Client', label: 'Client' },
        { value: 'Customer', label: 'Customer' }
    ]

    const SelectBox = () => (
        <Select styles={colourStyles} placeholder={'Select Type'} options={options} />
    )

    async function send(credentials: CredentialsModel) {
        console.log(credentials);
        try {
            const response = await axios.post<UserModel>(globals.urls.client + "login", credentials);
            console.log(response.data);
            store.dispatch(loginAction(response.data));
            notify.success(SccMsg.LOGIN_SUCCESS);

            history.push("/customer"); // Redirect to customer if success
        }
        catch (err) {
            notify.error(err);
        }
    }

    return (
        <div className="base-container " >
            <form onSubmit={handleSubmit(send)}>
                <div className="header" ></div>
                <div className="content">
                    <div className="image">
                        <img src={loginImage} />
                    </div>

                    <div className="form">
                        <div className="form-group">
                            <label htmlFor="username">Email</label>
                            <input type="email" placeholder="📧 email"
                                {...register("email", { required: true, pattern: /^\S+@\S+$/i })}
                            />
                            {errors.email?.type === 'required' && <span>Enter a valid email address</span>}
                        </div>

                        <div className="form-group">
                            <label htmlFor="username">Password</label>
                            <input type="password" placeholder="🔑 password"
                                {...register("password", {
                                    required: true,
                                    minLength: 4,
                                    maxLength: 12,
                                })}
                            />
                            {errors.password?.type === 'required' && <span>You must enter a password</span>}
                            {errors.password?.type === 'minLength' && <span>Password too short</span>}
                            {errors.password?.type === 'maxLength' && <span>Password too long</span>}

                        </div>
                        <div className="form-group">
                            <div className="loginas">Login as:</div>
                            <div className="">
                                {/* <SelectBox  /> */}
                                <select  name="ClientType" >
                                <option  value="ADMIN">ADMIN</option>
                                <option   value="Customer">Customer</option>
                                <option value="COMPANY">COMPANY</option>

                                </select>

                                
                            </div>
                        </div>
                    </div>
                </div>
                
                <div className="footer">
                    <Button type="submit" className=".btn" buttonStyle='btn--outline'>Login</Button>
                </div>
                <div className="register">
                    <p >
                        Don't have an account?
                        <br />
                        Please click here to <NavLink to="/Register"> REGISTER</NavLink>
                    </p>
                </div>
            </form>
        </div>

    );
}


export default Login;

As you can see I have an example of a send function for customer only. I would like to know the best approach for if I have 3 different client types and upon submit I will be redirected accordingly.

Customer Component

import axios from "axios";
import { Component } from "react";
import CouponModel from "../../../Models/CouponModel";
import CustomerModel from "../../../Models/CustomerModel";
import { couponsAction } from "../../../Redux/CouponState";
import store from "../../../Redux/Store";
import Card2 from "../../Card/Card2";
import "./Customer.css";

interface CustomerState {

    
    coupons: CouponModel[];
 
 }

class Customer extends Component <{}, CustomerState, CouponModel> {

    public constructor (props: {}) {
        super(props);
        this.state = {
            coupons: store.getState().couponState.coupons,
        };
    }


    public async componentDidMount () {

        try {
            const response = await axios.get<CouponModel[]>('http://localhost:8080/api/customer/my/coupons');
    
            store.dispatch(couponsAction(response.data)); // Updating global state
    
            this.setState({coupons: response.data});
        } catch (err) {
            alert(err.message);
        }

    }

    public render(): JSX.Element {
        return (
            <div className="Customer">

                <h1>This is customer page as logged</h1>

    
            {this.state.coupons.map(c => <Card2 key={c.id} coupon={c} />)}
                
            </div>
        );
    }
}

export default Customer;

Hope I am clear. I could add anymore information if needed.



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

How to handle aggregated query results with SQLAlchemy, pydantic and FastAPI

I would like to create an API that returns the aggregated values for each department as a response. I am new to FastAPI and pydantic and would appreciate any support. It seems the part where the query results are mapped in pydantic is not working well.

get method in main.py

@app.get("/api/{client_id}", response_model=List[schemas.Overview])
def read_overview(client_id: str, db: Session = Depends(get_db)):
    db_overview = crud.get_overview(db, client_id=client_id)
    if db_overview is None:
        raise HTTPException(status_code=404, detail="Overview not found")
    return db_overview

crud.py Get the data corresponding to the three department codes, 1000001, 1000002, and 2000001, aggregated by client_id and deptCode.

from sqlalchemy.orm import Session
from sqlalchemy import func
from . import models, schemas
import datetime

def get_overview(db: Session, client_id: str):
    text = '1000001,1000002,2000001'
    depts = text.split(',')
    tbl = models.Overview
       overview = db.query(tbl.client_id, tbl.deptCode, tbl.deptName, func.sum(tbl.count), func.sum(tbl.item1), func.sum(tbl.item2), func.sum(tbl.item3), func.sum(tbl.item4), func.sum(tbl.item5), func.sum(tbl.item6)).\
        filter(tbl.client_id==client_id). \
        filter(tbl.deptCode.in_(depts)). \
        group_by(tbl.client_id, tbl.deptCode, tbl.deptName).all()
    # print(“overview”, overview)
    return overview

If I check the result retrieved by QUERY with print(), I can see that three rows have been retrieved as expected.

Result - overview on terminal by using print()

[('C012345', '1000001', 'A地域', Decimal('25'), Decimal('7'), Decimal('0'), Decimal('2'), Decimal('0'), Decimal('0'), Decimal('0')), ('C012345', '1000002', 'Z地域', Decimal('55'), Decimal('15'), Decimal('2'), Decimal('12'), Decimal('0'), Decimal('0'), Decimal('0')), ('C012345', '2000001', 'あ小学校', Decimal('15'), Decimal('5'), Decimal('0'), Decimal('2'), Decimal('0'), Decimal('0'), Decimal('0'))]

However, I get the error message "value is not a valid integer" and "field required", resulting in an error as follows. Error

  File "/Users/junya/mr2edu_server/venv/lib/python3.9/site-packages/fastapi/routing.py", line 137, in serialize_response
    raise ValidationError(errors, field.type_)
pydantic.error_wrappers.ValidationError: 21 validation errors for Overview
response -> 0 -> count
  value is not a valid integer (type=type_error.integer)
response -> 0 -> item1
  field required (type=value_error.missing)
response -> 0 -> item2
  field required (type=value_error.missing)
response -> 0 -> item3
  field required (type=value_error.missing)
response -> 0 -> item4
  field required (type=value_error.missing)
response -> 0 -> item5
  field required (type=value_error.missing)
response -> 0 -> item6
  field required (type=value_error.missing)

…. continued ...

I also show schemas.py and models.py.

schemas.py

from pydantic import BaseModel
import datetime

class Overview(BaseModel):
    client_id: str
    deptCode: str
    deptName: str
    count: int
    item1: int
    item2: int
    item3: int
    item4: int
    item5: int
    item6: int

    class Config:
        orm_mode = True

models.py

from sqlalchemy import Column, Date, Integer, String
from sqlalchemy.orm import relationship

from .database import Base

class Overview(Base):
    __tablename__ = "overview"
    id = Column(String, primary_key=True, index=True)
    client_id = Column(String)
    date = Column(Date)
    deptCode = Column(String)
    deptName = Column(String)
    level = Column(Integer)
    count = Column(Integer)
    item1 = Column(Integer)
    item2 = Column(Integer)
    item3 = Column(Integer)
    item4 = Column(Integer)
    item5 = Column(Integer)
    item6 = Column(Integer)


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

Is there any potential problem with double-check lock for C++?

Here is a simple code snippet for demonstration.

Somebody told me that the double-check lock is incorrect. Since the variable is non-volatile, the compiler is free to reorder the calls or optimize them away(For details, see codereview.stackexchange.com/a/266302/226000).

But I really saw such a code snippet is used in many projects indeed. Could somebody shed some light on this matter? I googled and talked about it with my friends, but I still can't find out the answer.

#include <iostream>
#include <mutex>
#include <fstream>

namespace DemoLogger
{
    void InitFd()
    {
        if (!is_log_file_ready)
        {
            std::lock_guard<std::mutex> guard(log_mutex);
            if (!is_log_file_ready)
            {
                log_stream.open("sdk.log", std::ofstream::out | std::ofstream::trunc);
                is_log_file_ready = true;
            }
        }
    }


    extern static bool is_log_file_ready;
    extern static std::mutex log_mutex;
    extern static std::ofstream log_stream;
}

//cpp
namespace DemoLogger
{
    bool is_log_file_ready{false};
    std::mutex log_mutex;
    std::ofstream log_stream;
}

UPDATE: Thanks to all of you. There is better implementation for InitFd() indeed, but it's only a simple demo indeed, what I really want to know is that whether there is any potential problem with double-check lock or not.

For the complete code snippet, see https://codereview.stackexchange.com/questions/266282/c-logger-by-template.



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

How to secure web api to validate openid token generated by Client application?

OpenId Connect configuration in start up.cs file of Client app :

services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie()

            .AddOpenIdConnect(options =>
            {
                options.ClientId = azureAdConfig.ClientId;
                options.ClientSecret = azureAdConfig.ClientSecret;
                options.Authority = string.Format(https://login.microsoftonline.com/, azureAdConfig.Tenant);
                options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
                options.Resource = azureAdConfig.ResourceURI_Graph;
                options.Events = new AuthEvents(azureAdConfig, connectionStringsConfig);
            });

I want to pass the token to web api.

But how to secure web api and validate the token in api project?



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

how to put data into Excel table with for loop pandas?

Following my previous question, now i'm trying to put data in a table and convert it to an excel file but i can't get the table i want, the excel file contains just the last hotel in my list if anyone can help or explain what's the cause of it, this is the final output i want to get

enter image description here

this the data i'm printing

Byzance Nabeul : Chambre Double - {'All Inclusive soft': ('208', '166', '25%'), 'Demi Pension': 138}
Palmyra Club Nabeul Nabeul : Double Standard - {'All Inclusive soft': ('225', '180', '25%')}

and here is my code

#!/usr/bin/env python
# coding: utf-8
import time
from time import sleep
import ast
import xlwt
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait, Select
from selenium.common.exceptions import StaleElementReferenceException, NoSuchElementException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import pandas as pd


driver = webdriver.Chrome("C:\\Users\\marketing2\\Documents\\chromedriver.exe")
driver.get('https://tn.tunisiebooking.com/')

def exists(xpath):
        try:
            driver.find_element_by_id(xpath);
        except NoSuchElementException:
            return "false"
        else:
            return "true"

# params to select
params = {
    'destination': 'Nabeul',
    'date_from': '11/09/2021',
    'date_to': '12/09/2021',
    'bedroom': '1'
}

# select destination
destination_select = Select(WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, 'ville_des'))))
destination_select.select_by_value(params['destination'])

# select bedroom
bedroom_select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, 'select_ch'))))
bedroom_select.select_by_value(params['bedroom'])

# select dates
script = f"document.getElementById('checkin').value ='{params['date_from']}';"
script += f"document.getElementById('checkout').value ='{params['date_to']}';"
script +=  f"document.getElementById('depart').value ='{params['date_from']}';"
script += f"document.getElementById('arrivee').value ='{params['date_to']}';"
driver.execute_script(script)

# submit form
btn_rechercher = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="boutonr"]')))
btn_rechercher.click()
    
#----------   
if (exists('plus_res')=="true"):
   
    btn_plus = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, 'plus_res')))
    btn_plus.click()
    sleep(10)
else :
    pass
    
urls = []    
records = []
hotels = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.XPATH, "//div[starts-with(@id,'produit_affair')]")))

for hotel in hotels:
    link = hotel.find_element_by_xpath(".//span[@class='tittre_hotel']/a").get_attribute("href")
    urls.append(link)

for url in urls:
    driver.get(url)
       
    def existsElement(xpath):
        try:
            driver.find_element_by_id(xpath);
        except NoSuchElementException:
            return "false"
        else:
            return "true"
   
    if (existsElement('result_par_arrangement')=="false"):
   
        btn_t = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="moteur_rech"]/form/div/div[3]/div')))

        btn_t.click()
        sleep(10)
    else :
        pass
               
    
    try:
        name = str(WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//div[@class='bloc_titre_hotels']/h2"))).text)
        arropt = driver.find_element_by_xpath("//div[contains(@class,'line_result')][1]")
        opt = str(arropt.find_element_by_tag_name("b").text)
        num = len(arropt.find_elements_by_tag_name("option"))
        optiondata = {}
        achats = {}
        marges= {}
        selection = Select(driver.find_element_by_id("arrangement"))

        for i in range(num):
            try:
                selection = Select(driver.find_element_by_id("arrangement"))
                selection.select_by_index(i)
                time.sleep(2)

                arr = driver.find_element_by_xpath("//select[@id='arrangement']/option[@selected='selected']").text
                prize = driver.find_element_by_id("prix_total").text

                optiondata[arr] = (int(prize))

                btn_passe = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="resultat"]/div/form/div/div[2]/div[1]/div[2]/div[2]/div')))
                btn_passe.click()



                # params to select
                params = {
                            'civilite_acheteur': 'Mlle',
                            'prenom_acheteur': 'test',
                            'nom_acheteur': 'test',
                            'e_mail_acheteur': 'test@gmail.com',
                            'portable_acheteur': '22222222',
                            'ville_acheteur': 'Test',
                        }

                # select civilite
                civilite_acheteur = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.NAME, 'civilite_acheteur'))))
                civilite_acheteur.select_by_value(params['civilite_acheteur'])

                # saisir prenom 
                script  = f"document.getElementsByName('prenom_acheteur')[0].value ='{params['prenom_acheteur']}';"
                script += f"document.getElementsByName('nom_acheteur')[0].value ='{params['nom_acheteur']}';"
                script += f"document.getElementsByName('e_mail_acheteur')[0].value ='{params['e_mail_acheteur']}';"
                script += f"document.getElementsByName('portable_acheteur')[0].value ='{params['portable_acheteur']}';"
                script += f"document.getElementsByName('ville_acheteur')[0].value ='{params['ville_acheteur']}';"
                driver.execute_script(script)

                # submit form
                btn_agence = driver.find_element_by_id('titre_Nabeul')
                btn_agence.click()

                btn_continuez = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, 'boutonr')))
                btn_continuez.click()

                achat = str(int(driver.find_element_by_xpath('/html/body/header/div[2]/div[1]/div[1]/div[4]/div[2]/div[2]').text.replace(' TND', '')))

                achats[arr]=achat

                marge =str(int(((float(prize) - float(achat)) / float(achat)) * 100))+"%";
                marges[arr]=marge
                optiondata[arr]=prize,achat,marge
                
                
                driver.get(url)
                btn_display = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="moteur_rech"]/form/div/div[3]/div')))

                btn_display.click()
                sleep(10)
               

            except StaleElementReferenceException:
                pass

            

    except NoSuchElementException:
        pass
    

    s="{} : {} - {}".format(name, opt, optiondata)
    

    ds = []

    for l in s.splitlines():
            d = l.split("-")

            if len(d) > 1:
                df = pd.DataFrame(ast.literal_eval(d[1].strip()))
                ds.append(df)
    for df in ds:
            df.reset_index(drop=True, inplace=True)

    df = pd.concat(ds, axis= 1)

    cols = df.columns

    cols = [((col.split('.')[0], col)) for col in df.columns]

    df.columns=pd.MultiIndex.from_tuples(cols)

    print(df.T)
    df.to_excel("v.xlsx")

it's displaying "Palmyra club Nabeul Nabeul" only How can i solve the probleme please this the final and most important part and thank you in advance.



from Recent Questions - Stack Overflow https://ift.tt/3BtmkID
https://ift.tt/38nsqh2

Outlook VBA extract text from custom flags

I am fairly new to MS Outlook 2016 VBA. I handle a considerable number of emails every day on a 24x7 basis. I keep on flagging emails with custom text to enable me to track emails and correlate each with the other.

Unfortunately, however, I do not understand as to how to write an Outlook VBA to extract emails that are flagged along with custom texts in each flagged email in a folder.

I could manage to follow VBA code available at VBA Express forum. The code is as follows:

Sub CountItems()
    Dim objMainFolder As Outlook.folder
    Dim lItemsCount As Long
 
    'Select a folder
    Set objMainFolder = Outlook.Application.Session.PickFolder
 
    If objMainFolder Is Nothing Then
       MsgBox "You choose select a valid folder!", vbExclamation + vbOKOnly, "Warning for Pick Folder"
    Else
       'Initialize the total count
       lItemsCount = 0
       Call LoopFolders(objMainFolder, lItemsCount)
    End If
 
    'Display a message for the total count
    MsgBox "There are " & lItemsCount & " items in the " & objMainFolder.Name & " folder Including its subfolders.", vbInformation, "Count Items"
End Sub


Sub LoopFolders(ByVal objCurrentFolder As Outlook.folder, lCurrentItemsCount As Long)
    Dim objSubfolder As Outlook.folder
 
    lCurrentItemsCount = lCurrentItemsCount + objCurrentFolder.Items.Count
 
    'Process all folders and subfolders recursively
    If objCurrentFolder.Folders.Count Then
       For Each objSubfolder In objCurrentFolder.Folders
           Call LoopFolders(objSubfolder, lCurrentItemsCount)
       Next
    End If
End Sub

After running the code, I could understand that it displays the count of emails in a folder and its subfolders.

It would be very helpful if someone could please guide me to relevant documentation that can help me create VBA required.


Interestingly, I stumbled across this page which partially solves my problem. The question is titled "How do you access custom Follow-Up flag values (“Flag to…”) in Outlook 2016?"

The solution, from what I could understand, pivots around the Search Folder in Outlook mail client and setting custom view by All Mail fields and Follow Up Flag and then setting the condition of the latter to "is not empty". Grouping by "Follow Up Flag" ascending then displays the custom flags in groups for easy reference.

However, that still does not solve the problem of listing the custom flag values. Any pointers will be very helpful.



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

2021-08-30

I need help deploying my vue app on netlify

I've done this many times in the past, I'm getting this error in the netlify logs. The repo I am attempting to deploy is https://github.com/yanyamz/Key_Visual_Arts.

I checked to see if it was within size limitations of Netlify and it is, totally 15mb or so vs the 20+mb that you can deploy on netlify.

12:03:03 PM: Build ready to start
12:03:04 PM: build-image version: fa439ad1ab9393b2c0d449d8d7c033927683f4b0
12:03:04 PM: build-image tag: v4.3.0
12:03:04 PM: buildbot version: 0f2f658d862cfe72bae7cc05c6a8de0426a5a0e2
12:03:04 PM: Fetching cached dependencies
12:03:05 PM: Failed to fetch cache, continuing with build
12:03:05 PM: Starting to prepare the repo for build
12:03:05 PM: No cached dependencies found. Cloning fresh repo
12:03:05 PM: git clone https://github.com/yanyamz/Key_Visual_Arts
12:03:07 PM: Preparing Git Reference refs/heads/main
12:03:07 PM: Parsing package.json dependencies
12:03:08 PM: 
​
❯ Initial build environment
baseRelDir: true
branch: main
context: production
cwd: /opt/build/repo
featureFlags: []
mode: buildbot
repositoryRoot: /opt/build/repo
siteId: 9cc686ee-a337-4ebf-886c-99acf9adfe45
​
❯ UI build settings
baseRelDir: true
build:
  command: npm run build
  environment:
    - NETLIFY_BUILD_DEBUG
  publish: dist
​
❯ Resolved build environment
branch: main
buildDir: /opt/build/repo
context: production
env: []
​
❯ Resolved config
build:
  command: npm run build
  commandOrigin: ui
  environment:
    - NETLIFY_BUILD_DEBUG
  publish: /opt/build/repo/dist
  publishOrigin: ui

12:03:08 PM: Starting build script
12:03:08 PM: Installing dependencies
12:03:08 PM: Python version set to 2.7
12:03:09 PM: Downloading and installing node v16.8.0...
12:03:09 PM: Downloading https://nodejs.org/dist/v16.8.0/node-v16.8.0-linux-x64.tar.xz...
12:03:09 PM: Computing checksum with sha256sum
12:03:09 PM: Checksums matched!
12:03:12 PM: Now using node v16.8.0 (npm v7.21.0)
12:03:12 PM: Started restoring cached build plugins
12:03:12 PM: Finished restoring cached build plugins
12:03:12 PM: Attempting ruby version 2.7.2, read from environment
12:03:13 PM: Using ruby version 2.7.2
12:03:14 PM: Using PHP version 8.0
12:03:14 PM: Started restoring cached node modules
12:03:14 PM: Finished restoring cached node modules
12:03:14 PM: Installing NPM modules using NPM version 7.21.0
12:03:16 PM: npm WARN old lockfile
12:03:16 PM: npm WARN old lockfile The package-lock.json file was created with an old version of npm,
12:03:16 PM: npm WARN old lockfile so supplemental metadata must be fetched from the registry.
12:03:16 PM: npm WARN old lockfile
12:03:16 PM: npm WARN old lockfile This is a one-time fix-up, please be patient...
12:03:16 PM: npm WARN old lockfile
12:03:18 PM: npm WARN old lockfile vue-loader-v16: No matching version found for vue-loader-v16@16.5.0.
12:03:18 PM: npm WARN old lockfile     at module.exports (/opt/buildhome/.nvm/versions/node/v16.8.0/lib/node_modules/npm/node_modules/npm-pick-manifest/index.js:209:23)
12:03:18 PM: npm WARN old lockfile     at /opt/buildhome/.nvm/versions/node/v16.8.0/lib/node_modules/npm/node_modules/pacote/lib/registry.js:118:26
12:03:18 PM: npm WARN old lockfile     at async Array.<anonymous> (/opt/buildhome/.nvm/versions/node/v16.8.0/lib/node_modules/npm/node_modules/@npmcli/arborist/lib/arborist/build-ideal-tree.js:691:9)
12:03:18 PM: npm WARN old lockfile  Could not fetch metadata for vue-loader-v16@16.5.0 vue-loader-v16: No matching version found for vue-loader-v16@16.5.0.
12:03:18 PM: npm WARN old lockfile     at module.exports (/opt/buildhome/.nvm/versions/node/v16.8.0/lib/node_modules/npm/node_modules/npm-pick-manifest/index.js:209:23)
12:03:18 PM: npm WARN old lockfile     at /opt/buildhome/.nvm/versions/node/v16.8.0/lib/node_modules/npm/node_modules/pacote/lib/registry.js:118:26
12:03:18 PM: npm WARN old lockfile     at async Array.<anonymous> (/opt/buildhome/.nvm/versions/node/v16.8.0/lib/node_modules/npm/node_modules/@npmcli/arborist/lib/arborist/build-ideal-tree.js:691:9) {
12:03:18 PM: npm WARN old lockfile   code: 'ETARGET',
12:03:18 PM: npm WARN old lockfile   type: 'version',
12:03:18 PM: npm WARN old lockfile   wanted: '16.5.0',
12:03:18 PM: npm WARN old lockfile   versions: [
12:03:18 PM: npm WARN old lockfile     '16.0.0-beta.5',
12:03:18 PM: npm WARN old lockfile     '16.0.0-beta.5.1',
12:03:18 PM: npm WARN old lockfile     '16.0.0-beta.5.2',
12:03:18 PM: npm WARN old lockfile     '16.0.0-beta.5.3',
12:03:18 PM: npm WARN old lockfile     '16.0.0-beta.5.4'
12:03:18 PM: npm WARN old lockfile   ],
12:03:18 PM: npm WARN old lockfile   distTags: { latest: '16.0.0-beta.5.4' },
12:03:18 PM: npm WARN old lockfile   defaultTag: 'latest'
12:03:18 PM: npm WARN old lockfile }
12:03:33 PM: npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
12:03:33 PM: npm WARN deprecated har-validator@5.1.5: this library is no longer supported
12:03:33 PM: npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated
12:03:34 PM: npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
12:03:35 PM: npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
12:03:37 PM: npm WARN deprecated querystring@0.2.0: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
12:03:38 PM: npm WARN deprecated eslint-loader@2.2.1: This loader has been deprecated. Please use eslint-webpack-plugin
12:03:39 PM: npm WARN deprecated html-webpack-plugin@3.2.0: 3.x is no longer supported
12:03:40 PM: npm WARN deprecated babel-eslint@10.1.0: babel-eslint is now @babel/eslint-parser. This package will no longer receive updates.
12:03:40 PM: npm WARN deprecated @hapi/topo@3.1.6: This version has been deprecated and is no longer supported or maintained
12:03:40 PM: npm WARN deprecated @hapi/bourne@1.3.2: This version has been deprecated and is no longer supported or maintained
12:03:41 PM: npm WARN deprecated @hapi/address@2.1.4: Moved to 'npm install @sideway/address'
12:03:42 PM: npm WARN deprecated chokidar@2.1.8: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies.
12:03:42 PM: npm WARN deprecated @hapi/hoek@8.5.1: This version has been deprecated and is no longer supported or maintained
12:03:42 PM: npm WARN deprecated chokidar@2.1.8: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies.
12:03:43 PM: npm WARN deprecated @hapi/joi@15.1.1: Switch to 'npm install joi'
12:03:43 PM: npm WARN deprecated tar@2.2.2: This version of tar is no longer supported, and will not receive security updates. Please upgrade asap.
12:06:00 PM: npm ERR! code 1
12:06:00 PM: npm ERR! path /opt/build/repo/node_modules/node-sass
12:06:00 PM: npm ERR! command failed
12:06:00 PM: npm ERR! command sh -c node scripts/build.js
12:06:00 PM: npm ERR! Building: /opt/buildhome/.nvm/versions/node/v16.8.0/bin/node /opt/build/repo/node_modules/node-gyp/bin/node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=
12:06:00 PM: npm ERR! make: Entering directory '/opt/build/repo/node_modules/node-sass/build'
12:06:00 PM: npm ERR!   g++ '-DNODE_GYP_MODULE_NAME=libsass' '-DUSING_UV_SHARED=1' '-DUSING_V8_SHARED=1' 


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

How do i write a function that takes as an argument it's returned value and so on for a determined number of times [closed]

I want to write a function in python that takes as argument a value1 and returns value2 then takes this value2 as argument and returns value3 and so on untill i reach value27



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

How to display stored data in bullets or any other html tag?

I am getting data from database and storing it in react state which contains data form of different html tags for example <p>hello this is data</p>

<ul><li>hello</li><li>hello</li><li>hello</li></ul>

when i want to render this data

{this.state.data}

instead of showing this data in bullets react is simply rendering this as it is. output

How to render this data in bullets as following

  • hello
  • hello


from Recent Questions - Stack Overflow https://ift.tt/3gEF5AI
https://ift.tt/3ztotU0

How to set locale in postgres using docker-compose?

I've tried multiple ways of changing the locale to en_GB and nothing seems to work.

My current docker-compose.yml

version: '3.9'

services:

  db:
    image: postgres
    restart: always
    build: 
      context: .
      dockerfile: ./Dockerfile
    ports:
      - 5432:5432
    volumes:
      - ./pg-data:/var/lib/postgresql/data
    environment:
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_DB: ${POSTGRES_DB}
      PGDATA: ${PGDATA}
      # LANG: 'en_GB.UTF-8'

  adminer:
    depends_on: 
      - db
    image: adminer
    restart: always
    ports:
      - 8080:8080
  
volumes:
  pg-data:

An official postgres image docs says to create a Dockerfile with:

FROM postgres
RUN localedef -i en_GB -c -f UTF-8 -A /usr/share/locale/locale.alias en_GB.UTF-8
ENV LANG en_GB.utf8

However this has no effect whatsoever.. Tried setting enviorment variable LC_* and LANG however this throws build error of enviorment variables being configured wrong.

Having just a Dockerfile without the enviorment variables set container builds and db is being reinitialized but while running first migration with knex the table consisting money type is still in dollars.



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

A custom similarity function in elasticsearch

I want to make a custom "similarity". Actually, I just want to improve the default Okapi BM25 from ES doc. I want to add one more condition to Okami BM25's logic. This condition equals if count the number of occurrences of the searched_word in the doc > 3 return 0.0 else OkamiBM25() in pseudocode it looks like: score(D, Q)=0 if the count of the searched_word > 3 in the doc.

In my understanding, I have to make a custom "similarity" following the official ES doc recommendations and after it implements the formula of Okapi BM25 Wiki. As I understand I can describe it as the Okapi BM25 formula from Wiki above and in the return statement return=0 if searched_word > 3. But I'm wondering is it possible to wrap the default implementation of Okapi BM25 into my custom "similarity" function and then make a condition something like that return doc.freq > 3 ? 0.0 : OkapiBm25(); Unfortunately, I was not able to find such an example



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

Is there a way to delete a scheduled task if you only know the filename of the application the task will run

I need to delete a scheduled task on a large number of machines preferably using only the command line. The problem is that the tasks were manually added on every computer, so the name of the task is not consistent between each one. I was hoping I could delete the task using the name of the exe file that the task runs, but this does not appear to be an option of the schtasks command.

I thought I was making progress using this command, but its not returning the name of the task for it to then be deleted.

for /f "tokens=3 delims=\" %%x in ('schtasks /query /fo:list ^| findstr ^^PrintTask.exe') do schtasks /Delete /TN "%%x" /F


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

What causes cdk bootstrap to hang?

I am trying to use the cdk bootstrap command.

>$env:CDK_NEW_BOOTSTRAP=1
>npx cdk bootstrap --cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess aws://1234.../us-east-1

I get the output:

CDK_NEW_BOOTSTRAP set, using new-style bootstrapping.
Bootstrapping environment aws://1234.../us-east-1...

I just hangs at this point. On one attempt I came back more than an hour later and it was still stuck. An s3 bucket with the prefix cdk did show up but has no files.

I've attempted to run it a few times but it's always the same.

What can cause it to get stuck this way?



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

I can't get JSON to display what are my missing?

I'm developing a JSON webpage that would basically display all data returned by the server. However, it doesn't work. I tried everything taht I could think of, but it still doesn't work. Please help. I didn't receave any error or warnings. The webpage is just nothingness. The data should be display in a tag but it is not.

let arrayForData = [];

function showFamilyInfo() {
  fetch('users.json')
    .then(function(response) {
      response.json()
        .then(function(data) {
          let parseData = data;
          console.log(parseData);
          parseData.forEach(function(element) {
            for (let i in parseData[element]) {
              arrayForData.push(`'
<p>
${element[i]}: ${i.FirstName}
${element[i]}: ${i.LastName}
${element[i]}: ${i.Age}
${element[i]}:${i.Gender}
</p>
'`);
            }
          });
          document.getElementById('demo').innerHTML = arrayForData.join();
        })
        .catch(function(error) {
          document.getElementById('demo').innerHTML = error;
        });
    });
}
console.log(arrayForData);
<span id="demo">
</span>
<button onclick="showFamilyInfo()">
Show Family Info
    </button>

It doesn't seems that the JS regonize the element[i] object. What are the problems with my code?



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

Vue 3 on page refresh

this is my first try on vue 3. im making a to-do list app. my data is saved in vuex but at the same time i cant see it on the screen. i can see the same things when i do it in vue 2 but i cant see it in vue 3. The screen does not update even though . call getters with computed.

Template:

<template>
  <div class="row mt-5">
    <div class="col-xs-12 col-md-4">
      <div
        class="card text-center">
          <div class="card-middle" v-for="item in getTask(1)">
            <div class="card-content" :style="{ 'background-color': item.color }">
              <h4></h4>
            </div>
          </div>
      </div>
    </div>
    <div class="col-xs-12 col-md-4">
      <div class="card text-center">
          <div class="card-middle" v-for="item in getTask(3)">
            <div class="card-content" :style="{ 'background-color': item.color }">
              <h4></h4>
            </div>
          </div>
      </div>
    </div>
  </div>
</template>

Script:

export default {
  setup() {
    const store = useStore();
    function getTask(list) {
      return getAllTasks.value.filter((task) => task.list == list);
    }
    const getAllTasks = computed(function () {
      return store.getters.getAllTasks;
    });
    const getTodoCount = computed(function () {
      return store.getters.getTodoCount;
    });
    const getInProgressCount = computed(function () {
      return store.getters.getInProgressCount;
    });
    const getDoneCount = computed(function () {
      return store.getters.getDoneCount;
    });

    return {
      deleteTask,
      startDrag,
      onDrop,
      getTask,
      getAllTasks,
      getTodoCount,
      getInProgressCount,
      getDoneCount,
    };
  },
};


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

The method 'getString' was called on null. Receiver: null Tried calling: getString("name")

I am having a error The method 'getString' was called on null. Receiver: null Tried calling: getString("name") I already instantiated

firebaseFirestore = FirebaseFirestore.instance;
  sharedPreferences = await SharedPreferences.getInstance();
class _HomePageState extends State<HomePage> {
  HomepageBloc _bloc;
  ScrollController _scrollController = ScrollController();
  TextEditingController _userNameSearchController = TextEditingController();
  String userName = sharedPreferences.getString(SharedPreferencesKey.name);
  String userToken = sharedPreferences.getString(SharedPreferencesKey.token);
  @override
  void initState() {
    super.initState();
    _bloc = HomepageBloc(userToken);
  }

  @override
  void dispose() {
    super.dispose();
    _bloc.dispose();
  }

I don't know why I am getting this error, it would be wonderful if this error can be solved



from Recent Questions - Stack Overflow https://ift.tt/38n2IJv
https://ift.tt/eA8V8J

What function should I use to change image using left and right arrow keys

I have a gallery. of images, I need to change the image when the user will press the arrow keys after the modal popup. left arrow key to change the image to the left and the right arrow key for right. I'm pretty new to JavaScript so I couldn't understand what function should I use to change the images to left and right.

I tried

.modal {
  width: 58%;
  height: 100%;
  top: 0;
  position: fixed;
  display: none;
  background-color: rgba(22, 22, 22, 0.5);
  margin-left: 300px;
  max-width: 779px;
  min-width: 779px;
}

.modal-content {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
}

.mySlides {
  display: none;
}

.mySlides {
  display: none;
}

.cursor {
  cursor: pointer;
}

.cursor {
  cursor: pointer;
}

.prev {
  cursor: pointer;
  position: relative;
  top: -149px;
  padding: 16px;
  margin-top: -50px;
  color: white;
  font-weight: bold;
  font-size: 20px;
  border-radius: 0 3px 3px 0;
  user-select: none;
  -webkit-user-select: none;
  left: -10%;
}

.next {
  cursor: pointer;
  position: relative;
  top: -149px;
  padding: 16px;
  margin-top: -50px;
  color: white;
  font-weight: bold;
  font-size: 20px;
  border-radius: 0 3px 3px 0;
  user-select: none;
  -webkit-user-select: none;
  left: 600px;
}
<div class="main-container">
  <div class="row">
    <div class="column">
      <p align="center"><img src="https://source.unsplash.com/collection/190727/300x200" width="250" height="164" onclick="openModal();currentSlide(1)" class="hover-shadow cursor"></p>
    </div>
    <div class="column">
      <p align="center"><img src="https://source.unsplash.com/collection/190727/300x210" width="250" height="164" onclick="openModal();currentSlide(2)" class="hover-shadow cursor"></p>
    </div>
    <div id="myModal" class="modal">
      <div class="modal-content">
        <span class="close cursor" onclick="closeModal()">&times;</span>
        <div class="mySlides">
          <img src="https://source.unsplash.com/collection/190727/300x200" style="width: 98%;
position: relative;
left: 10px;
top: 109px;">
        </div>
        <div class="mySlides">
          <img src="https://source.unsplash.com/collection/190727/300x210" style="width: 98%;
position: relative;
left: 10px;
top: 109px;">
        </div>
        <a class="prev" id="prev1" onclick="plusSlides(-1)">&#10094;</a>
        <a class="next" onclick="plusSlides(1)">&#10095;</a>
      </div>
document.addEventListener('keydown', function(e) {
  if (e.keyCode === 37) {} else if (e.keyCode === 39) {}
});


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

How to access Context within a Class Component for react native?

I want to use my Context in a class component (MyEventsScreen), but whenever I do so, I get an error saying it is an invalid hooks call.

Here is MyEventsScreen.js (I've simplified it to be brief):

import { useAuthState } from "../contexts/authContext";

export default class MyEventsScreen extends Component {

 render() {
    return (
      <View>
          <Text></Text>
      </View>
}

I have my authContext.js here:

import React from "react";
import { authReducer } from "../reducers/authReducer";

const AuthStateContext = React.createContext();
const AuthDispatchContext = React.createContext();

function AuthProvider({ children }) {
  const [state, dispatch] = React.useReducer(authReducer, {
    isLoading: true,
    isSignout: false,
    userToken: null,
    email: null,
    userID: null,
  });

  return (
    <AuthStateContext.Provider value={state}>
      <AuthDispatchContext.Provider value={dispatch}>
        {children}
      </AuthDispatchContext.Provider>
    </AuthStateContext.Provider>
  );
}

function useAuthState() {
  const context = React.useContext(AuthStateContext);
  if (context === undefined) {
    throw new Error("useAuthState must be used within a AuthProvider");
  }
  return context;
}
function useAuthDispatch() {
  const context = React.useContext(AuthDispatchContext);
  if (context === undefined) {
    throw new Error("useAuthDispatch must be used within a AuthProvider");
  }
  return context;
}

export { AuthProvider, useAuthState, useAuthDispatch };

I have an authReducer.js here:

export const authReducer = (prevState, action) => {
  switch (action.type) {
    case "SIGN_IN":
      return {
        ...prevState,
        email: action.email,
        isSignout: false,
        userToken: action.token,
      };
    default:
      return prevState;
  }
};

Any help would be appreciated!



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

filesystem value_type pointer to string?

I have a directory_iterator and I want the filename but I can't seem to get anything to work, it just throws an error saying that value_type* cannot be converted into a string. I can't cast it to a string and std::to_string() doesn't work either!

for (auto& p : std::experimental::filesystem::directory_iterator(dir)) {
    auto path = p.path().filename().c_str();
    char f[50] = "Json/";
    std::strcpy(f, path);
    std::ifstream comp(f, std::ifstream::binary);
}


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

Docker Unauthorized when pulling

I have tried pulling my files numerous times on Windows 10, but right when it begins extracting a certain large file (1.3G), it halts and says 'unauthorized'.

I have tried fixing this issue by going to Docker -> Setting -> Shared, but 'Shared' does not pop up.

I even created an account on hub.docker.com, logged on, then ran it, but the same thing happened.

As a last resort, I then uninstalled docker and reinstalled it - still does not work.

Has anyone encounter these issues/does anyone know what to do from here?

Thank you

Edit for clarification

I am pulling from dockerhub: https://hub.docker.com/r/jimiucb1/i526-aml

The command is: docker pull jimiucb1/i526-aml



from Recent Questions - Stack Overflow https://ift.tt/38kTygC
https://ift.tt/eA8V8J

Block django allauth default signup/login url

I am rendering my django-allauth signin/signup form through custom URLs.

from allauth.account.views import LoginView, SignupView 

urlpatterns = [
   ...
   url(r'^customurl/login/', LoginView.as_view(), name="custom_login" ),
   url(r'^customurl/signup/', SignupView.as_view(), name="custom_singup" ),
   ...

]

These are working fine. The problem is django-allauth default singin/singup urls working also. How can I block default signin/signup URLs?



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

How can I set label location in Pine Script so its on the line and not above or below it?

I want the value to be placed on the line and not below bar. How do I do that? I only see abovebar and belowbar in pine-script manual. Above and below is making my chart look very messy.

if isBullEngulf
bullEngulfOpen := line.new(bar_index - 1, open[1], bar_index, open[1], extend=extend.right, color=color.black)
bullEngulfLow := line.new(bar_index - 1, low < low[1] ? low : low[1], bar_index, low < low[1] ? low : low[1], extend=extend.right, color=color.green)
bullEngulfLowPrice = line.get_y1(bullEngulfLow)
offset                  =       input(15, maxval=900, title="Label Offset",step=5)
tl                      =       offset *(time - time[1])
bullEngulfLowLabel := label.new(x = t1 + time, y = na, text="\n"+tostring(bullEngulfLowPrice), style=label.style_none,size=size.normal,textcolor=color.white, yloc=yloc.belowbar)
//bullEngulfLowLabel := label.new(x = bar_index, y = na, text="\n"+tostring(bullEngulfLowPrice), style=label.style_none,size=size.normal,textcolor=color.white, yloc=yloc.belowbar)
bullEngulfHigh := line.new(bar_index - 1, high < high[1] ? high : high[1], bar_index, high < high[1] ? high : high[1], extend=extend.right, color=color.green)
bullEngulfHighPrice = line.get_y1(bullEngulfHigh)
bullEngulfHighLabel := label.new(bar_index - 1, high[1],text="\n"+tostring(high[1]),
 style=label.style_none,size=size.normal,textcolor=color.white, yloc=yloc.abovebar)

enter image description here



from Recent Questions - Stack Overflow https://ift.tt/2WAEl8p
https://ift.tt/3jqIvsz

Matplotlib: how to draw an axes title at the left-most position?

I'm drawing my axes title with the method ax.set_title("Horizontal Bars", ha="left", x=0, fontsize=16) and it draw as below:

Horizontal bar chart with misplaced title

How do I draw it in the left-most position, as the "title here" in red above?



from Recent Questions - Stack Overflow https://ift.tt/3mIeCpD
https://ift.tt/2WzCG3u

What does __latent_entropy is used for in C

Please I would like to understand in which case do we use the keyword __latent_entropy in a C function signature. I saw some google results talking about a GCC plugin, but I don't still understand what is its impact. Thanks



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

Dynamically adding functions to array columns

I'm trying to dynamically add function calls to fill in array columns. I will be accessing the array millions of times so it needs to be quick.

I'm thinking to add the call of a function into a dictionary by using a string variable

numpy_array[row,column] = dict[key[index containing function call]]

The full scope of the code I'm working with is too large to post here is an equivalent simplistic example I've tried.

def hello(input):
    return input

dict1 = {}

#another function returns the name and ID values
name = 'hello'
ID = 0

dict1["hi"] = globals()[name](ID)
print (dict1)

but it literally activates the function when using

globals()[name](ID) 

instead of copy pasting hello(0) as a variable into the dictionary.

I'm a bit out of my depth here. What is the proper way to implement this?

Is there a more efficient way to do this than reading into a dictionary on every call of

 numpy_array[row,column] = dict[key[index containing function call]]

as I will be accessing and updating it millions of times.

I don't know if the dictionary is called every time the array is written to or if the location of the column is already saved into cache.

Would appreciate the help.

edit

Ultimately what I'm trying to do is initialize some arrays, dictionaries, and values with a function

def initialize(*args):
  create arrays and dictionaries
  assign values to global and local variables, arrays, dictionaries

Each time the initialize() function is used it creates a new set of variables (names, values, ect) that direct to a different function with a different set of variables.

I have an numpy array which I want to store information from the function and associated values created from the initialize() function.

So in other words, in the above example hello(0), the name of the function, it's value, and some other things as set up within initialize()

What I'm trying to do is add the function with these settings to the numpy array as a new column before I run the main program.

So as another example. If I was setting up hello() (and hello() was a complex function) and when I used initialize() it might give me a value of 1 for hello(1). Then if I use initialize again it might give me a value of 2 for hello(2). If I used it one more time it might give the value 0 for the function goodbye(0).

So in this scenaro let's say I have an array

    array[row,0] = stuff()
    array[row,1] = things()
    array[row,2] = more_stuff()
    array[row,3] = more_things()

Now I want it to look like

    array[row,0] = stuff()
    array[row,1] = things()
    array[row,2] = more_stuff()
    array[row,3] = more_things()
    array[row,4] = hello(1)
    array[row,5] = hello(2)
    array[row,6] = goodbye(0)

As a third, example.

def function1():
    do something
    
def function2():
    do something
    
def function3():
    do something
    
numpy_array(size)

initialize():
    do some stuff
    
    then add function1(23) to the next column in numpy_array
    
initialize():
    do some stuff
    
    then add function2(5) to the next column in numpy_array
    
    
initialize():
    do some stuff
    
    then add function3(50) to the next column in numpy_array

So as you can see. I need to permanently append new columns to the array and feed the new columns with the function/value as directed by the initialize() function without manual intervention.



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

Is There A Way To Attach Relationship(One-One, One-Many, Many-Many) When Importing Data From Excel In Laravel?

Is there a way to attach relationship in laravel directly in just one function?

For example I had Three Table in Database: users(first table), user_role(relationship table), and roles(second table)

In controller, AdminController.php I had this:

public function import_student(Request $request) 
    {
    $user = Auth::user();
    $this->validate($request, [
        'file' => 'required|mimes:csv,xls,xlsx'
    ]);
    $file = $request->file('file');
    $nama_file = rand().$file->getClientOriginalName();
    $file->move('file_student',$nama_file);
    Excel::import(new UserImport, public_path('/file_student/'.$nama_file));
    Session::flash('sukses','Data Siswa Berhasil Diimport!');
    return redirect()->back();
    }

and in import, UserImport.php I had this:

use App\User;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Concerns\WithConditionalSheets;

class UserImport implements ToModel
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    use WithConditionalSheets;
    public function conditionalSheets(): array
    {
        return [
            'Worksheet 1' => new FirstSheetImport(),
            'Worksheet 2' => new SecondSheetImport(),
            'Worksheet 3' => new ThirdSheetImport(),
        ];
    }
    public function model(array $row)
    {
        return new User([
        'nisn' => $row[1],
        'nip' => $row[2],
        'name' => $row[3],
        'username' => $row[4],
        'email' => $row[5],
        'kelas' => $row[6],
        'jabatan' => $row[7],
        'tempat_lahir' => $row[8],
        'tgl_lahir' => $row[9],
        'bulan_lahir' => $row[10],
        'tahun_lahir' => $row[11],
        'jenis_kelamin' => $row[12],
        'agama' => $row[13],
        'tahun_masuk' => $row[14],
        'no_telp' => $row[15],
        'password' => $row[16],
        ]);
    }
}

And for models, in User.php I had this:

protected $fillable = [
    'nisn',
    'nip',
    'name',
    'username',
    'email',
    'kelas',
    'jabatan',
    'tempat_lahir',
    'tgl_lahir',
    'bulan_lahir',
    'tahun_lahir',
    'jenis_kelamin',
    'agama',
    'tahun_masuk',
    'no_telp',
    'avatar',
    'password',
];
protected $table = 'users';
/*
 * Role & User Relationship
 *
 */
public function roles()
{
    return $this
        ->belongsToMany('App\Role')
        ->withTimestamps();
}

in Role.php I had this:

public function users()
    {
        return $this
            ->belongsToMany('App\User')
            ->withTimestamps();
    }

So, I'm wondering where to place this code: ->roles()->attach(Role::where('name', 'Student')->first()); I usually use this code to attach relationship after making new data one-per-one using CRUD, but I don't know how to place or code to attach relationship to imported data from excel with only one function(import_student). If no one know, maybe I would create CRUD for relationship table.



from Recent Questions - Stack Overflow https://ift.tt/38jl6Dc
https://ift.tt/eA8V8J

Pivot table into cross reference table

I have a list of students who are assigned into groups 4 different groups for 3 weeks or more. Here is the table.

student week 1 week 2 week 3
A 1 4 2
B 2 2 1
C 3 4 4
D 4 3 3
E 1 1 2
F 2 2 1
G 3 1 4
H 4 3 3
I 1 1 2
J 2 2 1

I want to pivot that table and see how many times a student worked with another student in a group. For example, student A worked with student J twice and student B worked with student F three times, whereas B and C never worked together.

How can I generate a pivot table in excel like the one below? The values in the table below show many times a student has been in the same group with another student.

FIELD1 A B C D E F G H I J
A - 2 2 2
B - - 3 3
C - - - 2
D - - - - 2
E - - - - - 2
F - - - - - - 3
G - - - - - - -
H - - - - - - - -
I - - - - - - - - -
J - - - - - - - - - -


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

allow inbound traffic in network security group in azure for a dynamic IP

We need to allow a platform traffic to reach our systems (as I know adding a static public IP in our network security group in azure), but they mention that they don't have a static public IP or a range of IPs to whitelist, but instead a static domain name

What I found in azure documentation and some questions is that filtering traffic based on FQDN is impossible for now in network security group resource !

Is there any other possibility to achieve this ?

The Azure firewall seems just working for outbound rules (as I understand from azure documentation)

Still waiting, help please !!



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

Selecting a large range of values to recode in R

I want to recode a large number of variables across multiple columns. Here is an example df

df <- data.frame(
  id_number = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
  age = c(10, 11, 12, 13, 14, 15, 16, 17, 18, 19),
  abc1 = c(501, 502, 503, 504, 505, 506, 507, 508, 509, 510),
  abc2 = c(501, 502, 501, 501, 502, 501, 502, 503, 501, 502),
  abc3 = c(501, 506, 501, 501, 510, 501, 510, 501, 501, 501),
  abc4 = c(507, 505, 501, 501, 501, 501, 501, 501, 501, 501)
)

df

The columns abc1:abc4 has values 501:510 and I am trying to recode 501:508 as 91, 509 as 92 and 510 as 93 across all these columns at once. Here is what I tried -

library(dplyr)
df1 <- 
  df %>%
  mutate(across(
    abc1:abc4,
    ~ recode(
      .x,
      `501:508` = 91L,
      `509` = 92L,
      `510` = 93L
          )
  ))

But I get an error

x NAs introduced by coercion ℹ Input ..1 is across(abc1:abc4, ~recode(.x, `501:508` = 91L, `509` = 92L, `510` = 93L)).NAs introduced by coercionProblem with mutate() input ..1. x Unreplaced values treated as NA as .x is not compatible. Please specify replacements exhaustively or supply .default

However, it works if I change the values one by one but I want to do it all at once as my real data has a very long list of values. Am I doing something wrong with the part

`501:508` = 91L,

Thank you !

Follow-up question from above

Let's say the value of abc1:abc4 is way larger and there is an additional set of value of range 1-175. abc1:abc4 = c(1:175, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510). I just tweaked the values from my previous example to illustrate this here.

df1 <- data.frame(
  id_number = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
  age = c(10, 11, 12, 13, 14, 15, 16, 17, 18, 19),
  abc1 = c(14, 158, 170, 504, 505, 506, 507, 508, 509, 510),
  abc2 = c(501, 502, 501, 501, 45, 501, 502, 59, 501, 100),
  abc3 = c(89, 506, 12, 501, 510, 13, 510, 501, 11, 501),
  abc4 = c(32, 505, 35, 501, 501, 56, 501, 12, 501, 501)
)

df1

Now I want to recode them all together where 1:175 = 90, 501:508 = 91, 509 = 92 and 510 - 93 across columns abc1:abc4 at one go. How would "nm1" in @akrun's answer be set here. and is there an easier way to do this? Thank you !



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

2021-08-29

Binding not Updating on DependencyProperty - no XAML binding failure shown

I'm creating a fairly basic calendar control - showing time slots during the day, kind of like the Outlook calendar does. The full XAML for my control is pretty simple so I'll post in full:

<UserControl x:Class="AJSoft.Controls.Diary.Calendar.CalendarTimeStrip"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:AJSoft.Controls.Diary.Calendar"
             Name="ucCalendarTimeStrip"
             >
    <ListBox ItemsSource="{Binding ElementName=ucCalendarTimeStrip, Path=TimeItemsSource, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" />
</UserControl>

Like I said - simple. I normally don't define all those binding properties explicitly, but am trying to eliminate problems. A ListBox displays "CalendarTimeItem" objects created dynamically. Here's the code behind:

public partial class CalendarTimeStrip : UserControl
    {
        public static readonly DependencyProperty TimeItemsSourceProperty = DependencyProperty.Register("TimeItems", typeof(IEnumerable<CalendarTimeItem>), typeof(CalendarTimeStrip));
        public static readonly DependencyProperty EndTimeProperty = DependencyProperty.Register("EndTime", typeof(DateTime), typeof(CalendarTimeStrip), 
            new(DateTime.Now.AddHours(12), TimeChangedCallback));
        public static readonly DependencyProperty StartTimeProperty = DependencyProperty.Register("StartTime", typeof(DateTime), typeof(CalendarTimeStrip),
            new(DateTime.Now, TimeChangedCallback));

        public CalendarTimeStrip()
        {
            InitializeComponent();
            TimeChangedCallback(this, new());
        }

        public DateTime EndTime
        {
            get => (DateTime)GetValue(EndTimeProperty);
            set => SetValue(EndTimeProperty, value);
        }

        public DateTime StartTime
        {
            get => (DateTime)GetValue(StartTimeProperty);
            set => SetValue(StartTimeProperty, value);
        }

        public IEnumerable<CalendarTimeItem> TimeItemsSource
        {
            get => (IEnumerable<CalendarTimeItem>)GetValue(TimeItemsSourceProperty);
            set => SetValue(TimeItemsSourceProperty, value);
        }

        public static void TimeChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            CalendarTimeStrip calendarTimeStrip = (CalendarTimeStrip)d;

            List<CalendarTimeItem> timeItems = new();

            int totalMinutes = (int)(calendarTimeStrip.EndTime - calendarTimeStrip.StartTime).TotalMinutes;

            for (int i = 0; i < totalMinutes; i += 5)
                timeItems.Add(new() { Time = calendarTimeStrip.StartTime.AddMinutes(i) });

            calendarTimeStrip.TimeItemsSource = timeItems;
        }
    }

Again - nothing too tricky. We add "CalendarTimeItem"s for each 5 minute interval between a given start and end time. When these values are updated, I recreate the entire set of CalendarTimeItems. No optimising yet, but this is early days.

For some reason, the Callback fires as expected, the TimeItemsSource setter is called, but the binding never seems to trigger the getter and I see no items in my ListBox. When I manually create CalendarTimeItem's in XAML, everything shows as expected.

What's going on here?

Edit: manually invoking the Callback after InitialiseComponent is in there for testing purposes...

Edit 2: I now have this working by using TimeItemsSource as a CLR property with INotifyPropertyChanged - but I don't like this. Although it works, I'd still like to know why it wasn't working when linked up as a DP.



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