Friday, November 19, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


is it adviceable to use vanilla/raw node.js code

Posted: 19 Nov 2021 08:28 AM PST

Is it adviceable to code in Vanilla Node.js without any framework?

Reason why i prefer using raw Nodejs:

  1. When the creator of some framework stop to maintain the code then it affect my code as well.

Any advice on this?

Spree E-commerce filter for multiple order numbers

Posted: 19 Nov 2021 08:27 AM PST

I need to be able to use the filter: "order number" to filter multiple orders. I haven't found any documentation or information about it.

How to add a image "on" the button at one corner of button?

Posted: 19 Nov 2021 08:27 AM PST

I want to add a image to one corner to a button like this:

enter image description here

    li#menu-item-2046  {  background-color: black;  margin-inline-end:7px;      Border-radius: 10px;  box-shadow: 5px 2px 10px;  }      <li id="menu-item-2046" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-2046 item-level-0 menu-item-design-default menu-simple-dropdown item-event-hover"><a href="https://www.website.com" class="demo-class"><span class="nav-link-text">text</span></a></li>  

How can i test my gRPC app without clients?

Posted: 19 Nov 2021 08:27 AM PST

I have a little Nest JS app, that implements one gRPC method. I need to test it before connect some clients. So, i tried to use grpcurl. Start app at localhost:5002, then grpcurl -plaintext 127.0.0.1:5002 list and get this Failed to list services: server does not support the reflection API, how can i fix it?

sftp stuck when not existing directory called

Posted: 19 Nov 2021 08:27 AM PST

When I try to fetch files via sftp in shell script:

  1. It's working fine when all called directory present.

  2. It's stuck once its deal with non existing directories.

    sshpass -p 'password' sftp -oBatchMode=no -o StrictHostKeyChecking=no -b - user1@www.ftp.com 1>$currentdir/listfiles.log << !  cd /Root/work/in/abc/  -mget *.*   cd /Root/work/in/def/  -mget *.*  bye  

    !

Above is code snipped can you suggest solution. Greatly appreciate!!

Failed to upload an APK to Firebase App Distribution

Posted: 19 Nov 2021 08:27 AM PST

I have a Firebase project with two android apps, one for debug and one for release. I want to distribute the Debug version via Firebase App Distribution. I did follow the steps from the documentation, however when I run the command ./gradlew assembleDebug appDistributionUploadDebug I got he following error:

Execution failed for task ':app:appDistributionUploadDebug'.  > App Distribution halted because it had a problem uploading the APK: [404] Requested entity was not found.  

Below the steps I did follow to configure the project:

  • Added Firebase to my android project

  • Added App Distribution gradle plugin: classpath "com.google.firebase:firebase-appdistribution-gradle:2.2.0

  • Applied the plugin: apply plugin: 'com.google.firebase.appdistribution'

  • Created the FIREBASE_TOKEN environment variabel with the token I got via the plugin's login action

  • Configured the following distribution properties in the app's build.gradle file:

    firebaseAppDistribution { appId = "1:1111118011111:android:9999947217bead99999" artifactType="APK" releaseNote="First app" testers="me@mail.com" }

Any idea about how to fix this issue? Thanks!

How to pass a variable from Javascript to Flask

Posted: 19 Nov 2021 08:27 AM PST

I was doing a little project where I want to pass value of variable "x" from javascript to a pyhthon variable get_x. Can someone help me on how to do so.

index.html:

<html>  <body>  <p id="msglog"></p>  <input type="text" id="msg">  <button onclick="myFunction()">></button>  </body>    <script>  function myFunction() {    var x = document.getElementById("msg").value;    document.getElementById("msglog").innerHTML = x;    return x  }  </script>  </html>

main.py:

from flask import Flask, render_template    app = Flask(__name__,template_folder='',static_folder='')    @app.route("/")  def mainpage():    return render_template('/index.html')    app.run(host='0.0.0.0')  

Generate y-values 45 degree line through two points given x-axis values

Posted: 19 Nov 2021 08:27 AM PST

I have x-axis values:

var step = .05;  var xValues= Range((int)lowerRange, (int)upperRange, step);  

Now, I have a

var x-intercept = somevalue  

I want a 45 degree line of y-Values (list<double>) that passes through x-intercept. Note that I want y-values that are less than zero and greater than zero.

var yValues = xValues.Select(WHAT GOES IN HERE ?)  

NOTE: I know I can start from x-intercept, which has a y-value of zero, and add/subtract one from y-values as x-values are 1 (since slope of 45 degrees is 1) more/less than x-intercept. But I find that too hardwired.

construct std::vector<int> with initial size without setting them to 0

