2022-11-30

Knex select always returns pending promise [duplicate]

I am writing a simple function to query my database with Knex in Node. Everything I've tried returns Promise { <pending> }

Function to query the DB:

const queryTable = async () => {
  const data = await knex
    .select("*")
    .from(TABLE_NAME)

  return data;
};

I've tried calling the function in it's own async/await wrapper, and I've tried the .then() callback after... No luck. Any leads appreciated!



body entered function not working in godot

i am trying to make a node named "gear" change textures when it moves through a certain area but nothing happens, i tried making it print something when it collides with something, but nothing happens, this problem has been bugging me for days and i cant find any reason why, its hitbox is working but the function refuses to acknowledge it

the captialisation is alright i literally copied and pasted it to no avail, i looked at somone elses code other than the name of that node the function is exactly the same, what is going on, link to project



pd.read_html(url) - awkward table design

Table headings through the table are being converted into single column headings.

url = "https://www.environment.nsw.gov.au/topics/animals-and-plants/threatened-species/programs-legislation-and-framework/nsw-koala-strategy/local-government-resources-for-koala-conservation/north-coast-koala-management-area#:~:text=The%20North%20Coast%20Koala%20Management,Valley%2C%20Clarence%20Valley%20and%20Taree."
dfs = pd.read_html(url)
df = dfs[0]
df.head()

output

Be great if I could have the High preferred use as a column that assigns to the correct species. Tried reset_index() this did not work. I'm lost for searching can't find anything similar.

Response to @Master Oogway and thanks @DYZ for the edits.

Screen shot inspect element - multiple class ="table-striped"

The amendment suggested removes the error, but does not interact with the second table. Take White Box, Eucalyptus albens. Occurs in second table and not first. If I export dftable: Filter no White Box

If I write htmltable to .txt when using find_all:

enter image description here

I have never done this before and appreciate that this is annoying. Thanks for the help so far.

It appears that find_all is gathering all the table data. But the creating of dftable is limiting to the first "table-striped".



Which data type is suitable for a date like 31-12-2014 in Snowflake?

I have lots of data we want to store in Snowflake cloud but we could save the data into the snowflake due to date like 31-12-2014 which is given in an excel CSV file:

check the image]

I am trying:

"Shipment date" varchar(16777216),
"Shipment year" number(4),

which data type will be suitable for that purpose?



(UNITY, SHADER)Can you draw the same texture multiple times in a single pass?

I'm new to shaders, and I'm trying to make an outline of a tk2d spine object(a 2d character). I know there are other ways to obtain the outline effect, but this approach got me curious. (Please don't suggest another way to draw outlines, respectfully, because that is not my question.)

So basically how I'm trying to get the outline effect is by getting the vertexes of my object, input a color, and draw it 8 directions(top, down, left, right, 4 diagonal directions) by setting offsets to each direction.

I got this working, and it looks fine, but my shader code doesn't, because I have a total of 9 passes, 8 of which do the exact same thing(draw the same texture), with the only difference being the offset direction, and the last pass drawing the tk2d spine character. I don't like that I have 8 almost-exactly repeated codes, it seems to be a waste because there is an area where the same calculation is done 8 times, and I suppose performance would be affected as well.

So, my question is : can I compress the 8 passes into one? i.e. saving the vertex position for each direction, and passing that information to the fragment shader.

I tried upscaling the vertexes, but this didn't get me the effect I wanted, because the characters do not have smooth edges, and therefore the "outline" became rigged.

this is my current code:

Shader "Custom/Shader_Spine_Battle_Red" 
{
   Properties 
   {
      
      _Color ("Color", color) = (1, 0, 0, 1)
      _MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}
      _OutlineWidth ("OutlineWidth", float) = 1
   }
   
   SubShader
   {
      Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
      ZWrite Off Lighting Off Cull Off Fog { Mode Off } Blend SrcAlpha OneMinusSrcAlpha
      LOD 110
      
      Stencil{
         Comp Equal
         }
      
      Pass 
      {
         CGPROGRAM
         #pragma vertex vert_vct
         #pragma fragment frag_mult 
         #pragma fragmentoption ARB_precision_hint_fastest
         #include "UnityCG.cginc"

         sampler2D _MainTex;
         fixed4 _Color;
         float _OutlineWidth;

         struct vin_vct 
         {
            float4 vertex : POSITION;
            float4 color : COLOR;
            float2 texcoord : TEXCOORD0;
         };

         struct v2f_vct
         {
            float4 vertex : SV_POSITION;
            fixed4 color : COLOR;
            float2 texcoord : TEXCOORD0;
         };

         v2f_vct vert_vct(vin_vct v)
         {
            v2f_vct o;

            // the only difference in the 8 passes is the two lines below
            v.vertex.x += _OutlineWidth * 0.1;
            v.vertex.y += _OutlineWidth * 0.1;
            o.vertex = UnityObjectToClipPos(v.vertex);
            o.color = _Color;
            o.texcoord = v.texcoord;
            return o;
         }

         fixed4 frag_mult(v2f_vct i) : SV_Target
         {
            fixed4 col = tex2D(_MainTex, i.texcoord);
            _Color.a *= ceil(col.a);
            col.rgb = _Color;
            col.a *= _Color.a;
            return col;
         }
         
         ENDCG
      }
      // (x 8 with only the rows mentioned above different

Pass { CGPROGRAM #pragma vertex vert_vct #pragma fragment frag_mult #pragma fragmentoption ARB_precision_hint_fastest #include "UnityCG.cginc"

     sampler2D _MainTex;
     fixed4 _Color;
     float _OutlineWidth;

     struct vin_vct 
     {
        float4 vertex : POSITION;
        float4 color : COLOR;
        float2 texcoord : TEXCOORD0;
     };

     struct v2f_vct
     {
        float4 vertex : SV_POSITION;
        fixed4 color : COLOR;
        float2 texcoord : TEXCOORD0;
     };

     v2f_vct vert_vct(vin_vct v)
     {
        v2f_vct o;

        o.vertex = UnityObjectToClipPos(v.vertex);
        o.color = v.color;
        o.texcoord = v.texcoord;
        return o;
     }

     fixed4 frag_mult(v2f_vct i) : SV_Target
     {
        fixed4 col = tex2D(_MainTex, i.texcoord) * i.color;
        return col;
     }
     
     ENDCG
  } 

} }






2022-11-29

ErrorReply: NOAUTH Authentication required when using createCluster with redis in nodejs

I am trying to use elasticache redis cluster and using a password with it. When I try to write or read I am seeing. I am running out of ideas of things to try. I have tried to use password in the root node on the object and putting directly. I've tried other libraries and am seeing the same issues.

[ErrorReply: NOAUTH Authentication required.]

So here is the example of my code sorry for the mess.

const redis = require('redis');
const {
    createCluster,
} = redis;

const password = 'abc123';

function getRedisClient() {
    const rootNodes = [{
        url: `rediss://:${password}@${host}:6379`,
        rejectUnauthorized: true,
    }];
    return createCluster({
        rootNodes,
        defaults: {
            socket: {
                connectTimeout: 5000,
            },
        },
    });
}

const cluster = getRedisClient();
cluster.on('error', (err) => console.log('Redis Cluster Error', err));

const run = async () => {
    try {
        await cluster.connect();
        // console.log('cluster => ', cluster);
        console.log('writing... => ');
        const writeResult = await cluster.hSet('mkey', 'bob', 'my value');
        console.log('reading... =>');
        const readResult = await cluster.hGetAll('mykey');
        //
        // // console.log('writeResult => ', writeResult);
        // console.log('readResult => ', readResult);
    } catch (e) {
        console.error(e);
    }
}

run()
    .catch((e) => console.error('error => ', e));

I have tried using ioredis, redis-clustr, and many different variations of variables. Using redis-cli it works just fine.



How to move specific cells in an excel file to a new column with openpyxl in python

I am trying to moving some specific cells to a designated location. As shown in the image, would like to move data in cells D3 to E2, D5 to E4,..... so on so for. Is it doable with openpyxl? Any suggestions would be greatly appreciate it!! Click to see the image

Here is what I got so far. It worked per say.

wb=xl.load_workbook(datafile)
ws=wb['Sheet1']

#insert a new column #5
ws.insert_cols(idx=5,amount=1)
wb.save(datafile)

mr=ws.max_row
   
#move cells

for i in range (1,mr+1):
    v=ws.cell(row = i+1,column=4) 
    ws.cell(row=i,column =5).value=v.value

wb.save(datafile)
wb.close

How do I skip a row? I only wanted to copy values in every other row over.



How to print all columns and prevent an insertion of one when using lapply()?

I have a file with 28 columns and numerous rows >10000. I am splitting this file by the second column called gene_id, so that there are numerous outputs each file with a distinct gene_id.

variant_id gene_id tss_distance ma_samples ma_count maf pval_nominal slope slope_se hg38_chr hg38_pos ref_allele alt_allele hg19_chr hg19_pos ID new_MAF CHROM POS REF ALT A1 OBS_CT BETA SE P SD Variance
chr1_17726150_G_A_b38 ENSG00000272426.1 821374 68 78 0.0644628 0.764314 -0.0320846 0.106958 chr1 17726150 G A chr1 18052645 rs260514:18052645:G:A 0.058155 1 18052645 G A G 1597 0.0147047 0.0656528 0.822804 2.62364886486368 6.88353336610048
chr1_17729225_G_A_b38 ENSG00000117118.9 675055 205 226 0.186777 0.770706 0.00898192 0.0308023 chr1 17729225 G A chr1 18055720 rs11580304:18055720:G:A 0.194694 1 18055720 G A A 1597 0.00515331 0.022282 0.817129 0.890444032956592 0.792890575828
chr1_17729225_G_A_b38 ENSG00000117122.13 748390 205 226 0.186777 0.0373499 0.0553745 0.0265315 chr1 17729225 G A chr1 18055720 rs11580304:18055720:G:A 0.194694 1 18055720 G A A 1597 0.00515331 0.022282 0.817129 0.890444032956592 0.792890575828
chr1_177298830_G_A_b38 ENSG00000117122.13 7483450 245 246 0.106777 0.0377699 0.009745 0.0265315 chr1 17729225 G A chr1 18055720 rs11580304:18055720:G:A 0.194694 1 18055720 G A A 1597 0.00515331 0.022282 0.817129 0.890449757 0.79289055858
output 1
chr1_17726150_G_A_b38 ENSG00000272426.1 821374 68 78 0.0644628 0.764314 -0.0320846 0.106958 chr1 17726150 G A chr1 18052645 rs260514:18052645:G:A 0.058155 1 18052645 G A G 1597 0.0147047 0.0656528 0.822804 2.62364886486368 6.88353336610048

output 2
chr1_17729225_G_A_b38 ENSG00000117118.9 675055 205 226 0.186777 0.770706 0.00898192 0.0308023 chr1 17729225 G A chr1 18055720 rs11580304:18055720:G:A 0.194694 1 18055720 G A A 1597 0.00515331 0.022282 0.817129 0.890444032956592 0.792890575828