Posted: 19 Nov 2021 08:27 AM PST

this

#include <fmt/core.h>  #include <vector>    int main() {      std::vector<int> a(5);      // a.resize(5) has the same effect        fmt::print("{}\n", a.size());      a.push_back(2);      fmt::print("{}\n", a.size());        return 0;  }    

will output:
5
6

i want to give the vector an initial size, but when doing so with a int vector, all those values are going to be set to 0, and i just want them to be nothing, so that when i push_back() to the vector, it does not resize, adding the element after those useless zeroes.

Pyspark: Check if column values are monotonically increasing

Posted: 19 Nov 2021 08:28 AM PST

Problem: Given the below pyspark dataframe, is it possible to check whether row-wise whether "some_value" did increase (compared to the previous row) by using a window function (see example below)?

A solution without lag would be preferred as I will have multiple columns like "some_value" and I don't know in advance how many and their explicit names.

Example: Here I want to achive a column like "FLAG_INCREASE".

+---+----------+---+----------+  | id|     datum|lfd|some_value| FLAG_INCREASE  +---+----------+---+----------+ ------------+  |  1|2015-01-01|  4|      20.0| 0  |  1|2015-01-06|  3|      10.0| 0  |  1|2015-01-07|  2|      25.0| 1  |  1|2015-01-12|  1|      30.0| 1  |  2|2015-01-01|  4|       5.0| 0  |  2|2015-01-06|  3|      30.0| 1  |  2|2015-01-12|  1|      20.0| 0  +---+----------+---+----------+--------------+  

Code:

import pyspark.sql.functions as F  from pyspark.sql.window import Window  from pyspark.sql import Row        row = Row("id", "datum", "lfd", "some_value", "some_value2")  df = spark.sparkContext.parallelize([      row(1, "2015-01-01", 4, 20.0, 20.0),      row(1, "2015-01-06", 3, 10.0, 20.0),      row(1, "2015-01-07", 2, 25.0, 20.0),      row(1, "2015-01-12", 1, 30.0, 20.0),      row(2, "2015-01-01", 4, 5.0, 20.0),      row(2, "2015-01-06", 3, 30.0, 20.0),      row(2, "2015-01-12", 1, 20.0, 20.0)  ]).toDF().withColumn("datum", F.col("datum").cast("date"))     +---+----------+---+----------+  | id|     datum|lfd|some_value|  +---+----------+---+----------+  |  1|2015-01-01|  4|      20.0|  |  1|2015-01-06|  3|      10.0|  |  1|2015-01-07|  2|      25.0|  |  1|2015-01-12|  1|      30.0|  |  2|2015-01-01|  4|       5.0|  |  2|2015-01-06|  3|      30.0|  |  2|2015-01-12|  1|      20.0|  +---+----------+---+----------+  

How to access redux state after dispatch is finished fully?

Posted: 19 Nov 2021 08:28 AM PST

I am making a Create Operation. When the user clicks on onSubmit I am dispatching an action that creates a resource in the database and updates the store with the information that is returned from API call which contains information like status(indicating the status of operation) and error or message.

const initialState = {     loading: true,     status: false,     error: false  }  

Above is my initial state of redux store

const {loading,status} = useSelector(state=>state.newUser)  

I am consuming the state using useSelector

const addUser = (values) => async (dispatch) => {      const response = // Makes an API call return information      dispatch({type:"ADD_USER",payload:response.data})  }    onSubmit = (values)=>{      dispatch(addUser(values))      .then(data=>{          console.log(data)      })      if(!status){               }  }  

In the above onSubmit function when the user submits the form it dispatches an action and updates the store. Now based on the new state I want to update the UI. After dispatching I am checking whether the status of the operation is true or false. If false I want to display the error. The problem is after dispatching If I try to access status it gives me the status value from initialState. I want to execute the if(!status) after the states get updated.

emojis are causing change in line height

Posted: 19 Nov 2021 08:28 AM PST

<p>Alternatively, you can use percentages, which     will be calculated with respect to the width of the generated box's     containing block. &#128517;Therefore, assuming the container's width     is greater than the image's height, margin: -50% 0 should be enough.     Hide code snippet  </p>

emoji increases line heightHow to avoid change in line-height on insertion of emojis?

React Native Webview looking for external static files into the app

Posted: 19 Nov 2021 08:27 AM PST

React Native loads HTML files which stored locally inside the app using webview and this HTML have link to external JavaScript file, that JavaScript file loads and embed some images (stored on S3 bucket) into the HTML file, for this react-native webview throws following error and look for static file inside the app where as file have external link

React-Native Webview get error:

Error: ENOENT: no such file or directory, scandir '/Users/bhanwar/nucava/repos/lvld/LVLDAPP/src/game/media/graphics/splash/desktop'

checkClickableLayer: function (b, c, d) {    "undefined" == typeof wm &&      (this.doesClickableLayerExist(b)        ? (ig.game.showOverlay([b]),          $("#" + b)            .find("[href]")            .attr("href", c))        : this.createClickableOutboundLayer(            b,            c,            "https://<some domain>/media/graphics/misc/invisible.png",            d          ));  },

How to print a dataframe which is read from a csv file into dictionary format?

Posted: 19 Nov 2021 08:27 AM PST

I turned the data in a csv file into a dataframe by using Pandas then proceeded to print the dataframe into dictionary format by using Ordereddict.

However, the index numbers for each row are missing when I did it, is that anyway to retain the index number or anyway to achieve the same result with index numbers?

And I am not entirely sure the part with zip() and tolist(), can anyone explain their usages?

My code:

import pandas as pd  from collections import OrderedDict  import collections    df = pd.read_csv('for_testing.csv')      for i, row in df.iterrows():    d = OrderedDict(zip(row.index.tolist(), row.tolist()))    print(d)  

Output:

OrderedDict([('First Name', 'Kate'), ('Last Name', 'Rose'), ('Occupation', 'Teacher'), ('Age', 24), ('Number', 87)])  OrderedDict([('First Name', 'James'), ('Last Name', 'Smith'), ('Occupation', 'Cook'), ('Age', 35), ('Number', 487)])  OrderedDict([('First Name', 'Nick'), ('Last Name', 'Carter'), ('Occupation', 'Writer'), ('Age', 44), ('Number', 896)])  OrderedDict([('First Name', 'Ray'), ('Last Name', 'Johnson'), ('Occupation', 'Designer'), ('Age', 34), ('Number', 412)])  OrderedDict([('First Name', 'Jay'), ('Last Name', 'Law'), ('Occupation', 'Unemployed'), ('Age', 25), ('Number', 123)])  

I would like the Output to be like this:

1. OrderedDict([('First Name', 'Kate'), ('Last Name', 'Rose'), ('Occupation', 'Teacher'), ('Age', 24), ('Number', 87)])  2. OrderedDict([('First Name', 'James'), ('Last Name', 'Smith'), ('Occupation', 'Cook'), ('Age', 35), ('Number', 487)])  3. OrderedDict([('First Name', 'Nick'), ('Last Name', 'Carter'), ('Occupation', 'Writer'), ('Age', 44), ('Number', 896)])  4. OrderedDict([('First Name', 'Ray'), ('Last Name', 'Johnson'), ('Occupation', 'Designer'), ('Age', 34), ('Number', 412)])  5. OrderedDict([('First Name', 'Jay'), ('Last Name', 'Law'), ('Occupation', 'Unemployed'), ('Age', 25), ('Number', 123)])  

Edit: I noticed a problem, when I try to make the print triggered by an user input, it only displays the last row of the ordereddict dataframe instead of the whole ordereddict dataframe:

New code:

import pandas as pd  from collections import OrderedDict  import collections    df = pd.read_csv('for_testing.csv')    def main():    choice = input("type sth ")        if choice == '1':        for i, row in df.iterrows():          d = OrderedDict(zip(row.index.tolist(), row.tolist()))        print(d)      main()  

New Output:

type sth 1  OrderedDict([('First Name', 'Jay'), ('Last Name', 'Law'), ('Occupation', 'Unemployed'), ('Age', 25), ('Number', 123)])  

spring-boot:run multi-modular maven build

Posted: 19 Nov 2021 08:27 AM PST

I have a multi-modular maven project.

I have the root folder(parent) and the modules(childs):

  • core
  • ui
  • rest

As of now I have to go into the rest directory to execute: mvn spring-boot:run Then I go into UI folder and execute mvn javafx:run for the application to start.

Is there a way to do this in "one" (i.e starting the server and launching the app). Or making sure the webserver is running while executing "mvn clean install" in the parent, as that will trigger all my tests to run, and tests are failing without the server to be up and running.

C# how to require a const / static readonly field of generic type parameter

Posted: 19 Nov 2021 08:28 AM PST

I am making a simulator for simulating interactions between planets of the solar system and asteroids etc. Seeing a lot of the code I am writing is very similar to the code I already wrote for an earlier project where I simulated oil spills, I want to use generics to reuse my old code. I have several classes that form the simulator, and one class that inhabits the simulation (celestial objects in this case), which is given as a generic type parameter. The simulator needs to know how many frames it has to store for recursive formulas, which is determined by the generic parameter.

public class Sim<T> where T : IEntity   {       readonly int RecursionDepth;     //need to get the value from the class passed as T         //some more code  }    public interface IEntity   {       //cant require a const here, it would be a default implementation instead       //don't want a int property with get; here as there are no guarantees about the immutability       //and different instances may have different values.         //some code  }  

It would make sense to have this value be a constant or a static readonly field of the class used in the simulation. However, neither of these two options can be required using an interface. Sure, I can add a property in the interface definition, but as far as I am aware I cannot require it being readonly, and the same for each instance of the class. I really do not want to have to resort to the situation where it is just a random integer passed to the system, and I have to trust it is going to work out.

Are there any requirements I can set to at least have reasonable confidence in the immutability of the parameter and its egality across all instances of the class?

Using template function for accessing the raw bytes of POD data type and strings

Posted: 19 Nov 2021 08:28 AM PST

I'm trying to make a function template that lets me process the raw bytes of a POD data type and strings.

I came up with this somewhat naive approach (I'm not using template a lot, and I'm able to write them use them only for very simple cases):

#include <cstdio>    template<typename T>  void PrintBytes(T object)  {    unsigned char* p = reinterpret_cast<unsigned char*>(&object);    for (int i = 0; i < sizeof object; i++)    {      printf("%02x ", *p++);    }      printf("\n");  }    int main()  {    int a = 10;    PrintBytes(a);    // works as expected          short b = 12;    PrintBytes(b);    // works as expected        const char* foo = "ABC";    PrintBytes(foo);  // works as expected, but doesn't do what I want    const char bar[] = "ABC";    PrintBytes(bar);  // works as expected, but doesn't do what I want  }  

Output

0a 00 00 00  0c 00  a4 ac 5b 8c f6 7f 00 00  a4 fb 7f 07 b7 00 00 00  

Desired output for the last two cases

41 42 43  41 42 43  

Obviously the first two cases work and the last two cases don't because foo and bar are already pointers and the unsigned char* p = reinterpret_cast<unsigned char*>(&object) should rather be unsigned char* p = object and the sizeof object should be strlen(object).

How can this be done with C++ templates? I can use c++17.

Get byte representation of C++ class

Posted: 19 Nov 2021 08:27 AM PST

I have objects that I need to hash with SHA256. The object has several fields as follows:

class Foo {      // some methods      protected:         std::array<32,int> x;         char y[32];         long z;  }  

Is there a way I can directly access the bytes representing the 3 member variables in memory as I would a struct ? These hashes need to be computed as quickly as possible so I want to avoid malloc'ing a new set of bytes and copying to a heap allocated array. Or is the answer to simply embed a struct within the class?

It is critical that I get the exact binary representation of these variables so that the SHA256 comes out exactly the same given that the 3 variables are equal (so I can't have any extra padding bytes etc included going into the hash function)

Extract a data.frame from a list within Rcpp

Posted: 19 Nov 2021 08:27 AM PST

This is probably a really simple question, but I can't figure out what's wrong.

I have a list that I pass to an Rcpp function, and the first element of that list is a data.frame.

How do I get that data.frame?

bar = list(df = data.frame(A = 1:3,B=letters[1:3]),some_other_variable = 2)    foo(bar)  

And the following C++ code:

#include <Rcpp.h>    // [[Rcpp::export]]  Rcpp::NumericVector bar(Rcpp::List test){    Rcpp::DataFrame df_test = test["df"];    Rcpp::NumericVector result = df_test["A"];    return result;  }  

I get the following error on the line DataFrame df_test = test["df"]:

error: conversion from 'Rcpp::Vector<19>::NameProxy{aka 'Rcpp::internal::generic_name_proxy<19, Rcpp::PreserveStorage> to 'Rcpp::DataFrame{aka 'Rcpp::DataFrame_ImplRcpp::PreserveStorage ambiguous

Anyone know what I'm missing? Thanks.

Entity Framework with Prism MVVM: How to get an auto incremented id to a CollectionViewSource?

Posted: 19 Nov 2021 08:27 AM PST

I'm new to EF and trying to get the EF Core Getting Started with WPF tutorial running with Prism MVVM.

I'm currently stuck with an ugly solution to reflect the auto-incremented id (sqlite) for an inserted item back to the DataGrid after pressing the Save button. Update: I later found out that all sorting and filtering is lost when done this way.

In the non-mvvm tutorial this is done by calling productsDataGrid.Items.Refresh(). That works nicely:

private void Button_Click(object sender, RoutedEventArgs e)  {      _context.SaveChanges();      productsDataGrid.Items.Refresh();  }  

The only solution (Update: See below for a better solution.) that currently works for me is to set the ObservableCollection to null and then re-assign it to the database context after calling context.SaveChanges() in my Save() function.

This is the working code:

MainWindow.xaml

<Window x:Class="EfTestPrism.MainWindow"          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"          xmlns:d="http://schemas.microsoft.com/expression/blend/2008"          xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"          xmlns:local="clr-namespace:EfTestPrism"          xmlns:i="http://schemas.microsoft.com/xaml/behaviors"          mc:Ignorable="d"          d:DataContext="{d:DesignInstance local:MainWindowViewModel, IsDesignTimeCreatable=True}"          Title="MainWindow" Height="450" Width="800">        <Window.Resources>          <CollectionViewSource x:Key="CategoryViewSource"                                Source="{Binding CategoriesCollection}"/>      </Window.Resources>        <i:Interaction.Triggers>          <i:EventTrigger EventName="Closing">              <i:InvokeCommandAction Command="{Binding WindowCloseCommand, Mode=OneTime}"/>          </i:EventTrigger>      </i:Interaction.Triggers>        <Grid>          <Grid.RowDefinitions>              <RowDefinition Height="*"/>              <RowDefinition Height="Auto"/>          </Grid.RowDefinitions>            <DataGrid Grid.Row="0"                    AutoGenerateColumns="False"                    RowDetailsVisibilityMode="VisibleWhenSelected"                    ItemsSource="{Binding                                  Source={StaticResource CategoryViewSource}}">              <DataGrid.Columns>                    <DataGridTextColumn Header="Category Id"                                      Width="SizeToHeader"                                      IsReadOnly="True"                                      Binding="{Binding CategoryId}"/>                  <DataGridTextColumn Header="Name"                                      Width="*"                                      Binding="{Binding Name}"/>              </DataGrid.Columns>          </DataGrid>            <Button Grid.Row="1"                  Content="Save"                  Command="{Binding SaveCommand}"/>      </Grid>  </Window>  

MainWindow.xaml.cs:

namespace EfTestPrism;    public partial class MainWindow  {      public MainWindow() {          InitializeComponent();          DataContext = new MainWindowViewModel();      }  }  

MainWindowViewModel.cs

using System.Collections.ObjectModel;  using System.Windows.Input;  using Microsoft.EntityFrameworkCore;  using Prism.Commands;  using Prism.Mvvm;    namespace EfTestPrism;    public class MainWindowViewModel : BindableBase  {      public MainWindowViewModel() {          context.Database.EnsureCreated();          context.Categories!.Load();          CategoriesCollection = context.Categories!.Local.ToObservableCollection();      }        private readonly ProductContext context = new ();        private ObservableCollection<Category> ? categoriesCollection;      public ObservableCollection<Category> ? CategoriesCollection {          get => categoriesCollection!;          set => SetProperty(ref categoriesCollection, value);      }        public ICommand SaveCommand => new DelegateCommand(Save);        private void Save() {          context.SaveChanges();          /* I don't like the following but it works.             I tried different things here, see below. */          CategoriesCollection = null;          CategoriesCollection = context.Categories!.Local.ToObservableCollection();      }        public ICommand WindowCloseCommand => new DelegateCommand(WindowClose);        private void WindowClose() {          context.Dispose();      }  }  

ProductContext.cs

using Microsoft.EntityFrameworkCore;    namespace EfTestPrism;    public class ProductContext : DbContext  {      public DbSet<Category> ? Categories { get; set; }        protected override void OnConfiguring(DbContextOptionsBuilder options) {          options.UseSqlite("Data Source=products.db");          options.UseLazyLoadingProxies();      }  }  

Category.cs

namespace EfTestPrism;    public class Category // I tried making this a BindableBase and...  {      public int CategoryId { get; set; } // ...using SetProperty without success      public string Name { get; set; }  }  

Things I've tried without success:

ViewModel::Save() function:

  • RaisePropertyChanged(nameof(CategoriesCollection)
  • Refreshing each collection item and/or id property:

.

foreach (var item in CategoriesCollection) {      RaisePropertyChanged(nameof(item.CategoryId));      RaisePropertyChanged(nameof(item));  }  
  • Setting the id to zero and back to the original value. Strange things happen here like all ids being zero in the data grid except for the newly added items:

.

foreach (var item in oc) {      var temp = item.CategoryId;      item.CategoryId = 0;      item.CategoryId = temp;  }  

MainWindow.xaml:

  • Trying all UpdateSourceTriggers for the CategoryID binding.

I can see that the collection changes. When I remove the IsReadonly="True" on the DataGrids CategoryId column, the value gets updated as soon as I double click it after saving.

What would be a proper mvvm way to update the DataGrid similarly to the categoryDataGrid.Items.Refresh(); call after _context.SaveChanges() in the Button_Click function of the tutorial?

Update: - callback to code behind

The following works and keeps sorting and filtering. I don't mind too much about the code behind because it's strictly view related and I think that's acceptable.

Pro: No manual impementation of removing and adding back the items to the collection i.e. least code that works (if there's not a better solution).

Con: The view model has to call a delegate. So it actually has to anticipate that the view it's used in might want to provide a callback.

Changes to the code:

MainWindow.xaml: Add an x:Name to the DataGrid to make it accessable from the code behind:

[...]  <DataGrid Grid.Row="0"            x:Name="CategoriesDataGrid"            AutoGenerateColumns="False"  [...]  

Add a delegate to MainWindowViewModel.cs and call it in Save():

[...]  public delegate void Callback();    public class MainWindowViewModel : BindableBase  {      public MainWindowViewModel(Callback ? refreshView = null) {          RefreshView = refreshView;  [...]      private readonly Callback ? RefreshView;  [...]      private void Save() {          context.SaveChanges();          RefreshView?.Invoke();      }  [...]  

Implement and supply a RefreshView method in MainWindow.xaml.cs:

namespace EfTestPrism;    public partial class MainWindow  {      public MainWindow() {          InitializeComponent();          DataContext = new MainWindowViewModel(RefreshView);      }        private void RefreshView() {          CategoriesDataGrid.Items.Refresh();      }  }  

Sharing state when applying Douglas Crockford's composition pattern

Posted: 19 Nov 2021 08:28 AM PST

This is the form of constructor which Douglas Crockford suggests in his book "How Javascript works" and in his lectures.

const constructor_x = function (spec) {    let { a } = spec // private state        // methods can modify private state    const method_x = function () { a = '...' }        // methods are exposed as public interface    return Object.freeze({ method_x })  }

He suggests the following pattern for composition:

const constructor_y = function (spec) {    let { b } = spec // private state      // we can call other constructor and borrow functionality    const { method_x } = constructor_x(spec)      // we define new methods    const method_y = function () { b = '...' }      // we can merge borrowed and new functionality    // and expose everything as public interface    return Object.freeze({ method_x, method_y })  }

So here we see how to compose constructor_x and constructor_y. But my problem with this example (and all examples used when this pattern is presented) is that constructor_x and constructor_y make separate private states. constructor_x works on variable a, while constructor_y works on variable b. What if we want our constructors to share state? What if constructor_y also wants to work with variable a?

const constructor_y = function (spec) {    let { a, b } = spec      const { method_x } = constructor_x(spec)      const method_y = function () { b = '...' }    const method_z = function () {       // we may want to read `a` and maybe write to it      a = '...'     }      return Object.freeze({ method_x, method_y, method_z })  }

Of course this doesn't achieve what I want because a which constructor_y sees is not the same a constructor_x sees. If I used this, I could have achieved that maybe like so:

const constructor_x = function (spec) {    return {      _a: spec.a,      method_x () { this._a = '...' }    }  }    const constructor_y = function (spec) {    return {      ...constructor_x(spec),      _b: spec.b      method_y () { this._b = '...' },      method_z () { this._a = '...' }    }  }

But here I have lost privacy of variables _a and _b since they are attached to instance and are accessible just like methods. The best I can do is add underscore prefix which Douglas Crockford calls a sign of incompetence. I also lost instance's rigidness because it can no longer be frozen.

I could have exposed accessors for variable a in constructor_x like so:

const constructor_x = function (spec) {    let { a } = spec // private state        // methods can modify private state    const method_x = function () { a = '...' }        // methods are exposed as public interface    return Object.freeze({       method_x,      get_a () { return a },      set_a (val) { a = val }    })  }    const constructor_y = function (spec) {    let { a, b } = spec      const { method_x, get_a, set_a } = constructor_x(spec)      const method_y = function () { b = '...' }    const method_z = function () { set_a('...') }      return Object.freeze({ method_x, method_y, method_z })  }

These accessors can now be used by constructor_y to access private state of constructor_x. They are something like protected members in classical inheritance model. This makes constructor_x in some way special: It is not to be used as normal constructor, but only for composition inside other constructors. Another problem is that if we had another constructor like constructor_x which works on private variable a, we couldn't use them together in composition:

// another constructors which wants to work on `a`  const constructor_x2 = function (spec) => {    let { a } = spec       const method_z = function () { a = '...' }      return Object.freeze({       method_z,      get_a () { return a },      set_a (val) { a = val }    })  }    const constructor_y = function (spec) {    let { a, b } = spec      const { method_x, get_a, set_a } = constructor_x(spec)    const { method_x2, get_a: get_a2, set_a: set_a2 } = constructor_x2(spec)      // How do I use variable a now? There are two of them    // and constructors x and x2 don't share them.  }

All of this would not be a problem if I used this and modified state on the instance.

Can I use variables or regex for selectors in CSS?

Posted: 19 Nov 2021 08:28 AM PST

Hi,

I have this markup:

<div data-users="room2">   <span data-room="room1,room2,room3">john</span>   <span data-room="room1">george</span>   <span data-room="room2">jane</span>  </div>  

I want only users that have the same room data as the div parent so I wrote this css:

span { display: none; }  [data-users="room2"] [data-room*="room2"] { display: block; }  

fiddle: https://jsfiddle.net/ehpt9f5z/2/

However, since the data in the div parent can change to any room number I need a variable there so the CSS selector will always match the room data from the child with its parent, something like this:

[data-users=$1] [data-room*=$1] { display: block; }  

Is it even possible with pure css?

Thank you.

typora: Automatic document map on left side when exporting simple HTML document

Posted: 19 Nov 2021 08:27 AM PST

Let's say I start with a markdown file I made in typora...then I export it as a simple HTML file without anything fancy. The HTML file is a simple html document that only contains headers h1 to h5 and text for each header level...

Is there a simple way to automatically create a "document map" based on the html headings that is attached to the left side of the html document the same way as it is in document maps in microsoft word, acrobat reader? Looking for simplest solution.

For instance, maybe i can cut and paste a small javascript program to query the heading tags and display them on the side?

Or maybe I can write a python, perl, or powershell script to read all the header tags and put links on the side by producing a new html document?

May the simplest method win..

<!doctype html>  <html>  <head>  <meta charset='UTF-8'><meta name='viewport' content='width=device-width initial-scale=1'>  <title>sample</title>  </head>  <body><p>&nbsp;</p>  <p>&nbsp;</p>  <h1 id='heading-1'>heading 1</h1>      <h2 id='apples'>Apples</h2>      <p>Apples are tasty</p>          <h3 id='mcintosh'>McIntosh</h3>          <h3 id='gala'>Gala</h3>          <h3 id='red-delicious'>Red Delicious</h3>        <h2 id='pears'>Pears</h2>      <p>Pears are green</p>        <h2 id='oranges'>Oranges</h2>      <p>oranges are orange</p>      <p>&nbsp;</p>  </body>  </html>  

Here's what I want my document to look like in HTML using the simplest javascript code possible

enter image description here

How to get a list of existing student names in Django?

Posted: 19 Nov 2021 08:28 AM PST

I am new to Django rest framework, I want to get a list of the student first names(only) when it is existed. can anyone help me?

In my models.py

class School(models.Model):      name = models.CharField(max_length=100, null=False, blank=False)      city = models.CharField(max_length=100, null=False, blank=False)      street = models.CharField(max_length=100, null=False, blank=False)        def __str__(self):          return f"{self.city}->{self.street}->{self.name}"    class Student(models.Model):      school_id = models.ForeignKey(School, on_delete=models.CASCADE)      first_name = models.CharField(max_length=100, null=False, blank=False)      last_name = models.CharField(max_length=100, null=False, blank=False)        def __str__(self):          return f"{self.first_name} {self.last_name}"  

In my serializers.py:

class StudentSerializer(serializers.Serializer):      class Meta:          model = Student          fields = ['first_name']         class SchoolSerializer(serializers.Serializer):      is_existing_student = = serializers.BooleanField()      student = StudentSerializer(many=True, read_only=True)        class Meta:          model = School          fields = ['is_existing_student','student']  

In my views.py:

class schoolViewSet(viewsets.ModelViewSet):      serializer_class = SchoolSerializer      queryset = School.objects.all()  

In this picture you can see how it should look like [1]: https://i.stack.imgur.com/bR8cN.png

How to apply transaction logic in FastAPI RealWorld example app?

Posted: 19 Nov 2021 08:27 AM PST

I am using nsidnev/fastapi-realworld-example-app.

I need to apply transaction logic to this project.

In one API, I am calling a lot of methods from repositories and doing updating, inserting and deleting operations in many tables. If there is an exception in any of these operations, how can I roll back changes? (Or if everything is correct then commit.)

Office Add-in development: Styling an Inserted HTML table in Word

Posted: 19 Nov 2021 08:27 AM PST

I'm working on a Word Taskpane AddIn (Office.js). In this AddIn, I have a function to insert an HTML-table in the document. This is working fine, but now I want to style the table. It seems that is only possible using inline styling. I mean I cannot use any external-CSS file to style the insert HTML-table, which is kind of logical because in the Word document it would be impossible to reference such a css file? I just wonder if there are any other options, styling the table, like reference or apply a (builtin) style in Word for example. But I don't have a clue how I would do that in this case.

 function createReGeBoHtmlTable(result) {        var srcArray = result.Sources;        var table = "<table border='1' style='border: 1px solid black;border-collapse: collapse;width:100%'>";        table += "<tr><th style='background-color:#FF0000;text-align:left'>Onderdeel</th><th>Bevinding</th><th>Informatiebron</th></tr>";        $.each(result.Values, function (i, item) {          console.log(item);            var src = "";          if (item.sources) {                $.each(item.sources, function (j, source) {                  src = src + srcArray[source].name + '<sup>' + source.toString() + '<sup> \n';              })          };            table += "<tr><td style='width:40%'><strong>" + item.title + "</strong></td><td>" + ((item.value == 'null') ? "" : item.value) + "</td><td>" + src + "</td></tr>";      });        table += "</table>";      insertHtmlTable(table);  

This is the code I use to create the table

    function insertHtmlTable(htmlTable) {      Word.run(function (context) {            var thisDocument = context.document;            var range = thisDocument.getSelection();          range.insertHtml(htmlTable, 'End');          return context.sync().then(function () {              ;              console.log('Added Table.');          });      })          .catch(function (error) {              console.log('Error: ' + JSON.stringify(error));              if (error instanceof OfficeExtension.Error) {                  console.log('Debug info: ' + JSON.stringify(error.debugInfo));              }          });  }  

Any ideas are welcome.

UPDATE

In the meantime, I have found another way for developing an AddIn. This gives me also the possibility for using styles on a table. I also found a very useful option for developing Add In (Script Lab. I generate my Add in now using Yeoman Getting Started.

Therefore this question can be closed!

Firebase user.sendEmailVerification() is not a function

Posted: 19 Nov 2021 08:27 AM PST

firebase.auth().createUserWithEmailAndPassword(email, password).then((user) => {       user.sendEmailVerification().then(()=>{console.log("Email Sent")}).catch((err)=>{console.log(err)});  }).catch((error) => {      var errorCode = error.code;      var errorMessage = error.message;      });  

Getting error - user.sendEmailVerification() is not function. Can someone help how to send Verification Email in Firebase Authentication?

How do I compile a UWP application to a stand-alone EXE file?

Posted: 19 Nov 2021 08:27 AM PST

I have a UWP application. I can run it inside of Visual Studio by using the Run button. I also know how to create an App Package and distributed it via App Center.

What I can't figure out how to do is build an EXE file that I can run on my own computer without launching Visual Studio (or copy to another computer). I found the EXE in the project folder under bin/x64/Debug (or bin/x64/Release), but it won't run. In fact it does nothing when I double-click on it.

What am I doing wrong?

Command Line Tool - Error - xcrun: error: unable to find utility "xcodebuild", not a developer tool or in PATH

Posted: 19 Nov 2021 08:28 AM PST

I am getting this error while building the SwiftJSON framework to the Some Xcode project through Carthage Dependency Manager.

Sivaramaiahs-Mac-mini:GZipDemoApp vsoftMacmini5$ carthage update --platform iOS

*** Fetching GzipSwift

*** Fetching SwiftyJSON

*** Checking out GzipSwift at "3.1.1"

*** Downloading SwiftyJSON.framework binary at "3.1.3"

*** xcodebuild output can be found in /var/folders/7m/y0r2mdhn0f16zz1nlt34ypzr0000gn/T/carthage-xcodebuild.apLXCc.log

A shell task (/usr/bin/xcrun xcodebuild -project /Users/vsoftMacmini5/Desktop/GZipDemoApp/Carthage/Checkouts/GzipSwift/Gzip.xcodeproj CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= CARTHAGE=YES -list) failed with exit code 72:

xcrun: error: unable to find utility "xcodebuild", not a developer tool or in PATH

Print time in C initially and at the end of doing sleep

Posted: 19 Nov 2021 08:28 AM PST

I'm trying to print the date two times:

char *init_time = getTime();  // Do something and sleep 5 seconds  char *end = getTime();  printf("train 2 started at %s and arrived at %s\n", init_time, end);  

The get time:

char* getTime(){      time_t result;      result = time(NULL);      return asctime(localtime(&result));  }  

Why is the result printed the same?

No comments:

Post a Comment