output 3
chr1_17729225_G_A_b38 ENSG00000117122.13 748390 205 226 0.186777 0.0373499 0.0553745 0.0265315 chr1 17729225 G A chr1 18055720 rs11580304:18055720:G:A 0.194694 1 18055720 G A A 1597 0.00515331 0.022282 0.817129 0.890444032956592 0.792890575828
chr1_17729883_G_A_b38 ENSG00000117122.13 7483450 245 246 0.106777 0.0377699 0.009745 0.0265315 chr1 17729225 G A chr1 18055720 rs11580304:18055720:G:A 0.194694 1 18055720 G A A 1597 0.00515331 0.022282 0.817129 0.890449757 0.79289055858

I am using the r script below:

df <- read.table("/data/coloc_eQTL/combined_GWAS_skin_eQTL_AL.txt", header = TRUE)

mylist <- split(df , f = df$gene_id)

lapply(names(mylist), function(x) write.table(mylist[[x]], file=paste(x,".txt"), sep="\t", row.names=FALSE, quote=FALSE))

However, I notice in the output file there is a column inserted at the start with numbers even though I have stated rownames = FALSE. Also, the output does not show the P column. Therefore, everything is misaligned. How can I ensure all columns are retained and an additional column is not added at the start?

number  variant_id  gene_id tss_distance    ma_samples  ma_count    maf pval_nominal    slope   slope_se    hg38_chr    hg38_pos    ref_allele  alt_allele  hg19_chr    hg19_pos    ID  new_MAF CHROM   POS REF ALT A1  OBS_CT  BETA    SE  SD  Variance
6253451 chr1_17726150_G_A_b38   ENSG00000074964.16  186315  68  78  0.0644628   0.966721    0.00151619  0.0363244   chr1    17726150    G   A   chr1    18052645    rs260514:18052645:G:A   0.058155    1   18052645    G   A   G   1597    0.0147047   0.0656528   0.822804    2.62364886486368    6.88353336610048

dput the original file (10 rows).

structure(list(variant_id = c("chr1_17726150_G_A_b38", "chr1_17726150_G_A_b38", 
"chr1_17726150_G_A_b38", "chr1_17726150_G_A_b38", "chr1_17726150_G_A_b38", 
"chr1_17726150_G_A_b38", "chr1_17726150_G_A_b38", "chr1_17726150_G_A_b38", 
"chr1_17726150_G_A_b38", "chr1_17726150_G_A_b38"), gene_id = c("ENSG00000272426.1", 
"ENSG00000117118.9", "ENSG00000142623.9", "ENSG00000142619.4", 
"ENSG00000179023.8", "ENSG00000228549.3", "ENSG00000058453.16", 
"ENSG00000159339.13", "ENSG00000074964.16", "ENSG00000117122.13"
), tss_distance = c(821374L, 671980L, 521024L, 477052L, -754832L, 
855205L, 804200L, 417955L, 186315L, 745315L), ma_samples = c(68L, 
68L, 68L, 68L, 68L, 68L, 68L, 68L, 68L, 68L), ma_count = c(78L, 
78L, 78L, 78L, 78L, 78L, 78L, 78L, 78L, 78L), maf = c(0.0644628, 
0.0644628, 0.0644628, 0.0644628, 0.0644628, 0.0644628, 0.0644628, 
0.0644628, 0.0644628, 0.0644628), pval_nominal = c(0.764314, 
0.955989, 0.352575, 0.00666648, 0.667965, 0.0943182, 0.489115, 
0.796736, 0.966721, 0.326205), slope = c(-0.0320846, -0.00275742, 
-0.0687903, -0.202377, 0.0460589, -0.180725, -0.0449686, 0.0258654, 
0.00151619, -0.0424019), slope_se = c(0.106958, 0.0499406, 0.0739349, 
0.0743021, 0.107318, 0.10783, 0.0649652, 0.10037, 0.0363244, 
0.0431489), hg38_chr = c("chr1", "chr1", "chr1", "chr1", "chr1", 
"chr1", "chr1", "chr1", "chr1", "chr1"), hg38_pos = c(17726150L, 
17726150L, 17726150L, 17726150L, 17726150L, 17726150L, 17726150L, 
17726150L, 17726150L, 17726150L), ref_allele = c("G", "G", "G", 
"G", "G", "G", "G", "G", "G", "G"), alt_allele = c("A", "A", 
"A", "A", "A", "A", "A", "A", "A", "A"), hg19_chr = c("chr1", 
"chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", "chr1", 
"chr1"), hg19_pos = c(18052645L, 18052645L, 18052645L, 18052645L, 
18052645L, 18052645L, 18052645L, 18052645L, 18052645L, 18052645L
), ID = c("rs260514:18052645:G:A", "rs260514:18052645:G:A", "rs260514:18052645:G:A", 
"rs260514:18052645:G:A", "rs260514:18052645:G:A", "rs260514:18052645:G:A", 
"rs260514:18052645:G:A", "rs260514:18052645:G:A", "rs260514:18052645:G:A", 
"rs260514:18052645:G:A"), new_MAF = c(0.058155, 0.058155, 0.058155, 
0.058155, 0.058155, 0.058155, 0.058155, 0.058155, 0.058155, 0.058155
), CHROM = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), POS = c(18052645L, 
18052645L, 18052645L, 18052645L, 18052645L, 18052645L, 18052645L, 
18052645L, 18052645L, 18052645L), REF = c("G", "G", "G", "G", 
"G", "G", "G", "G", "G", "G"), ALT = c("A", "A", "A", "A", "A", 
"A", "A", "A", "A", "A"), A1 = c("G", "G", "G", "G", "G", "G", 
"G", "G", "G", "G"), OBS_CT = c(1597L, 1597L, 1597L, 1597L, 1597L, 
1597L, 1597L, 1597L, 1597L, 1597L), BETA = c(0.0147047, 0.0147047, 
0.0147047, 0.0147047, 0.0147047, 0.0147047, 0.0147047, 0.0147047, 
0.0147047, 0.0147047), SE = c(0.0656528, 0.0656528, 0.0656528, 
0.0656528, 0.0656528, 0.0656528, 0.0656528, 0.0656528, 0.0656528, 
0.0656528), P = c(0.822804, 0.822804, 0.822804, 0.822804, 0.822804, 
0.822804, 0.822804, 0.822804, 0.822804, 0.822804), SD = c(2.62364886486368, 
2.62364886486368, 2.62364886486368, 2.62364886486368, 2.62364886486368, 
2.62364886486368, 2.62364886486368, 2.62364886486368, 2.62364886486368, 
2.62364886486368), Variance = c(6.88353336610048, 6.88353336610048, 
6.88353336610048, 6.88353336610048, 6.88353336610048, 6.88353336610048, 
6.88353336610048, 6.88353336610048, 6.88353336610048, 6.88353336610048
)), row.names = c(NA, 10L), class = "data.frame")

dput the results of mylist (the first 2 rows).

list(ENSG00000058453.16 = structure(list(variant_id = c("chr1_17726150_G_A_b38", 
"chr1_17728143_GC_G_b38", "chr1_17728290_G_A_b38", "chr1_17729225_G_A_b38", 
"chr1_17729967_C_T_b38", "chr1_17731217_C_T_b38"), gene_id = c("ENSG00000058453.16", 
"ENSG00000058453.16", "ENSG00000058453.16", "ENSG00000058453.16", 
"ENSG00000058453.16", "ENSG00000058453.16"), tss_distance = c(804200L, 
806193L, 806340L, 807275L, 808017L, 809267L), ma_samples = c(68L, 
395L, 167L, 205L, 233L, 233L), ma_count = c(78L, 486L, 183L, 
226L, 262L, 263L), maf = c(0.0644628, 0.401653, 0.15124, 0.186777, 
0.216529, 0.217355), pval_nominal = c(0.489115, 0.210837, 0.820243, 
0.301818, 0.137132, 0.128855), slope = c(-0.0449686, 0.0404518, 
0.0097847, 0.0413934, 0.0574705, 0.0585334), slope_se = c(0.0649652, 
0.0322899, 0.0430392, 0.0400502, 0.0386021, 0.038484), hg38_chr = c("chr1", 
"chr1", "chr1", "chr1", "chr1", "chr1"), hg38_pos = c(17726150L, 
17728143L, 17728290L, 17729225L, 17729967L, 17731217L), ref_allele = c("G", 
"GC", "G", "G", "C", "C"), alt_allele = c("A", "G", "A", "A", 
"T", "T"), hg19_chr = c("chr1", "chr1", "chr1", "chr1", "chr1", 
"chr1"), hg19_pos = c(18052645L, 18054638L, 18054785L, 18055720L, 
18056462L, 18057712L), ID = c("rs260514:18052645:G:A", "rs35592535:18054638:GC:G", 
"rs1572792:18054785:G:A", "rs11580304:18055720:G:A", "rs1890743:18056462:C:T", 
"rs7546135:18057712:C:T"), new_MAF = c(0.058155, 0.371673, 0.17466, 
0.194694, 0.197464, 0.198691), CHROM = c(1L, 1L, 1L, 1L, 1L, 
1L), POS = c(18052645L, 18054638L, 18054785L, 18055720L, 18056462L, 
18057712L), REF = c("G", "GC", "G", "G", "C", "C"), ALT = c("A", 
"G", "A", "A", "T", "T"), A1 = c("G", "G", "A", "A", "T", "T"
), OBS_CT = c(1597L, 1597L, 1597L, 1597L, 1597L, 1597L), BETA = c(0.0147047, 
0.0138673, -0.0126002, 0.00515331, 0.00415908, 0.00597402), SE = c(0.0656528, 
0.0269643, 0.0256229, 0.022282, 0.0220529, 0.0217018), P = c(0.822804, 
0.607124, 0.622959, 0.817129, 0.850434, 0.783139), SD = c(2.62364886486368, 
1.07756036432328, 1.02395469042471, 0.890444032956592, 0.88128862823752, 
0.867257800664993), Variance = c(6.88353336610048, 1.16113633876053, 
1.04848320804277, 0.792890575828, 0.77666964626077, 0.75213609281428
)), row.names = c(7L, 25L, 45L, 56L, 77L, 94L), class = "data.frame"), 
    ENSG00000074964.16 = structure(list(variant_id = c("chr1_17726150_G_A_b38", 
    "chr1_17728143_GC_G_b38", "chr1_17728290_G_A_b38", "chr1_17729225_G_A_b38", 
    "chr1_17729967_C_T_b38", "chr1_17731217_C_T_b38"), gene_id = c("ENSG00000074964.16", 
    "ENSG00000074964.16", "ENSG00000074964.16", "ENSG00000074964.16", 
    "ENSG00000074964.16", "ENSG00000074964.16"), tss_distance = c(186315L, 
    188308L, 188455L, 189390L, 190132L, 191382L), ma_samples = c(68L, 
    395L, 167L, 205L, 233L, 233L), ma_count = c(78L, 486L, 183L, 
    226L, 262L, 263L), maf = c(0.0644628, 0.401653, 0.15124, 
    0.186777, 0.216529, 0.217355), pval_nominal = c(0.966721, 
    0.954589, 0.17366, 0.865996, 0.547435, 0.565949), slope = c(0.00151619, 
    0.00102964, -0.0327149, -0.00378263, -0.01301, -0.0123769
    ), slope_se = c(0.0363244, 0.0180728, 0.0240136, 0.0224053, 
    0.0216116, 0.021548), hg38_chr = c("chr1", "chr1", "chr1", 
    "chr1", "chr1", "chr1"), hg38_pos = c(17726150L, 17728143L, 
    17728290L, 17729225L, 17729967L, 17731217L), ref_allele = c("G", 
    "GC", "G", "G", "C", "C"), alt_allele = c("A", "G", "A", 
    "A", "T", "T"), hg19_chr = c("chr1", "chr1", "chr1", "chr1", 
    "chr1", "chr1"), hg19_pos = c(18052645L, 18054638L, 18054785L, 
    18055720L, 18056462L, 18057712L), ID = c("rs260514:18052645:G:A", 
    "rs35592535:18054638:GC:G", "rs1572792:18054785:G:A", "rs11580304:18055720:G:A", 
    "rs1890743:18056462:C:T", "rs7546135:18057712:C:T"), new_MAF = c(0.058155, 
    0.371673, 0.17466, 0.194694, 0.197464, 0.198691), CHROM = c(1L, 
    1L, 1L, 1L, 1L, 1L), POS = c(18052645L, 18054638L, 18054785L, 
    18055720L, 18056462L, 18057712L), REF = c("G", "GC", "G", 
    "G", "C", "C"), ALT = c("A", "G", "A", "A", "T", "T"), A1 = c("G", 
    "G", "A", "A", "T", "T"), OBS_CT = c(1597L, 1597L, 1597L, 
    1597L, 1597L, 1597L), BETA = c(0.0147047, 0.0138673, -0.0126002, 
    0.00515331, 0.00415908, 0.00597402), SE = c(0.0656528, 0.0269643, 
    0.0256229, 0.022282, 0.0220529, 0.0217018), P = c(0.822804, 
    0.607124, 0.622959, 0.817129, 0.850434, 0.783139), SD = c(2.62364886486368, 
    1.07756036432328, 1.02395469042471, 0.890444032956592, 0.88128862823752, 
    0.867257800664993), Variance = c(6.88353336610048, 1.16113633876053, 
    1.04848320804277, 0.792890575828, 0.77666964626077, 0.75213609281428
    )), row.names = c(9L, 23L, 38L, 66L, 76L, 97L), class = "data.frame"))


Different Headers but Same Footer for Each Section

How would I create a document that has two sections where the headers are different but the footers are the same? For example, I would have the first section be labeled "Header 1" and the second section be labeled "Header 2" but the footer for both of those sections would be the same, in this case, "Author: John Apples."

I am working in MS Excel since I want to import some data from a sheet.

NOTE: I am very new to VBA

I tried using the "DifferentHeaderFirstPageHeaderFooter = True" but that applies to both the header and footer, not just the header. Also, I don't believe I am creating separate sections so it would be nice to have that feature implemented since I plan to add more sections that would have different headers. Any help would be greatly appreciated.

My Code

'Create a new Doc
Set myDocument = WordApp.Documents.Add
WordApp.Visible = True
WordApp.Activate

'Set Landscape Orientation
myDocument.PageSetup.Orientation = 1

'Set Margins
myDocument.PageSetup.BottomMargin = 26
myDocument.PageSetup.TopMargin = 26
myDocument.PageSetup.LeftMargin = 36
myDocument.PageSetup.RightMargin = 36

myDocument.Styles("Footer").Font.Size = 9
myDocument.Styles("Header").Font.Size = 18
myDocument.Styles("Header").Font.Color = RGB(0, 98, 155)

Set objSelection = WordApp.Selection

'Creating the header
objSelection.Sections(1).Headers(wdHeaderFooterPrimary).Range.InsertBefore "Header 1"
objSelection.Sections(1).Headers(wdHeaderFooterFirstPage).Range.InsertBefore "Header 2"

'Add Footer and Page Numbers
objSelection.Sections(1).Footers(WdHeaderFooterIndex.wdHeaderFooterPrimary).Range.InsertBefore "Author: John Apples"
objSelection.Sections(1).Footers(WdHeaderFooterIndex.wdHeaderFooterFirstPage).Range.InsertBefore "Author: John Apples"
        
objSelection.Sections(1).Footers(wdHeaderFooterFirstPage).PageNumbers.ShowFirstPageNumber = True
objSelection.Sections(1).Footers(wdHeaderFooterPrimary).PageNumbers.Add FirstPage:=True

        
objSelection.Font.Name = "Arial"
objSelection.Font.Size = 12
objSelection.Font.Color = RGB(0, 98, 155)
        
myDocument.Sections.First.PageSetup.DifferentFirstPageHeaderFooter = True

UPDATE:

https://i.stack.imgur.com/Ko9rd.png

https://i.stack.imgur.com/GWPPu.png

These two photos are what I would like the end product to look like.



All imports in WebStorm shown as unused at TypeScript backend project

https://i.stack.imgur.com/J0yZw.png This is how it looks for all files with .ts. And in .tsx files it also doesn't work.

Other projects in WebStorm work correct but they're written in .js and .jsx only.

Also I've tried reinstall WebStorm twice and set all to defaults, that doesn't help at all.



PHP Constructors and extending parent classes

I'm coming from Java, and wanting to use the constructor of a child class the way that it works in Java, but it appears that it doesn't work like that in PHP. The constructor of the child object can't seem to overwrite the instance variable values constructed in the parent object. Here, the parent object is being used just for the common methods between multiple child classes that will extend it. The parent class will never be called on its own.

When I instantiate a new TestPackage, I just get the initialized error values from the parent class. What gives?

<?php
interface Package{
    public function getCode();
    public function decode($packageCode);
    public function getSetName();
    public function getSetNameLang();
    public function getSubsetType();
    public function getSubsetTypeLang();
    public function setSubsetType($typeCode);
    public function getPackageOptionsArray();
    public function getChoicesArray();
    public function getOptionStatus($index);
    public function setOptionStatus($index, $booleanStatus);
}
?>

ParentPackage.php

class ParentPackage implements Package{
    private int $packageCode;
    private int $subsetType;
    private String $setName;
    private String $setNameLang;
    private $packageOptionsArray;
    private $subsetTypeArray;

    public function __construct(){
        $this->packageCode = 0;
        $this->subsetType = 0;
        $this->setName = "Error: parentClass";
        $this->setNameLang = "Error: Parent Class";

        $this->packageOptionsArray = array("Error",   //too much stuff to pass
                                            "Error",  //to a constructor as a variable
                                            "Error",
                                            "Error",
                                            "Error",
                                            "Error",
                                            "Error",
                                            "Error",
                                            "Error",
                                            "Error",
                                            "Error",
                                            "Error",
                                            );
        
        $this->subsetTypeArray = array("Error: Initializer",   //16
                                        "Error: Initializer",  //32
                                        "Error: Initializer",  //48
                                        );

     //........A whole bunch more stuff that is too much to pass as a variable to a constructor
     //..... OR let's just say that I don't want to do it that way

    }

TestPackage.php

class TestPackage extends ParentPackage{

    public function __construct(){
        parent::__construct();
        $this->packageCode = 0;
        $this->subsetType = 0;
        $this->setName = "layeredarch";
        $this->setNameLang = "Layered Arch";

        $this->packageOptionsArray = array("Customized welcome sign (choice of trellis half arch or smooth half arch insert up to 25 words text)",
                                            "3 piece seating chart half arch set (print service for cards is available for a small additional fee)",
                                            "Table numbers 1-30",
                                            "Gold Card option04 with choice of Gifts & Cards sign",
                                            "5 Reserved signs",
                                            "Up to 2 Double Half Arch Small signs (Gifts & Cards, Take One, Dont Mind if I Do, In Loving Memory)",
                                            "Up to 2 Sunset Small signs (Please Sign Our Guestbook, Gifts & Cards, In Loving Memory)",
                                            "1 Double Half Arch Medium sign (Cheers, The Bar, Guestbook, or Custom Acrylic Text)",
                                            "1 Double Full Arch Medium sign (Signature Drinks, or Custom Acrylic Text)",
                                            "Unplugged Ceremony sign",
                                            "Hairpin Record Player Prop",
                                            "%22Mr & Mrs%22 Custom Head Table Keepsake is a free gift in addition to the items above"
                                            );
        
        $this->subsetTypeArray = array("Full Set",   //16
                                        "Pick Six",  //32
                                        "Pick Four" //48
                                        );

    }


2022-11-28

React State not Updating in DataGrid MUI

for some reason a column in my Material-UI DataGruid wont update upon state change?

Code for state var: const [brandMap, setBrandMap] = useState(new Map());

fetchBrands function (which changes state)

async function fetchBrands() {
  const accessToken = await getToken();
  await fetch("http://localhost:8000/auth/brands",
    {
      method: "GET",
      headers: {
        Authorization: `Bearer ${accessToken}`
      }
    })
  .then((data) => data.json())
  .then(data => {
    setBrandMap(prevState => ({ ...prevState, ...data.data.reduce((map, obj) => (map[obj.id] = obj.name, map), {}) }))
  })
};

Columns list that I pass into MUI DataGrid, note the "FetchData(1)" function gets the data that the columns use.

useEffect(() => {
    setColumns(({
        columns: [
        { field: 'image', headerName: '', filterable: false, renderCell: (params) => (
          <img src={params.value} style=/>
        )},
        { field: 'name', headerName: 'Name', editable: true, filterOperators, flex: 1 },
        { field: 'sku', headerName: 'SKU', editable: true, filterOperators, flex: 1 },
 ....
        { field: 'brand_id', headerName: 'Brand', editable: true, flex: 1, renderCell: (params) => (
          <Typography variant="body2" color="text.secondary" component="p" style= >
            {brandMap[params.value] ?? <CircularProgress size={20} />}
          </Typography>
        )},
...
]}))
        updateData(1)
        fetchBrands()
  }, [user])
   


Return value must be of type Collections array returned Doctrine / Symfony 6

I have 2 order and line entities, with onetoMany / manytoOne relationship

I want to save a command with its lines, except I need to customize things, so I go through a datapersister function persist

If I don't try to save my lines it goes well, but as soon as I want to save the lines I get this message:

"App\Entity\DoRetourEntete::getRetALignes(): the return value must be of type Doctrine\Common\Collections\Collection, array returned

Basically I'm sending it an array while it's waiting for a collection.

But how to send it a collection in json?

In get everything works fine, I have my line detail when I call a command.

Here is my POST:

{
  "nomCommande": "2398",
  "cmdALignes": [
    {
      "ref": "maref1",
      "des1": "designation1",
      "qtt": 2
    },
    {
      "ref": "maref2",
      "des1": "designation2",
      "qtt": 2
    }
 
    
  ]
}

Here is a piece of my entities:

Commande:

/**
     * @ORM\OneToMany(targetEntity=lignes::class, mappedBy="ligneEntete")
     */
    private $cmdALignes;
 
    public function __construct()
    {
        $this->cmdALignes = new ArrayCollection();
    }
 
    /**
     * @return Collection|Post[]
     */
    public function getCmdALignes(): Collection
    {
        return $this->cmdALignes;
    }
 
    public function setCmdALignes(array $cmdALignes): self
    {
        $this->cmdALignes= $cmdALignes;
 
        return $this;
    }

and ligne :

/**
     *
     * @ORM\ManyToOne(targetEntity=Commande::class, inversedBy="cmdALignes")<br>
     */
    private $ligneEntete;
 
    public function __construct()
    {
        $this->ligneEntete= new ArrayCollection();<br>    }
 
    public function getLigneEntete(): ?Commande
    {
        return $this->ligneEntete;<br>    }
 
 
    public function setLigneEntete(?Commande $ligneEntete): self
    {
        $this->ligneEntete= $ligneEntete;
        return $this;
    }

In my data persister :

$commande = new Commande();
$commande->setNomCommande($data->getNomCommande);

and in principle if I want to browse my lines, I do:

foreach ($data->getCmdALignes() as $ligne){ }

I know that I send an array in a collection but how to do? thanks in advance

Guillaume



is not being positioned where I want it to go

I'm trying to create a fake website for a school project. So far I've added a banner of images that cross fade. The next thing I want to add is a bar where you could go to different pages like "food," "sale," and so on. I want this bar to go beneath the image banner. When I add the tags though, they are positioned on top of my banner. Before, I had used a simple image banner, and when I added the tags they positioned themselves beneath the image like normal. But because I'm using multiple images and animations, it's behaving differently and I don't know how to fix it.

enter image description here

Below is the effect that I want (but it's because I disabled the cross fade)

enter image description here

The closest solution I got is changing .fadein{height:1000px} and that moves the buttons down but I'm not sure how viable that is. I've also changed the position of the buttons from relative, absolute, etc. but none give the effect that I want.

Here is my code.

Edit: I don't know why you removed my thanks message but I'm putting it here again because I actually appreciate anyone who comments and I want them to know that. So thank you to anyone who reads and or replies to my post.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style type="text/css">
/* http://meyerweb.com/eric/tools/css/reset/ 
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure, 
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}

img {display:block}
    
.button {
    background-color:black;
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 20px;
    font-family: Segoe, "Segoe UI", "DejaVu Sans", "Trebuchet MS", Verdana, sans-serif;
}
.button:hover{background-color:aqua}

.header {
    background-color: #DB912B;
}
p {
    font-family: Segoe, "Segoe UI", "DejaVu Sans", "Trebuchet MS", Verdana, sans-serif;
}

.blackFriday{
    line-height: 40px;
    height: 40px;
    position: relative;
    overflow: hidden;
    background-color: antiquewhite z-index: 1;
    font-family: Segoe, "Segoe UI", "DejaVu Sans", "Trebuchet MS", Verdana, sans-serif;
}

/*.fadein{height:100px;}*/
    
/*Animated Banner*/
.fadein img {
    position:absolute;
    -webkit-animation-name: fade;
    -webkit-animation-iteration-count: infinite;
    -webkit-animation-duration: 12s;
    animation-name: fade;
    animation-iteration-count: infinite;
    animation-duration: 12s;
}

@-webkit-keyframes fade {
    0% {opacity: 0;}
    20% {opacity: 1;}
    33% {opacity: 1;}
    53% {opacity: 0;}
    100% {opacity: 0;}
}
@keyframes fade {
    0% {opacity: 0;}
    20% {opacity: 1;}
    33% {opacity: 1;}
    53% {opacity: 0;}
    100% {opacity: 0;}
}

#f1 {
    background-color: lightblue;
}
#f2 {
    -webkit-animation-delay: -8s;
    background-color: yellow;
}
#f3 {
    -webkit-animation-delay: -4s;
    background-color: lightgreen;
}
    
    
</style>

</head>

<body>
    <center>
      <p class="blackFriday" style="background-color:#191616; color: white; font-weight:bold;">BLACK FRIDAY SALE!</p>
    </center>
<div class="fadein">
    <img id="f3" src="banner1.png" width="100%" alt="">
    <img id="f2" src="banner2.png" width="100%"  alt="">
    <img id="f1" src="banner3.png" width="100%"   alt="">
</div>

<!--Buttons-->
<center>
    <p style="background-color:black; position:relative;" >
        <button class="button">food</button>
        <button class="button">toys</button>
        <button class="button">medicine</button>
        <button class="button">holiday sale</button>
        <button class="button">about us</button>
    </p>
</center>
    
</body>
</html>



How do you read through a file to get specific key value pairs with 1 key, and 2 values that are in a dictionary? [closed]

The first parameter is a dictionary representing data for a city and the second parameter is a data file that is open for reading. This function should modify the dictionary so that it contains the data in the file.

If a city with data in the file is already in the dictionary then its data should be updated. Otherwise it should be added to the dictionary with its data.

After this function is called, the dictionary should contain key/value pairs whose keys are the names of every city in the data file, and whose values are dictionaries which contain at least the population and economics_situation for those cities.

I'm just trying to figure how to even start with this? Can anybody give me a clue, or a first step on an approach?

We want our dict to look something like this: This is assuming if its an empty dictionary

'''

{'Brampton': {'#': 1, 'population': [703, 38907, 6789, 8769, 9087, 9087]},

'Pickering': {'#': 2, 'population': [789, 10987, 4678, 3980, 9087, 4789]},

'Toronto': {'#': 3, 'population': [220, 6789, 1678, 1098, 1098, 2908]},

'Oshawa': {'#': 4, 'population': [201, 2900, 8000, 3229, 2809, 2789]},

'Ottawa': {'#': 5, 'population': [100, 290, 5000, 2842, 948, 5677]}}

'''

Our file would have be (in row 1):

Column index Description

HT_ID_COL An ID that uniquely identifies each city.

HT_NBH_NAME_COL The name of the city. City names are unique.

HT_20_44_COL The number of people aged 20 to 44 with hypertension in the city.

NBH_20_44_COL The total number of people aged 20 to 44 in the city.

HT_45_64_COL The number of people aged 45 to 64 with hypertension in the city.

NBH_45_64_COL The total number of people aged 45 to 64 in the city.

HT_65_UP_COL The number of people aged 65 and older with hypertension in the city



Pass an object from getServerSideProps to page function

In the code below when I return a class object in the function getServerSideProps through props, in the page function the variable is undefined, just like in the code below.

export default function cars(obj){
    return <h1>counter: {obj.counter}</h1> // obj is undefined, why??
}
export async function getServerSideProps({req,res}){
    class Counter{
        constructor(){
            this.counter = 22
        }
    }
    var counter = new Counter()

    return {
        props:
        {
            obj:JSON.stringify(counter)
        }
    }
}

I was expecting that the page parameter obj would have the object counter and not be undefined.



2022-11-27

Flutter_map showing a black screen

I'm trying to use a map on my app, but i get a black screen instead of viewing the map.

I tried adding some marker to the map which show and can be manipulated, but where there should be the map is a black background instead.

My goal is to manage to show the map and navigate on it. I've already managed to show some elements on top on the map, but i cant get the map to display behind the elements. (i'm getting the same problem with or without the marker elements).

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:latlong2/latlong.dart';
import 'package:flutter_map/flutter_map.dart';

class MapScreen extends StatefulWidget {
  @override
  State<MapScreen> createState() => MapScreenState();
}

class MapScreenState extends State<MapScreen> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Stack(
          children: [
            FlutterMap(
              mapController: MapController(),
              options: 
              MapOptions(
                center: LatLng(
                    28.9, -13.5), 
                zoom: 9.2,
                maxZoom: 12,
                minZoom: 2,
              ),
              layers: [
                TileLayerOptions(
                  minZoom: 1,
                  maxZoom: 18,
                  backgroundColor: Colors.black,
                  urlTemplate:
                      'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
                  subdomains: ['a', 'b', 'c'],
                ),
                MarkerLayerOptions(
                  markers: [
                    mapTag("Hello World", 51.5, -0.09),
                    mapTag("Arrecife", 28.9, -13.5),
                  ],
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

Marker mapTag(TagText, Lat, Long) {
  return Marker(
    width: 80.0,
    height: 80.0,
    point: LatLng(Lat, Long),
    builder: (ctx) => Container(
      child: Stack(
        children: [
          Container(
            decoration: BoxDecoration(
              border: Border.all(color: Colors.white),
              color: Colors.grey[800],
              borderRadius: BorderRadius.all(
                Radius.circular(20),
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(12.0),
            child: Text(
              TagText,
              style: TextStyle(
                fontWeight: FontWeight.bold,
                color: Colors.white),
            ),
          ),
        ],
      ),
    ),
  );
}

enter image description here

Any idea why i'm getting a black screen and how to get the map to show?



How to add data-id to button, Using YouTube API [duplicate]

The javascript I am using here is following YouTube's Api.

https://developers.google.com/youtube/iframe_api_reference

What I am trying to do in the code is add the data-id

This: data-id="-Xgi_way56U"

to the button.

<button class="playa1 cover" type="button" data-container="play1"></button>

Which would then become this:

<button class="playa3 cover" type="button" data-container="play1" data-id="-Xgi_way56U"></button>

Currently, I have 2 containers: Placing the data-id on the button will allow me to remove 1 container from the html.

Am I right?

https://jsfiddle.net/7apg90wz/

How the code works is, after clicking a button a video will appear on the screen, click the X the buttons return to the screen where you can click on the 2nd button and a video will appear on the screen.

function onYouTubeIframeAPIReady() {  
  players.add(".playa1", {});
  players.add(".playa2", {});
}

<div class="container play1 with-curtain">
  <div class="inner-container curtain ">
    <div class="ratio-keeper">
      <div class="wrap">
        <div class="video video-frame" data-id="-Xgi_way56U"></div>
      </div>
    </div>
    <button class="exit" type="button" title="Exit" aria-label="Close"></button>
  </div>
</div>
<div class="container play2 with-curtain">
  <div class="inner-container curtain">
    <div class="ratio-keeper">
      <div class="wrap">
        <div class="video video-frame" data-id="0dgNc5S8cLI"></div>
      </div>
    </div>
    <button class="exit" type="button" title="Exit" aria-label="Close"></button>
  </div>
</div>

<div class="playButtonContainer with-curtain">
  <button class="playa1 cover" type="button" data-container="play1"></button>
  <button class="playa2 cover" type="button" data-container="play2"></button>
</div>


Double Loops in R: Use .name_repair to specify repair?

I have this dataset in R:

set.seed(123)

myFun <- function(n = 5000) {
  a <- do.call(paste0, replicate(5, sample(LETTERS, n, TRUE), FALSE))
  paste0(a, sprintf("%04d", sample(9999, n, TRUE)), sample(LETTERS, n, TRUE))
}

col1 = myFun(100)
col2 = myFun(100)
col3 = myFun(100)
col4 = myFun(100)
group <- c("A","B","C","D")
group = sample(group, 100, replace=TRUE)

example = data.frame(col1, col2, col3, col4, group)

       col1       col2       col3       col4 group
1 SKZDZ9876D BTAMF8110T LIBFV6882H ZFIPL4295E     A
2 NXJRX7189Y AIZGY5809C HSMIH4556D YJGJP8022H     C
3 XPTZB2035P EEKXK0873A PCPNW1021S NMROS4134O     A
4 LJMCM3436S KGADK2847O SRMUI5723N RDIXI7301N     B
5 ADITC6567L HUOCT5660P AQCNE3753K FUMGY1428B     D
6 BAEDP8491P IAGQG4816B TXXQH6337M SDACH5752D     C

I wrote this loop that compares different string distance metrics between all combinations of (col1,col2) and (col3,col4):

method = c("osa", "lv", "dl", "hamming", "lcs", "qgram", "cosine", "jaccard", "jw","soundex")

library(stringdist)

results = list()

for (i in 1:length(method))

{

method_i = method[i]
name_1_i = paste0("col1_col_2", method_i)
 name_2_i = paste0("col3_col_4", method_i)

p1_i = stringdistmatrix(col1, col2, method =  method_i, useNames = "string") %>%
            as_tibble(rownames = "a") %>%
            pivot_longer(-1, names_to = "b", values_to = name_1_i)

p2_i = stringdistmatrix(col3, col4, method =  method_i, useNames = "string") %>%
            as_tibble(rownames = "a") %>%
            pivot_longer(-1, names_to = "b", values_to = name_2_i)

p1_i = p1_i[,3]
p2_i = p2_i[,3]

final_i = cbind(p1_i, p2_i)

results[[i]] = final_i
}

final = do.call(cbind.data.frame, results)
final = cbind(col1,col2, col3,col4, final)

average_col1_col2_dist = (final$col1_col_2osa  + final$col1_col_2lv + final$col1_col_2dl      + final$col1_col_2hamming + final$col1_col_2lcs +     final$col1_col_2qgram  + final$col1_col_2cosine    + final$col1_col_2jaccard + final$col1_col_2jw   + final$col1_col_2soundex)/10

 average_col3_col4_dist =  ( final$col3_col_4osa     +    final$col3_col_4lv       +     final$col3_col_4dl  +     final$col3_col_4hamming +  final$col3_col_4lcs +  final$col3_col_4qgram  +   final$col3_col_4cosine +    final$col3_col_4jaccard  +    final$col3_col_4jw     +   final$col3_col_4soundex)/10

final = data.frame( col1, col2, col3, col4, average_col1_col2_dist,  average_col3_col4_dist)
final = scale(final)

Now, I would like to make this a "double loop" and have the same comparisons being done, but the comparisons should be made only within each "group" :

results = list()


for (i in 1:length(method))
for (j in 1:length(unique(example$group))

{

{

groups_j = unique(example$group[j])
my_data_i = file[which(file$fsa == groups_j  ), ]


method_i = method[i]
name_1_i = paste0("col1_col_2", method_i)
 name_2_i = paste0("col3_col_4", method_i)

p1_i = stringdistmatrix(my_data_i$col1, my_data_i$col2, method =  method_i, useNames = "string") %>%
            as_tibble(rownames = "a") %>%
            pivot_longer(-1, names_to = "b", values_to = name_1_i)

p2_i = stringdistmatrix(my_data_i$col3, my_data_i$col4, method =  method_i, useNames = "string") %>%
            as_tibble(rownames = "a") %>%
            pivot_longer(-1, names_to = "b", values_to = name_2_i)

p1_i = p1_i[,3]
p2_i = p2_i[,3]

final_i = cbind(p1_i, p2_i)
 results[[i]] = final_i

}
   
}

final = do.call(cbind.data.frame, results)
final = cbind(col1,col2, col3,col4, final)

average_col1_col2_dist = (final$col1_col_2osa  + final$col1_col_2lv + final$col1_col_2dl      + final$col1_col_2hamming + final$col1_col_2lcs +     final$col1_col_2qgram  + final$col1_col_2cosine    + final$col1_col_2jaccard + final$col1_col_2jw   + final$col1_col_2soundex)/10

 average_col3_col4_dist =  ( final$col3_col_4osa     +    final$col3_col_4lv       +     final$col3_col_4dl  +     final$col3_col_4hamming +  final$col3_col_4lcs +  final$col3_col_4qgram  +   final$col3_col_4cosine +    final$col3_col_4jaccard  +    final$col3_col_4jw     +   final$col3_col_4soundex)/10

final = data.frame( col1, col2, col3, col4, average_col1_col2_dist,  average_col3_col4_dist)
final = scale(final)

But I keep getting this error:

Error:
! Column 1 must be named.
Use .name_repair to specify repair.
Caused by error in `repaired_names()`:
! Names can't be empty.
x Empty name found at location 1.

Does anyone know how I can fix this?

Thank you!



How to pass a string from a secondary window to the main window in WPF

I am working on a to-do list application for a project. I would like to change the value of a string in an observableCollection. I am able to change the string in the same window but I would like to change the value from a textbox in a secondary window.

So what I tried to do was is change a string in the first window by using a textbox in the second window. By doing the way I have listed below it just blanks out the item I am trying to edit.

I would like to take the test from the textbox in the second window and use it to modify the taskName in the first window. Below I am going to include my code for the two c# files for the windows.

This is the main window but it is called DemoMainWindow:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ToDoList.ViewModels;
using ToDoList.Model;

namespace ToDoList
{
    /// <summary>
    /// Interaction logic for DemoMainWindow.xaml
    /// </summary>
    public partial class DemoMainWindow : Window
    {
        private ViewModel _viewModel;

        public string? EditedTaskName { get; set; }

        public DemoMainWindow()
        {
            InitializeComponent();

        
            TxtUCEnteredTask.txtLimitedInput.Text = "Do the dishes";

           _viewModel = new ViewModel();

            DataContext = _viewModel;


        }

        private void BtnAddTask_Click(object sender, RoutedEventArgs e)
        {
            _viewModel.Tasks.Add(new TaskModel() { TaskName = TxtUCEnteredTask.txtLimitedInput.Text });
        }

        private void BtnDeleteTask_Click(object sender, RoutedEventArgs e)
        {
            if(LstBoxTasks.SelectedItem != null)
            {
#pragma warning disable CS8604 // Possible null reference argument.
                _ = _viewModel.Tasks.Remove(item: LstBoxTasks.SelectedItem as TaskModel);
#pragma warning restore CS8604 // Possible null reference argument.
            }
        }

        private void BtnHelp_Click(object sender, RoutedEventArgs e)
        {
            HelpWindow helpWindow = new HelpWindow();

            helpWindow.Show();
        }

        private string? GetEditedTaskName()
        {
            return EditedTaskName;
        }

        private void BtnEditTask_Click(object sender, RoutedEventArgs e)
        {
            if (LstBoxTasks.SelectedItem != null)
            {
                EditWindow editWindow = new EditWindow();
                editWindow.Show();
               //_viewModel.Tasks[LstBoxTasks.SelectedIndex].TaskName = editedTaskName;
            }
        }
    }
}

This is the code for the C# file of the second window:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace ToDoList
{
    /// <summary>
    /// Interaction logic for EditWindow.xaml
    /// </summary>
    public partial class EditWindow : Window
    {
        public EditWindow()
        {
            InitializeComponent();
            var DemoMainWindow = this.DataContext;
        }

        private void BtnEdit_Click(object sender, RoutedEventArgs e)
        {
            ((DemoMainWindow)Application.Current.MainWindow).EditedTaskName = EditTextBox.Text;

            // _viewModel.Tasks[LstBoxTasks.SelectedIndex].TaskName = TxtUCEnteredTask.txtLimitedInput.Text;
        }
    }
}


cloudflare python bypassing

I'm trying too bypass cloudflare is there anything that im doing wrong? It just keeps returning the error code 403

import os
import requests

def clear():
    os.system('cls' if os.name == 'nt' else 'clear')

Heads = {
    'accept': '*/*',
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'en-US,en;q=0.9',
    'content-type': 'application/x-www-form-urlencoded',
    'origin': 'https://rblxwild.com',
    'referer': 'https://rblxwild.com/',
    'sec-ch-ua': '"Google Chrome";v="107", "Chromium";v="107", "Not=A?Brand";v="24"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': "Windows",
    'sec-fetch-dest': 'empty',
    'sec-fetch-mode': 'cors',
    'sec-fetch-site': 'same-origin',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36',
    "cookie": "_gcl_au=1.1.1876961596.1667714438; __mmapiwsid=e0b61652-f9fa-435f-84d5-1569a5a8782a:97606858c8e3a23f5545f36c6b749337dfab8db1; cf_clearance=IfMGgI6y0PiecdKCjg_P4oF3e7N1IaofGWLsWdhhLI8-1669369447-0-150; session=s%3AIUKmEfU6w_a1vjANCzYpHbgdxMNE7kjM.5vpUqzkjhI0VJDDxQZOwXBpWU2WdREmKhMSDg%2BJP40Q; __cf_bm=1jTWWnuejycehaRKVPBHBS3Cplxq2IujjBwBziLd3fk-1669429026-0-ARd9aZadaaE5t9ss/uPcyTOYyZE/0qzzENCVi7UZD7AjP8NIT5M40Y6ODZnFnDAqUzwLHnzEMb3QZkvVVW10y1JZWj2Y2vqcbPS1BMs5YcmH7BZK4SZp6+7em9bel/9URw=="
}

clear()
r = requests.get("https://rblxwild.com/", headers=Heads)
print(r) >> <Response [403]>

can you guys tell me if i did something wrong



2022-11-26

How to change row-'value' every time i try to position a label using grid?

I am trying to create a terminal GUI using python tkinter module and I already managed to access the tk.Label from TextFrame class.

class TextFrame(tk.Frame):
    def __init__(self, container):
        super().__init__()
        self.container = container
        self['bg']='black'
        self.pack(fill='both', expand=True)
        self.label = tk.Label(self)

Now the problem is that, I can't change the row everytime I call show() function inside Instances class.

class Instances(Window):
    def __init__(self):
        super().__init__()
        self.string = tk.StringVar()

        self.index_row = 0

        self.text_frame = TextFrame(self)
        self.text_frame.pack()
        self.entry_frame = EntryFrame(self)
        self.entry_frame.pack(side='bottom',fill='both')

    def show(self, e):     
        textvar = self.string.get()
        self.entry_frame.entry.delete(0, 'end')
        self.text_frame.label.config(text=textvar)
        self.text_frame.label.grid(column=0, row=self.index_row, sticky="w")
        self.index_row += 1

Here is the full code of my problem:

import tkinter as tk

class Window(tk.Tk):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.geometry('800x600')
        self.title('Terminal')

                
class Instances(Window):
    def __init__(self):
        super().__init__()
        self.string = tk.StringVar()
        
        self.index_row = 0
        
        self.text_frame = TextFrame(self)
        self.text_frame.pack()
        self.entry_frame = EntryFrame(self)
        self.entry_frame.pack(side='bottom',fill='both')
        
    def show(self, e):     
        textvar = self.string.get()
        self.entry_frame.entry.delete(0, 'end')
        self.text_frame.label.config(text=textvar)
        self.text_frame.label.grid(column=0, row=self.index_row, sticky="w")
        self.index_row += 1
        

class TextFrame(tk.Frame):
    def __init__(self, container):
        super().__init__()
        self.container = container
        self['bg']='black'
        self.pack(fill='both', expand=True)
        self.label = tk.Label(self)
        
        
    
                                    
                                    
class EntryFrame(tk.Frame):
    def __init__(self, container):
        super().__init__()
        self.entry = tk.Entry(self,  textvariable=container.string)
        self.entry.pack(fill='both')
        self.entry.bind('<Return>', container.show) 
                                                                                                                          
if __name__ == '__main__':
    window = Instances()
    window.mainloop()
                   

Any help would be appreciated.

Problem Solved

I added 1 line of code on show() function

def show(self, e):     
        textvar = self.string.get()
        self.entry_frame.entry.delete(0, 'end')
        self.text_frame.label = tk.Label(self.text_frame, fg='green', bg='black')
        self.text_frame.label.config(text=textvar)
        if len(textvar) > 0 :
            self.text_frame.label.grid(column=0, row=self.index_row, sticky="w")
            self.index_row += 1


Restricting access of some roles to some specific pages

@bp.route("/products/wishlist", methods=["GET"])
@login_required
@roles_required(
    "ADMIN",
    "CUSTOMER_STORE_MANAGER"
)
def product_wishlist():
    return product_wishlist_page()

I have role restrictions like this where each page has some role requirements, what I need to do is restricting some roles so they could have access to only some specific pages, for example when CUSTOMER_STORE_MANAGER logins into the webpage, they should only be able to view the product_wishlist

I thought about defining pages for each role and check if they are trying to access to pages which they have authorization. But I wonder if there is a more convenient way to do this in Flask?



How String.fromCharCode function work for mobile key board in html input field

I want to capture the keyboard key code and convert it to characters. I am using the String.fromCharCode javascript function but it only works on a computer keyboard it is not working with a mobile keypad. Any help will be appreciated.

$(".inputsmeter").keyup(function (e) { 
  let key = e.which; 
  let c = String.fromCharCode(key); 
  alert(c); 
});


CSS How To Blur/Bleed Sides Of Image

I have a large image centered like this: enter image description here

I want to image to bleed with a blur on the sides like this:

enter image description here

Is this possible? Also, is there a particular term used to describe what I want?

I tried adding a background image and blurring that, but then I realized that just blurs everything. I don't know what else to do.



Problems with images in react application

When using images in react, there is either a problem with typescript, or the image breaks on the site.

To solve the problem, I tried:

  1. Add url-loader and file-loader to the webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const BUILD_PATH = path.resolve(__dirname, './build');
const SRC_PATH = path.resolve(__dirname, './src/');
const PUBLIC_PATH = path.resolve(__dirname, './public')

module.exports = {
  entry: SRC_PATH + '/index.tsx',

  output: {
    path: BUILD_PATH,
    filename: 'bundle.js',
  },

  mode: process.env.NODE_ENV || 'development',

  resolve: {
    modules: [path.resolve(__dirname, 'src'), 'node_modules'],
    extensions: [ '.tsx', '.ts', '.js' ],
  },

  devServer: {
    static: PUBLIC_PATH,
  },

  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ['babel-loader']
      },
      {
        test: /\.tsx?$/,
        exclude: /node_modules/,
        loader: 'ts-loader'
      },
      {
        test: /\.(css|scss)$/,
        use: ['style-loader', 'css-loader', 'sass-loader'],
      },
      {
        test: /\.module.css$/,
        use: [
          {
            loader: "css-loader",
            options: {
              modules: true,
            },
          },
        ],
      },
      {
        test: /\.(jpg|png|svg)$/,
        loader: 'url-loader',
        options: {
          limit: 8192,
        },
      },
      {
        test: /\.(jpg|jpeg|png|gif|mp3|svg)$/,
        use: ['file-loader']
      },
    ],
  },

  plugins: [
    new HtmlWebpackPlugin({
      template: path.join(__dirname, 'public', 'index.html'),
    }),
  ],
};
  1. Import images as components
import React from 'react';

import logo from './header-logo.svg';

import styles from './Header.module.scss';

export const Header = () => {
  return <header className={styles.header}>
    <img src={logo} />
  </header>
};
  1. Create the images.d.ts file in the src/types directory
declare module "*.svg" {
  const content: any;
  export default content;
}
  1. And I even tried svgr..

But nothing helped. If I delete the images.d.ts file, typescript cannot detect the module when importing. When using images.d.ts, vscode does not show errors, but the picture is not displayed in the browser, and instead of the normal path, something strange data:image/svg+xml;base64,ZXhwb3J0IGRlZmF1bHQgX193ZWJwYWNrX3B1YmxpY19wYXRoX18gKyAiZWMzYzM1Nzg3YTljZTMyMzE4M2NmMzM2Y2EzMDBkOTkuc3ZnIjs=

And just in case, I attach tsconfig.json

{
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./build/",
    "noImplicitAny": true,
    "module": "es6",
    "target": "es5",
    "jsx": "react",
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "moduleResolution": "node",
    "plugins": [
      {
        "name": "typescript-plugin-css-modules"
      },
    ],
  },
}

I'm new to react so please don't judge strictly for stupid mistakes. I would appreciate any advice!



2022-11-25

Karate UI: Locating web elements on a HTML web page having multiple div tags with same ID?

My web app has a page displaying a .yaml file with key-val pairs, the yaml page has multiple(100+) tags having the same ID's for all the key-vals making it hard to locate the web element to update through the karate ui script.

Example of xpaths:

  1. key1: val1 //*[@id="ember5066"]/div[2]/div[6]/div[1]/div/div/div/div[5]/div[369]/pre/span/span[3]

  2. key2: val2 //*[@id="ember5066"]/div[2]/div[6]/div[1]/div/div/div/div[5]/div[373]/pre/span/span[3]

enter image description here

the below locator doesn't seem to work in this scenario

* string webElement = "//span[text()='abc']/following::span[text()='key1']//following-sibling::span"

Using the script syntax as below to update the value

script(webElement, "_.innerHTML='" + parameterized + "'")

Question: How to locate and update the value of the webElement or if there is a way to do indexing in karate?

Thanks in advance!

EDIT: @Peter Thomas
I am able to locate the element using this syntax:

  • def ele = locateAll('.classname')
  • def vals = ele.map(x => x.text)

Then print vals[40]
Is there a way to pass vals[40] to the 'input' syntax to be able to edit it in my tests?

Ex: * input(vals[40], 'test input')



File path in NextJS api route not resolving

I'm trying to resolve a file path in NextJS.

I understand that API routes are working a little bit differently when deployed to Vercel. In order to create a correct path to the file I assumed I had to do this:

const svg = fs.readFileSync(
  path.join(process.cwd(), "img", "file.svg"),
  "utf-8",
);

// ENOENT: no such file or directory

But I cannot make it work. The file cannot be found under that path.

How can I find the correct path for a file in NextJS api routes?

I've followed the documentation of this.

  • Next version is: 11.1.3
  • When logging the path, it is giving /var/task/data/project-root/img/file.svg


Returning data from firebase functions returns null

I have this code

exports.battle = functions.https.onCall((data, context) => {
    if(context.auth){
        var difficulty = randInt(2,10) / 10
        var user = context.auth["uid"]
        
        var userHP
        var userLevel
        var userDmg 
        var resultUserDmg = []
        var resultUserHp = []

        var monsterHP
        var monsterLevel
        var monsterDmg
        var resultMonsterDmg = []
        var resultMonsterHp = []

        

        var ref = db.ref(`players/${user}`);
        ref.child("hp").once("value", (snapshot) => {
           userHP = snapshot.val()
           monsterHP = userHP * difficulty

           ref.child("level").once("value", (snapshot) => {
                userLevel = snapshot.val()
                monsterLevel = userLevel * difficulty

                console.log("type"+typeof(userHP))
                console.log("value"+userHP)
                

                console.log("type"+typeof(monsterHP))
                console.log("value"+monsterHP)
                console.log("diff "+difficulty)


                while (userHP > 0 && monsterHP > 0){
                    userDmg = randInt(7, 14) * userLevel
                    monsterDmg = randInt(7, 14) * userLevel * difficulty


                    userHP = Math.round((userHP - monsterDmg)*10) /10;
                    console.log("userHP"+(userHP))
                    console.log("monsterDmg"+monsterDmg)
                    resultMonsterDmg.push(Math.round(monsterDmg*10) /10)
                    resultUserHp.push(Math.round(userHP*10)/10)
                    monsterHP = Math.round((monsterHP - userDmg)*10) /10;
                    console.log("userDmg"+userDmg)
                    console.log("monsterHP"+monsterHP)
                    resultUserDmg.push(Math.round(userDmg*10)/10)
                    resultMonsterHp.push(Math.round(monsterHP*10)/10)
                    console.log("----------")
                }

            
                var ref = db.ref(`players/${user}/coins`);
                ref.once("value", function(snapshot) {
                    var coinsNow = parseInt(snapshot.val());
                    const userRef = db.ref(`players/${user}`);
                    userRef.update({
                        'coins' : coinsNow+1
                    })
                });

                var result ={
                    userDmg : resultUserDmg,
                    userHp : resultUserHp,
                    monsterDmg : resultMonsterDmg,
                    monsterHp : resultMonsterHp,
                    monsterLvl : monsterLevel,
                };
                console.log("result is "+resultUserDmg)
                console.log("result is "+resultUserHp)
                console.log("result is "+resultMonsterDmg)
                console.log("result is "+resultMonsterHp)
                console.log("result is "+monsterLevel)
                return result 

            })
        })
    }
    else{
        console.log("User is not logged")
    }

    
})

Simply what this code does is that it calculates the player's life and damage against the monster using a while loop. This works correctly. The problem is when I want to send the data in the result variable to the user for further work. It returns null every time. Do you know where the error is? The only thing I can think of is that the error would be in the return. Maybe it gets called before the requested data has any value. I don't know. I can't figure it out.

But I am sure that the values I want to send to the user are not null but have the values they should have. Here is the log from the firebase console

Firebase console log

Here is code that i am useing for client returning. I always get null here

var battle = firebase.functions().httpsCallable('battle')
    battle().then(result => {
        console.log(result)
    })

UPDATE: Frank's response was great direction. But I don't think it's entirely clear. After a longer search, I found a more understandable solution for me here: https://medium.com/@stephane.giron/firebase-cloud-functions-oncall-returned-before-end-of-the-function-2d898d8ff259

I simply changed this at the beginning of the code ann add this to the end

exports.battle = functions.https.onCall((data, context) => {
    if(context.auth){
         return new Promise(function(resolve, reject) {
                
                 /* 
                   . . . .                       
                     code 
                   . . . .
                            */

                 reslove(result)
)}

I hope this has helped someone else. I recommend adding .catch to the end of the code for possible errores but I'm not entirely sure so I don't want to possibly confuse



.NET Maui Map Pin Example

I'm not sure this is actually possible, but I can't seem to find an example so maybe not. Just trying to display location pins on the map at certain long/lat coordinates i have available. Can anyone link an example?



Shared ViewModel Not Working With Bottom Sheet Dialog Fragment, DB and UI

i have a really simple vocabulary note app contains 2 fragment and 1 root activity. In HomeFragment i have a button "addVocabularyButton". When it is clicked a BottomSheetDialogFragment appears and user gives 3 inputs and with a viewmodel it is saved in DB. My problem is when i save the input to the DB it works fine but i cannot see in HomeFragment that word instantaneously. I have to re-run the app to see in home fragment. I am using Navigation library and recycler view in home fragment.

Github link : https://github.com/ugursnr/MyVocabularyNotebook

Home Fragment

class HomeFragment : Fragment() {
    private var _binding : FragmentHomeBinding? = null
    private val binding get() = _binding!!

    private var vocabularyAdapter = VocabulariesHomeAdapter()
    private lateinit var sharedViewModel: AddVocabularySharedViewModel
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentHomeBinding.inflate(layoutInflater,container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        //sharedViewModel = ViewModelProvider(this)[AddVocabularySharedViewModel::class.java]
        sharedViewModel = (activity as MainActivity).sharedViewModel
        sharedViewModel.getAllVocabulariesFromDB()
        observeAllVocabularies()
        prepareRecyclerView()
        addVocabularyOnClick()

        vocabularyAdapter.onItemDeleteClicked = {
            sharedViewModel.deleteVocabulary(it)
            observeAllVocabularies()

        }

    }


    private fun prepareRecyclerView(){

        binding.recyclerViewHome.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = vocabularyAdapter
        }
    }

    private fun addVocabularyOnClick(){
        binding.addVocabularyButton.setOnClickListener{
            val action = HomeFragmentDirections.actionHomeFragmentToAddVocabularyBottomSheetFragment()
            Navigation.findNavController(it).navigate(action)
        }
    }

    private fun observeAllVocabularies(){

        sharedViewModel.allVocabulariesLiveData.observe(viewLifecycleOwner, Observer {

            vocabularyAdapter.updateVocabularyList(it)

        })
    }

}

Dialog Fragment

class AddVocabularyBottomSheetFragment : BottomSheetDialogFragment() {
    private var _binding : FragmentAddVocabularyBottomSheetBinding? = null
    private val binding get() = _binding!!
    private lateinit var sharedViewModel: AddVocabularySharedViewModel

    private var vocabularyInput : String? = null
    private var translationInput : String? = null
    private var sampleSentenceInput : String? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentAddVocabularyBottomSheetBinding.inflate(layoutInflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        //sharedViewModel = ViewModelProvider(this)[AddVocabularySharedViewModel::class.java]
        sharedViewModel = (activity as MainActivity).sharedViewModel
        binding.addOrUpdateVocabularyButton.setOnClickListener {

            vocabularyInput = binding.vocabularyActualET.text.toString()
            translationInput = binding.vocabularyTranslationET.text.toString()
            sampleSentenceInput = binding.vocabularySampleSentenceET.text.toString()

            val inputVocabulary = Vocabulary(vocabularyInput,translationInput,sampleSentenceInput)
            insertVocabularyToDB(inputVocabulary)
            sharedViewModel.getAllVocabulariesFromDB()
            dismiss()

        }

    }

    private fun insertVocabularyToDB(vocabulary: Vocabulary){
        sharedViewModel.insertVocabulary(vocabulary)
    }

    
}

Shared ViewModel

class AddVocabularySharedViewModel(application: Application) : AndroidViewModel(application) {

    private var _allVocabulariesLiveData = MutableLiveData<List<Vocabulary>>()
    private var _vocabularyLiveData = MutableLiveData<Vocabulary>()

    val allVocabulariesLiveData get() = _allVocabulariesLiveData
    val vocabularyLiveData get() = _vocabularyLiveData

    val dao = VocabularyDatabase.makeDatabase(application).vocabularyDao()
    val repository = VocabularyRepository(dao)

    fun insertVocabulary(vocabulary: Vocabulary) = CoroutineScope(Dispatchers.IO).launch {
        repository.insertVocabulary(vocabulary)
    }
    fun updateVocabulary(vocabulary: Vocabulary) = CoroutineScope(Dispatchers.IO).launch {
        repository.updateVocabulary(vocabulary)
    }
    fun deleteVocabulary(vocabulary: Vocabulary) = CoroutineScope(Dispatchers.IO).launch {
        repository.deleteVocabulary(vocabulary)
    }

    fun getAllVocabulariesFromDB() = CoroutineScope(Dispatchers.IO).launch {
        val temp = repository.getAllVocabulariesFromDB()

        withContext(Dispatchers.Main){
            _allVocabulariesLiveData.value = temp
        }

    }

    fun getVocabularyDetailsByID(vocabularyID : Int) = CoroutineScope(Dispatchers.IO).launch {

        val temp = repository.getVocabularyDetailsByID(vocabularyID).first()

        withContext(Dispatchers.Main){
            _vocabularyLiveData.value = temp
        }

    }
    

}

Adapter

class VocabulariesHomeAdapter : RecyclerView.Adapter<VocabulariesHomeAdapter.VocabulariesHomeViewHolder>() {

    lateinit var onItemDeleteClicked : ((Vocabulary) -> Unit)


    val allVocabulariesList = arrayListOf<Vocabulary>()
    class VocabulariesHomeViewHolder(val binding : RecyclerRowBinding) : RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VocabulariesHomeViewHolder {
        return VocabulariesHomeViewHolder(RecyclerRowBinding.inflate(LayoutInflater.from(parent.context), parent, false))
    }

    override fun onBindViewHolder(holder: VocabulariesHomeViewHolder, position: Int) {
        val vocabulary = allVocabulariesList[position]
        holder.binding.apply {
            actualWordTV.text = vocabulary.vocabulary
            translationWordTV.text = vocabulary.vocabularyTranslation

            deleteButtonRV.setOnClickListener {
                onItemDeleteClicked.invoke(vocabulary)
                notifyItemRemoved(position)
            }
        }



    }

    override fun getItemCount(): Int {
        return allVocabulariesList.size
    }

    fun updateVocabularyList(newList : List<Vocabulary>){
        allVocabulariesList.clear()
        allVocabulariesList.addAll(newList)
        notifyDataSetChanged()
    }


}

I know there are lots of codes up there but i have a really big problems about using these dialog fragments. Thank you for your help.

enter image description here enter image description here



Vuejs select options

trying to make select option: DVD, Books, Furniture. When selecting DVD it changes the element content to: DVD selection content . Code on select option and the form that should change:

`<div class="typeswitcher">
                <div>
                    <h4 class="typeHeading">Type Switcher</h4>
                </div>
                <select name="typeSwitcher" id="typeSwitcher" v-model="itemType">
                    <option value="DVD" id="DVD" >DVD</option>
                    <option value="dimensions" id="Furniture">Furniture</option>
                    <option value="weight" id="Book">Books</option>
                    
                </select>
            </div>
            <form method="POST">
                    <div class="switcher-form">
                        <!-- //slice used to remove unnecessary iterations from the v-for -->
                        <div v-if="itemType === 'DVD'" class="row mb-1" v-html="item.size" v-for="item in switcherForm.slice(0,1)":key="item" >
                        </div>
                        <div v-if="itemType === 'dimensions'" class="row mb-1"v-html="item.dimensions" v-for="item in switcherForm.slice(1,2)":key="item">                            
                        </div>
                        <div v-if="itemType === 'weight'" class="row mb-1" v-html="item.weight" v-for="item in switcherForm.slice(2,3)":key="item" >
                        </div>
                        
                    </div>

import { createApp } from 'https://ift.tt/eWoq2Zn'

createApp({
    data() {
    return {
        title: 'Add product',
        itemType:null,
        switcherForm: [
                        {size:`
                        <label class="col-sm-4 col-form-label">Size (MB)</label>
                        <div class="col-sm-6">
                            <input id="size" type="text" name="size" placeholder="size" value="<?php echo $size; ?>"></input>
                            <h6>Please provide DVD size in MB.</h6>
                        </div>
                        `},
                        {dimensions:`
                        <label class="col-sm-4 col-form-label">Dimensions</label>
                        <div class="col-sm-6">
                            <input type="text" name="dimensions" placeholder="dimensions" value="<?php echo $dimensions; ?>"></input>
                            <h6>Please provide dimensions in HxWxL. format</h6>
                        </div>
                        `},
                        {weight:`
                         <label class="col-sm-4 col-form-label">Weight (KG)</label>
                        <div class="col-sm-6">
                            <input type="text" name="weight" placeholder="weight" value="<?php echo $weight; ?>"></input>
                            <h6>Please provide Book weight in KG.</h6>
                        </div>
                        `},

                    ] 
        }
    },
}).mount('#add-product')

    I got it work like this, connected the itemType:null to typeswitcher with v-model and then used <div v-if="itemType === 'DVD'" class="row mb-1" v-html="item.size" v-for="item in switcherForm.slice(0,1)":key="item" > with every input i wanted to render , used slice method to cut off excess v-for iterations. switcherForm is an array of objects with the html inputs.



  [1]: https://codepen.io/aTHEM2/pen/gOezQJr


2022-11-24

How can I add 2d text to three.js (already tried sprites, fontLoader, etc)?

I'm to add 2d text as labels next to an object, as shown in the image. I've tried sprites (which, as far as I understand, don't work in newer versions of three.js), fontLoader, and a couple of rendering mechanisms--but I have not had any success, unfortunately.

I see that I can use CSS3D, but I'm not sure what to grab from the sample codes. If someone could point me in the right direction, I would appreciate it.

Image showing what I'm trying to achieve

If anyone has any advice, I would greatly appreciate it.

The following are some key parts of my code:

    <script src="https://unpkg.com/three@0.132.2/build/three.min.js"></script>
      <script src="https://unpkg.com/three@0.132.2/examples/js/loaders/GLTFLoader.js"></script>
    <script src="https://unpkg.com/three@0.132.2/examples/js/loaders/DRACOLoader.js"></script>
    <script src="https://unpkg.com/three@0.132.2/examples/js/controls/OrbitControls.js"></script>

 <canvas id="c"></canvas>


    window.addEventListener('load', init);

   function init() {
    const width = window.innerWidth;
    const height = window.innerHeight;

    const canvasElement = document.querySelector('#c');
    const renderer = new THREE.WebGLRenderer({
        canvas: canvasElement,
    });
    renderer.setSize(width, height);

    const scene = new THREE.Scene();
    scene.background = new THREE.Color( 0xf5e8c6 );




    loader.load('js/PricklyPearObject/scene.gltf', (gltf) => {
        const model = gltf.scene;

         model.scale.set( 0.1,0.1,0.1);
           model.position.set(-2, 0, 0);
        scene.add(model);
    });



I tried using sprites, fontloader, and an approach using render but could not get them to work.



How to center the axes in Plotly on a 3d scatter plot in R?

I have a 3d scatter plot that I created with Plotly in R - is there anyway to move the axes to the middle? My plot right now looks similar to this plot that I made real quick in R:

enter image description here

But I would like to remove the grid background, the axis ticks, and move the axes to the middle of the plot to make it look similar to this:

enter image description here

My main problem is moving the axes to the middle while maintaining the x, y, and z labels on them. I have used traces to simulate the central axes, but then I have the issue of no axis labels when I remove the background grid and axes. What is the best way to go about this?

The code to recreate the first plot is below as well:

coords = list("x"=c(), "y"=c(), "z"=c())
for(phi in seq(0, 2*pi, 0.2)) {
  for(theta in seq(0, pi, 0.2)) {
    x = (8 * sin(theta) * cos(phi))
    y = (8 * sin(theta) * sin(phi))
    z = (8 * cos(theta))
    coords$x = append(coords$x, x)
    coords$y = append(coords$y, y)
    coords$z = append(coords$z, z)
  }
}
df = data.frame("x"=coords$x, "y"=coords$y, "z"=coords$z)
fig = plot_ly(df, x=~x, y=~y, z=~z, type="scatter3d",
              mode="markers", marker=list(size=3))
fig = layout(fig, scene=list(xaxis=list(range=c(-12, 12)),
                             yaxis=list(range=c(-12, 12)),
                             zaxis=list(range=c(-12, 12))))
fig


Where does BioPython store information related to various chemical molecules?

If we reconstruct a protein from a PDB file, is it enough to have a PDB file, or do we need more info external to the PDB?

Take, for example, the BioPython framework. If any info is needed external to the PDB files, where does this framework store them?

Can I open and check to see those files?



cross check if two df have different values and print any if there

i have two df and i wanna check for the id if the value differs in both df if so i need to print those.

example:

df1 = |id |check_column1|
      |1|abc|
      |1|bcd|
      |2|xyz|
      |2|mno|
      |2|mmm|
df2 = 
      |id |check_column2|
      |1|bcd|
      |1|abc|
      |2|xyz|
      |2|mno|
      |2|kkk|

here the output should be just |2|mmm|kkk| but i am getting whole table as output since index are different

This is what i did

output = pd.merge(df1,df2, on= ['id'], how='inner')

event4 = output[output.apply(lambda x: x['check_column1'] != x['check_column2'], axis=1)]


Determining the splitting ratio when augmenting image data

I have an image dataset that is quite imbalanced, with one class having 2873 images and another having only 115. The rest of the classes have ~250 images each. For reducing the imbalance, I decided to split the dataset into Train-Valid-Test components, with the major class having less proportion of images in the training set compared to the minor classes. Then I'll be augmenting the data in the training set. I intend to perform an 80-10-10 split on the dataset.

Which outcome shall be considered as an 80-10-10 split?

  • Splitting the dataset in the proportion 80-10-10, and THEN augmenting the training images (which would eventually result in >80% proportion for the training set after augmentation).
  • Splitting the dataset in a proportion such that it eventually results in an 80-10-10 split AFTER augmentation.

Also, is it acceptable to have an 85-7.5-7.5 split, provided it reduces imbalance in the dataset?



gettext/get_text while using beautifulsoup python

import requests
from bs4 import BeautifulSoup

price_limit = 15

URL = "https://a.co/d/5iUKt2H"

header = {
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
        "Accept-Encoding" : "gzip, deflate",
        "Accept-Language": "en-US,en;q=0.9,pl-PL;q=0.8,pl;q=0.7",
        "Connection": "keep-alive",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                      "Chrome/107.0.0.0 Safari/537.36"
}

response = requests.get(url=URL, headers=header)
soup = BeautifulSoup(response.text, 'html.parser')
price = float(soup.find("span", class_=["a-offscreen"]).get_text().split("$")[1])
name = " ".join(soup.find(id="productTitle").getText().split())

if 5 < price_limit :
    print("good")

It shows me in gettext/get_text error I tried to fix it and couldn't and this is the picture of how it looks in VSCode editor:



2022-11-23

How much do most C compilers remove constant expressions? [closed]

At least with macros, C compilers are expected to remove at least most constant math operations. For example, func((4 + 40) * 2) is expected to become func(88) during compilation.

I don't know what happens with something like this:

if (1)
    first();
else
    second();

(which is the same as)

const int mybool = 1;
if (mybool)
    first();
else
    second();

Does this just become first(); on most compilers?

What about:

while(0){
    dostuff();
}

Does this get removed?

If the answer isn't just "They all stay", where is a list of the things C compilers are expected to find and remove (aside from optimization)?



Importing RxJs in small Javascript project

I'm trying to import RxJs in a small javascript project using "import" in my script file but I keep on getting the following error:

Subscriber.js:10 Uncaught (in promise) TypeError: Cannot set properties of undefined (setting 'rxjs')

enter image description here

This is what my script file looks like:

<!DOCTYPE html>
<html lang="en-US">

  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="./styles/style.css">
    <title>Load RxJs using import</title>
  </head>

  <body>
    <h1>Importing RxJs Lib</h1>
    <div>
      <h1 id="info">'loading ...'</h1>
    </div>
    
    <!-- <script src="https://unpkg.com/rxjs@7.5.7/dist/bundles/rxjs.umd.js"></script> -->
    <script src="./js/script.js"></script>
  </body>
</html>

The script file looks like this:

// const updateUI = text => document.querySelectorAll('#info')[0].innerText = "finished";

const loadRxJsLib = async () => {
  await import('https://unpkg.com/rxjs@7.5.7/dist/bundles/rxjs.umd.js');
}

document.addEventListener('DOMContentLoaded', (event) => {
  loadRxJsLib();
});

document.addEventListener('readystatechange', (event) => {
  if (document.readyState === 'complete') {
    const { range } = rxjs;
    const { filter, map } = rxjs.operators;

    range(1, 200)
      .pipe(
        filter((x) => x % 2 === 1),
        map((x) => x + x)
      )
      .subscribe((x) => console.log(x))
  }
});

Any idea why it's not working? any comment will be highly appreciated



EXC_BREAKPOINT on NSFetchedResultsController.performFetch() because of -[CFString isNSString__]: message sent to deallocated instance

I'm running into a repeatable crash when calling -performFetch on my NSFetchedResultsController in what SEEMS like a data-related crash:

 NSFetchedResultsController *aFetchedResultsController =
        [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                            managedObjectContext:self.managedObjectContext
                                              sectionNameKeyPath:sectionnamekeypath
                                                       cacheName:cacheName];
        

aFetchedResultsController.delegate = self;

NSError *error = nil;
if (NO == [aFetchedResultsController performFetch:&error]) {
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
}

It crashes at the performFetch() call. I turned on Zombie checking and it printed:

*** -[CFString isNSString__]: message sent to deallocated instance 0x12c6071d0

I've checked all of the strings in my function and I can't find a string that has that address. I NSLog()'d all of the strings along with their address locations. I figured it would break on whatever NSLog() line that referenced the string in question, but all of them were still valid.

This makes me think this is a problem inside NSFetchedResultsController.performFetch() but it's hard to imagine that they have this kind of bug. So, what else can I do to find out what string this is?

I haven't run into problems like this since we switched over to ARC. I'm not sure how to figure out where this string comes from.

It SEEMS like this is data related though. My app pulls down data from our server, imports it into Core Data, and then uses the NSFetchedResultsController to show the data in a UITableView. I can login as various different users, download their data, and the FRC fetches and works just fine. But when I login as this one particular user, then it crashes. That user is one of our biggest users and their dataset is thousands and thousands of records, so it's not something I can easily look through to visually find things that might be weird. Doing further testing and will update this if I find any new info.

Any help?



Phaser 3 Tetris clone, Game freezes when trying to stack blocks

In the Tetris clone I'm making, I'm only working with single blocks right now and I have been trying to stack blocks in a few rows. Here is the code for the blocks

if (this.active == false){
    this.cube = Math.floor((Math.random()* 7));
    this.testblock = this.physics.add.sprite(608, 32, this.blocks[this.cube]);
    this.testblock.body.immovable = true;
    this.testblock.body.allowGravity = false;
    //this.testblock.body.setGravityY(-100);
    this.physics.add.collider(this.walls, this.testblock);
    this.physics.add.collider(this.p1, this.testblock);
    this.activeBlock = this.testblock;
    this.active = true;
}

this.activeBlock.y = this.activeBlock.y + 0.5;

if(Phaser.Input.Keyboard.JustDown(this.keyE)){
    console.log(this.activeBlock.y);
}

if(Phaser.Input.Keyboard.JustDown(this.keyA) && this.activeBlock.x != 352) {
    this.activeBlock.x = this.activeBlock.x - 64;
}

if(Phaser.Input.Keyboard.JustDown(this.keyD) && this.activeBlock.x != 928) {
    this.activeBlock.x = this.activeBlock.x + 64;
}

if (this.activeBlock.y == 416){
    if(this.activeBlock.x == 352 && this.row4[0] != null){
        this.row5[0] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 416 && this.row4[1] != null){
        this.row5[1] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 480 && this.row4[2] != null){
        this.row5[2] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 544 && this.row4[3] != null){
        this.row5[3] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 608 && this.row4[4] != null){
        this.row5[4] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 672 && this.row4[5] != null){
        this.row5[5] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 736 && this.row4[6] != null){
        this.row5[6] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 800 && this.row4[7] != null){
        this.row5[7] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 864 && this.row4[8] != null){
        this.row5[8] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 928 && this.row4[9] != null){
        this.row5[9] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
}


if (this.activeBlock.y == 480){
    if(this.activeBlock.x == 352 && this.row3[0] != null){
        this.row4[0] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 416 && this.row3[1] != null){
        this.row4[1] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 480 && this.row3[2] != null){
        this.row4[2] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 544 && this.row3[3] != null){
        this.row4[3] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 608 && this.row3[4] != null){
        this.row4[4] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 672 && this.row3[5] != null){
        this.row4[5] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 736 && this.row3[6] != null){
        this.row4[6] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 800 && this.row3[7] != null){
        this.row4[7] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 864 && this.row3[8] != null){
        this.row4[8] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 928 && this.row3[9] != null){
        this.row4[9] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
}

if (this.activeBlock.y == 544){
    if(this.activeBlock.x == 352 && this.row2[0] != null){
        this.row3[0] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 416 && this.row2[1] != null){
        this.row3[1] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 480 && this.row2[2] != null){
        this.row3[2] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 544 && this.row2[3] != null){
        this.row3[3] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 608 && this.row2[4] != null){
        this.row3[4] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 672 && this.row2[5] != null){
        this.row3[5] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 736 && this.row2[6] != null){
        this.row3[6] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 800 && this.row2[7] != null){
        this.row3[7] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 864 && this.row2[8] != null){
        this.row3[8] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 928 && this.row2[9] != null){
        this.row3[9] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
}

if (this.activeBlock.y == 608){
    if(this.activeBlock.x == 352 && this.row1[0] != null){
        this.row2[0] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 416 && this.row1[1] != null){
        this.row2[1] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 480 && this.row1[2] != null){
        this.row2[2] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 544 && this.row1[3] != null){
        this.row2[3] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 608 && this.row1[4] != null){
        this.row2[4] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 672 && this.row1[5] != null){
        this.row2[5] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 736 && this.row1[6] != null){
        this.row2[6] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 800 && this.row1[7] != null){
        this.row2[7] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 864 && this.row1[8] != null){
        this.row2[8] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 928 && this.row1[9] != null){
        this.row2[9] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
}

if (this.activeBlock.y == 672){
    if(this.activeBlock.x == 352){
        this.row1[0] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 416){
        this.row1[1] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 480){
        this.row1[2] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 544){
        this.row1[3] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 608){
        this.row1[4] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 672){
        this.row1[5] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 736){
        this.row1[6] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 800){
        this.row1[7] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 864){
        this.row1[8] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
    else if(this.activeBlock.x == 928){
        this.row1[9] = this.activeBlock;
        this.activeBlock = null;
        this.active = false;
    }
}

I've only programmed these first five rows for testing. The first block is landing just fine, but the game freezes when the second block lands. When checking inspection mode, the error message reads Cannot read properties of null (reading 'y') and for some reason the line that triggers it is

if (this.activeBlock.y == 672)

This is supposed to trigger the landing process of the first row, which already has a block in its space at that point. It's as if the line that triggers the landing process of the second row is never triggered.

I'm certain the block passes over the y coordinate, 608, that triggers landing in the second row. And I'm pretty sure nothing is setting the active block to null again along the way. Can someone tell where things went wrong?