Wednesday, September 22, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


typescript calculated values computations

Posted: 22 Sep 2021 09:11 AM PDT

Why is that my calculation below does not match the desired ouput and computation from excel ? is there an issue with the Nullish Coalescing Operator ? Thanks.

inputs :

10000000  125000  50000  11250000  

#target output enter image description here

#code

calc() {      this.metricsData["netProceeds"] = (this.dealDispositionFormFields.salePrice ?? 0) - (this.dealDispositionFormFields.brokerCommission ?? 0) - (this.dealDispositionFormFields.transactionCosts ?? 0);      this.metricsData["netSaleGainLossRate"] = (this.metricsData["netProceeds"] ?? 0) - (this.dealDispositionFormFields.netBookValue ?? 0);      this.metricsData["netSaleGainLossPercentage"] = (this.metricsData["netSaleGainLossRate"] ?? 0) - (this.dealDispositionFormFields.netBookValue ?? 0);    }  

#current output

enter image description here

Azure Stream Analytics - Joining Two Streaming Source

Posted: 22 Sep 2021 09:11 AM PDT

I am trying to join 2 Streaming Source which produces the same data output from EventHub. I am trying to find the Maximum Open Price for the Stock every 5 mins and trying to write it to the the Table. I am interested in the time at within the 5 min window at which the stock was maximum and the window time. I used the below mentioned query but it isn't producing any output for the same. I think I have messed the joining the condition.

  WITH Source1 AS (  SELECT      System.TimeStamp() as TimeSlot,max([open]) as 'MaxOpenPrice'      FROM      EventHubInputData  TIMESTAMP BY TimeSlot  GROUP BY TumblingWindow(minute,5)  ),  Source2 AS(  SELECT EventEnqueuedUtcTime,[open]  FROM EventHubInputDataDup TIMESTAMP BY EventEnqueuedUtcTime),  Source3 as (  select Source2.EventEnqueuedUtcTime as datetime,Source1.MaxOpenPrice,System.TimeStamp() as TimeSlot       FROM  Source1      JOIN Source2       ON Source2.[Open] = Source1.[MaxOpenPrice] AND DATEDIFF (minute,Source1,Source2) BETWEEN 0 AND 5      )  SELECT datetime,MaxOpenPrice,TimeSlot  INTO EventHubOutPutSQLDB  FROM Source3   ```      

(Python) Randomly select a list then an item from said list, then print it but ALSO print the list it is in

Posted: 22 Sep 2021 09:11 AM PDT

I know how to randomly select something from a list. I want to randomly select a list and then randomly select a thing from that list, to print it but I also want to be able to print the list the thing is in.

Say there's this:

a = [a1, a2, a3]  b = [b1, b2, b3]  

If it selects b2, I want it to print "b2, b" since b2 is in b. If it selects a1, it should print a.

I'm new to python, so help would be great.

How to generate random Double numbers in Google Sheets within range?

Posted: 22 Sep 2021 09:10 AM PDT

I am looking to generate a list of 50 numbers between -.15 to +.15 in Google Sheets

Both rand(), randarray() seem to offer positive numbers only. I hacked my way around n via a conditional =if(F5>=0.5,1,-1), but this seems grossly inelegant.

Is there a better, cleaner way to create a list of positive and negative numbers within a given range? Wish =RANDBETWEEN(-0.15,0.15) would work

Any ideas?

Footer and Header Layout Bug

Posted: 22 Sep 2021 09:10 AM PDT

Good day I hope this message finds you well. May you please help with advice on what could be the problem with the header and footer of my website. I did not make any changes to my website besides adding a blog post and updating plugins. When I logged in the other day, all of a sudden the header and footer layout was changed. It looks like there is a bug but I can't tell where. I use Advanced twenty seventeen these and my website is http://www.blvckuniverse.co.za Thank you very much. I look forward to your response. Kind regards

data.frame to jason in R

Posted: 22 Sep 2021 09:11 AM PDT

I have a data.frame that looks like this:

test <- data.frame(ID = c('1','1','1','1','1','1','1','1','2','2','2','2','2','2','2','2',                '3','3','3','3','3','3','3','3','4','4','4','4','4','4','4','4',                '5','5','5','5','5','5','5','5','6','6','6','6','6','6','6','6'),         CAT = c('CAT1','CAT1','CAT1','CAT1','CAT2','CAT2','CAT2','CAT2',                 'CAT1','CAT1','CAT1','CAT1','CAT2','CAT2','CAT2','CAT2',                 'CAT1','CAT1','CAT1','CAT1','CAT2','CAT2','CAT2','CAT2',                 'CAT1','CAT1','CAT1','CAT1','CAT2','CAT2','CAT2','CAT2',                 'CAT1','CAT1','CAT1','CAT1','CAT2','CAT2','CAT2','CAT2',                 'CAT1','CAT1','CAT1','CAT1','CAT2','CAT2','CAT2','CAT2'),         CODE = c('code1','code2','code3','code4','code1','code2','code3','code4',                  'code1','code2','code3','code4','code1','code2','code3','code4',                  'code1','code2','code3','code4','code1','code2','code3','code4',                  'code1','code2','code3','code4','code1','code2','code3','code4',                  'code1','code2','code3','code4','code1','code2','code3','code4',                  'code1','code2','code3','code4','code1','code2','code3','code4'),         DATE = c('date1', 'date2', 'date3','date4','date1','date2','date3','date4',                  'date1', 'date2', 'date3','date4','date1','date2','date3','date4',                  'date1', 'date2', 'date3','date4','date1','date2','date3','date4',                  'date1', 'date2', 'date3','date4','date1','date2','date3','date4',                  'date1', 'date2', 'date3','date4','date1','date2','date3','date4',                  'date1', 'date2', 'date3','date4','date1','date2','date3','date4'),         stringsAsFactors = F)  

I would like to have like following:

[  {"id": 1,    "CAT1": ['code1', 'code2','code3', 'code4'],    "CAT1_dates": ['date1',  'date2','date3','date4'],    "CAT2": ['code1', 'code2','code3', 'code4'],    "CAT2_dates": ['date1',  'date2','date3','date4'],  }  {"id": 2,    "CAT1": ['code1', 'code2','code3', 'code4'],    "CAT1_dates": ['date1',  'date2','date3','date4'],    "CAT2": ['code1', 'code2','code3', 'code4'],    "CAT2_dates": ['date1',  'date2','date3','date4'],  }  ]  

I understood that i need to write a function to do that job. I was not successfull.

From dataFrame to grouped Json in R

convert date frame to json in R

How to manipulate webRequest cookie in a cross-browser extension?

Posted: 22 Sep 2021 09:11 AM PDT

I am trying to edit cookie for all API calls using webRequest from a cross-browser (supporting chrome and Firefox) extension which I am creating.

Following is the code:

chrome.webRequest.onBeforeSendHeaders.addListener(   data => { // cookie manipulation logic },   { urls: ['https://*/*'] },   ['blocking', 'requestHeaders', 'extraHeaders']  );  

Problem: In Chrome, the code works with extraHeaders and in Firefox the same code works only if extraHeaders is removed. How can I make it work on both browsers?

Following is the browser doc reference for Chrome and Firefox.

Chrome: Chrome documentation states that extraHeaders is needed if we want to manipulate cookie. Reference picture below. Reference link: Link

enter image description here

Firefox:

Firefox documentation doesn't tell to use any extra spec to manipulate cookie. Instead it gives error when extraHeaders is present in the third argument of addListener.

jQuery .wrap() adjascent button HTML

Posted: 22 Sep 2021 09:10 AM PDT

I'm using

jQuery( ".quantity" ).wrap( "<div class=\"engrave_button\"></div>" )  

to wrap the quantity div with the engrave_button div.

But I need to include the button inside the engrave_button div. How can I do that?

Current HTML:

<div class="engrave_button">  <div class="quantity">          <input type="number" id="quantity_" class="input-text qty text" step="1" min="1" max="" name="quantity" value="1" title="Qty" size="4" placeholder="" inputmode="numeric">  </div>  </div>  </div>  // closing engrave_button div  <button type="submit" name="add-to-cart" value="123456" class="single_add_to_cart_button button alt">Add to cart</button>  </form>  

Needed HTML:

<div class="engrave_button">  <div class="quantity">          <input type="number" id="quantity_" class="input-text qty text" step="1" min="1" max="" name="quantity" value="1" title="Qty" size="4" placeholder="" inputmode="numeric">  </div>  <button type="submit" name="add-to-cart" value="123456" class="single_add_to_cart_button button alt">Add to cart</button>  </div>  // move closing engrave_button div here  </form>  

socket.io, vTiger, and csrf-magic.js. CORS issues

Posted: 22 Sep 2021 09:12 AM PDT

I'm attempting to create and add a socket.io module to my vTiger 7.0 so that I can update fields in real-time to multiple users.

We are have issues with users changing fields that should be locked while our quality control is attempting to check the record. This is causes things to get approved that should not. Node.js with vTiger will be awesome add-on.

The only problem is that vTiger uses csrf-magic.js to create a token that need to be included in the header to allow CORS

I have the middleware setup in my node project to allow my vtiger to make a request

vTiger is on vtiger.example.com

The node server is on node.example.com:3010

//server code node.example.com:3010  const fs = require("fs");  const config = require("./core/config").config();  var options = {      key: fs.readFileSync(config.key),      cert: fs.readFileSync(config.cert),      ca: fs.readFileSync(config.ca),      requestCert: true,      rejectUnauthorized: false,  };    const app = require("express")();  const server = require("https").Server(options, app);  const io = require("socket.io")(server);  // Need to send io to socket module    module.exports = io;  app.use(function (req, res, next) {      var allowedOrigins = [          "https://node.example.com",          "https://vtiger.example.com"      ];      var origin = req.headers.origin;          if (allowedOrigins.indexOf(origin) > -1) {          res.setHeader("Access-Control-Allow-Origin", origin);      }        res.header("Access-Control-Allow-Methods", "GET, OPTIONS");      res.header("Access-Control-Allow-Headers", "Content-Type, Authorization");      res.header("Access-Control-Allow-Credentials", true);            return next();  });    io.sockets.on("connection", require("./sockets/socket.js"));    const qc = require('./models/qc_model');  app.get('/', (req,res) => {      res.json({message: 'No Access'});  })    qc.pullLeadInfo(13622196, 10730, (data) => {      console.log(data.lead.lsloa_ver_by);  });                //Start the server  server.listen(config.port, () => {      console.log("server listening on port: " + config.port);  });  
\\client side vtiger.example.com  var socket = io.connect('https://node.example.com:3010');  

I get this error

Access to XMLHttpRequest at 'https://node.example.com:3010/socket.io/?EIO=4&transport=polling&t=NmEEc_r' from origin 'https://vtiger.example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.  csrf-magic.js:41 GET https://node.example.com:3010/socket.io/?EIO=4&transport=polling&t=NmEEc_r net::ERR_FAILED  

I cannot find any good documentation dealing with this issue. Any help would be great!

Creating a uniform distribution and then converting it into a normal distribution in JULIA

Posted: 22 Sep 2021 09:10 AM PDT

Hi it's my first using Julia so I have a few questions here about the code I'm working on. My task is to convert a uniform distribution of random numbers into a normal distribution. For the first part, I tried generating uniform random numbers first:

n = 5;  x = rand((1:10),n,n);  freq = counts(x);  total = sum(freq);  y = (freq/total)  

where x stores my generated random numbers and y holds the relative frequencies of each random number. Next, I moved on to graphing this uniform distribution:

using Plots  graph=histogram(x,y);  plot(graph, title="Uniform Distribution of Numbers from 1-10", xlabel = "Numbers", ylabel = "Relative Frequency", legend = false)  

So far I haven't encountered any errors for the uniform distribution. Feel free to correct me if I did anything wrong or if I did things right. I'm currently stuck on how to transform the uniform distribution into a normal distribution. I'm still researching about it so any tips on how to do it is appreciated for the meantime. Thank you

How to show a div only sometimes randomly?

Posted: 22 Sep 2021 09:12 AM PDT

I am trying to make my own subscription opt-in pop-up in html on my website. I want the pop-up to show only sometimes randomly. I don't want it to be visible all the time. I want it to be visible 1/3rd of the times. Please help me how to do it. I looked up on the web but it always misunderstood my question, so I am posting it here. Here is the code:

<div id="demo-float" class='demo-float'>    <span class='df-hide'>      <i class='fas fa-times'></i>    </span>    <div class='df-logo'></div>    <h3>Subscribe</h3>    <p class='excerpt'>Would you like to receive notifications on latest updates from Usual Queries?</p>    <a href='https://usualqueries.blogspot.com/p/subscribe.html' title='Sub'>Subscribe</a>  </div>  

Here is the link to that pop-up (i.e. my website): https://usualqueries.blogspot.com/

Help me. Thanking you in appreciation!

How to read file from a specific location and cache it just to avoid multiple calls

Posted: 22 Sep 2021 09:10 AM PDT

I have a simple requirement where I have to read a file from a specific location and upload it to a sharedPoint (a different location). Now this reading file process can be multiple times so to avoid multiple calls, I want to store the file into a cache and read it from there. Now I am not bothered on the contents of the file. Just have to read from the spefied location and upload. Adn my application is a Java application. Can anyone suggest best way to implement the above requirement.

MySQL JSON with arbitrary keys to table

Posted: 22 Sep 2021 09:11 AM PDT

There is a map nested in a large json payload like

{      "map": {          "key1": "value1",          "key2": "value2",          "key3": "value3"      },      // more stuff  }  

I would like to generate a table like that:

+------#--------+  | Key  | Value  |  +------#--------+  | key1 | value1 |  | key2 | value2 |  | key3 | value3 |  +------#--------+  

The only thing I can think of is writing a stored function that loops over JSON_KEYS to convert all key value pairs into

[{"key":"key1", "value":"value1"}, {"key":"key2", "value":"value2"}, ...]  

which makes the task trivial with JSON_TABLE.

Is there a faster and more elegant way?

String to integer list or integer array

Posted: 22 Sep 2021 09:10 AM PDT

Hi I'm new to java I want to change a String "3,4,5" to an Array of integer like this "[3,4,5]"

String dayOfWeekShipment = "3,4,5";    String[] dayOfWeekShipmentArString = dayOfWeekShipment.split(",");            log.info(String.valueOf(dayOfWeekShipmentArString));            int[] dayOfWeekShipmentArInt = new int[dayOfWeekShipmentArString.length];  for (int i = 0; i < dayOfWeekShipmentArString.length; i++) {      dayOfWeekShipmentArInt[i] = Integer.parseInt(dayOfWeekShipmentArString[i]);  }  

I need to loop it later to find the closest number to Integer todayDay for example

Integer tempInt = 7;  Integer todayDay = 1;  for (int i = 0; i < dayOfWeekShipment.length(); i++) {     if(dayOfWeekShipmentArInt[i] > todayDay && dayOfWeekShipmentArInt[i] <= tempInt){        tempInt = dayOfWeekShipmentArInt[i];     }   }  

It supposed to work but , it shows error like this Ljava.lang.String;@6f57e7dd

Some said I should use List and change it to List

Any solution so I can loop that string 3,4,5 to Integer and put my logic to it ?

Flutter - Centering TextField on appBar not working

Posted: 22 Sep 2021 09:10 AM PDT

I have an appbar with a textfield as the title, and when I pass centerTitle: true in the appbar, it doesn't center and stays aligned to the left.

Here's my code

appBar: AppBar(          // Where user inputs the title of the note          centerTitle: true,          title: TextField(            // The style of the input field            decoration: InputDecoration(              hintText: 'Title',              icon: Icon(Icons.edit), // Edit icon              // The style of the hint text              hintStyle: TextStyle(                color: Colors.black,                fontSize: 18,              ),            ),            controller:                titleAndNoteController[0], // The controller of the input box          ),          bottom: PreferredSize(            child: Opacity(              opacity: 0.25,              child: Divider(                color: Colors.black,                thickness: 1,                endIndent: 150,                indent: 150,              ),            ),            preferredSize: Size.fromHeight(4.0),          ),          iconTheme: IconThemeData(color: Colors.black),          backgroundColor: Colors.transparent,          elevation: 0.0,        ),  

How can I make this code working in python? [closed]

Posted: 22 Sep 2021 09:11 AM PDT

Hi i need to do the same thing that i do in this code but in python, can someone help me? Im having many difficults doing this. Is there a way to use two list and not the bidimensional array se[BLINK_ROW][2] ????

#define BLINK_ROW 10  int main()  {      int a[] = {1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1};      int i, h = 0, count = 0;      int se[BLINK_ROW][2];        int size_a = sizeof(a) / sizeof(a[0]);        for (int i = 0; i < size_a; i++) {          if (a[i] == 0) {                se[h][0] = i;                while (a[i] == 0)                  i++;                se[h][1] = i-1;                h++;                count++;          }      }        printf("blink: %d\n", count);        for (i = 0; i < count; i++)          printf("inizio fone: %d\t%d\n", se[i][0], se[i][1]);        return 0;  }  

I tried to make this in python, using Matrix as bidimensional array and 'eyeLF' as list that contains the 0 and the other value.

Matrix = [[0 for x in range(20)] for y in range(20)]             count = 0      h=0            for i, lf in enumerate(eyeLF):          if(eyeLF[i] == 0):              Matrix[h][0]          while eyeLF[i] == 0:              i+=1          Matrix[h][1] = i-1          h+=1          count+=1        print("blink: %d\n", count)        for i in range(0,count,1):          print("inizio fine: %d\t%d\n", Matrix[i][0], Matrix[i][1])  

My achievement is get when element in the list are 0 and count them, but when the 0 are in sequence it count as one, examples:

int a[] = {1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1};  

I want to achieve that the first 0 is in 5th position to 8th count as 1 because of the sequence, the next 0 count as 1, and has no other sequence of 0

How to display a version # in a customUI ribbon

Posted: 22 Sep 2021 09:11 AM PDT

I have a Excel VBA project where I expect to issue updates. It has a custom UI ribbon. For support purposes (screen captures), I want to display the app's version number in the ribbon, which would be read from a hidden sheet. I was hoping to do this with just a label control. But it does not appear that a label control has a callback. I thought I would try it with an Edit Box without an on_change capability. Unless I am using it wrong, InvalidateControl still allows me to type into the Edit Box.

Sub GetVersion(control As IRibbonControl, ByRef sVversion)      sVversion = ThisWorkbook.Sheets("Sheet1").Range("A1").Text      myRibbon.InvalidateControl "GetVersion"  End Sub  

Does anyone have any suggestion?

Other ideas I have considered would be a button control that displays the version in a MsgBox or UserForm, or a button with no functionality and just displays a tool tip.

Should i cast different?

Posted: 22 Sep 2021 09:11 AM PDT

I have this C code(Is not for PC. Is 8bit microcontroller, CCS Compiler)

long SirenVolt;//unsigned int16  long long DummyVolt;//unsigned int32    DummyVolt=read_adc();//Function always get values from 0 to 1024  SirenVolt=(long long)((493*DummyVolt)/100);  

The last line should be cast as long instead? I need that SirenVolt gets an unsigned int16(long, according the CCS Compiler) enter image description here

how I can change the distance between text and tile

Posted: 22 Sep 2021 09:10 AM PDT

So I have two SwitchListTiles on my modal Page, and the problem is that the text doesn't fit into it. (it takes 3 lines, but should 1) How can I make it to be in one single line, without decreasing it's font size

child: SwitchListTile(          value: state.filter.flagId == null ? false : true,          onChanged: (newValue) =>              context.read<FilterBloc>().add(HotPressed(newValue)),          title: Text(            AppLocalizations.of(context)!.hotAdds.capitalize(),            style: FlutterFlowTheme.dark50016.copyWith(),          ),          tileColor: FlutterFlowTheme.white,          activeColor: FlutterFlowTheme.primaryColor,          dense: true,          controlAffinity: ListTileControlAffinity.trailing,        ),  

I was thinking that the possible answer could be to decrease the distance between tile, but don't know how to do it

Replace "OR" on 2 indexes with a faster solution (UNION?)

Posted: 22 Sep 2021 09:10 AM PDT

I'm querying shopping-carts in a shop-system, like:

DROP TABLE IF EXISTS c;  CREATE TABLE c (    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,    `user` int(10) unsigned DEFAULT NULL,    `email` VARCHAR(255) NOT NULL DEFAULT '',     `number` VARCHAR(20) NOT NULL DEFAULT '',    PRIMARY KEY (`id`),    KEY `user`(`user`),    KEY `email`(`email`),    UNIQUE KEY `number`(`number`)  ) ENGINE=InnoDB;    INSERT INTO c SET user=1, email="test1@example.com", number="00001";  INSERT INTO c SET user=2, email="test2@example.com", number="00002";  INSERT INTO c SET user=3, email="test3@example.com", number="00003";  INSERT INTO c SET user=4, email="test1@example.com", number="00004";  INSERT INTO c SET user=1, email="test1@example.com", number="00005";  

I need to query records of c with a column which shows the number of carts which have the same user OR the same email. So I do:

SELECT c.number,          (SELECT COUNT(DISTINCT (id)) FROM c AS c2                    WHERE c2.email = c.email OR c2.user = c.user         ) AS ordercount  FROM c;         +--------+------------+  | number | ordercount |  +--------+------------+  | 00001  |          3 |  | 00002  |          1 |  | 00003  |          1 |  | 00004  |          3 |  | 00005  |          3 |  +--------+------------+  

This works, but the problem is that the OR is very slow, because MySQL/MariaDB doesn't use any key in the subquery:

EXPLAIN SELECT c.number,                  (SELECT COUNT(DISTINCT (id)) FROM c AS c2                     WHERE c2.email = c.email OR c2.user = c.user                 ) AS ordercount          FROM c;    +----+--------------------+-------+------------+------+---------------------------+--    ----+---------+------+------+----------+-------------+  | id | select_type        | table | partitions | type | possible_keys             | key  | key_len | ref  | rows | filtered | Extra       |  +----+--------------------+-------+------------+------+---------------------------+------+---------+------+------+----------+-------------+  |  1 | PRIMARY            | c     | NULL       | ALL  | NULL                      | NULL | NULL    | NULL |    5 |   100.00 | NULL        |  |  2 | DEPENDENT SUBQUERY | c2    | NULL       | ALL  | PRIMARY,number,user,email | NULL | NULL    | NULL |    5 |    36.00 | Using where |  +----+--------------------+-------+------------+------+---------------------------+------+---------+------+------+----------+-------------+  

Even forcing the index doesn't make the DB using it:

EXPLAIN SELECT c.number,                  (SELECT COUNT(DISTINCT (id)) FROM c AS c2 FORCE INDEX(email, user)                    WHERE c2.email = c.email OR c2.user = c.user                 ) AS ordercount          FROM c;    +----+--------------------+-------+------------+------+---------------------------+--    ----+---------+------+------+----------+-------------+  | id | select_type        | table | partitions | type | possible_keys             | key  | key_len | ref  | rows | filtered | Extra       |  +----+--------------------+-------+------------+------+---------------------------+------+---------+------+------+----------+-------------+  |  1 | PRIMARY            | c     | NULL       | ALL  | NULL                      | NULL | NULL    | NULL |    5 |   100.00 | NULL        |  |  2 | DEPENDENT SUBQUERY | c2    | NULL       | ALL  | PRIMARY,number,user,email | NULL | NULL    | NULL |    5 |    36.00 | Using where |  +----+--------------------+-------+------------+------+---------------------------+------+---------+------+------+----------+-------------+  

Using either column "email" or column "user" works fine, the key is used:

EXPLAIN SELECT c.number,                  (SELECT COUNT(DISTINCT (id)) FROM c AS c2 WHERE c2.email = c.email) AS ordercount          FROM c;    +----+--------------------+-------+------------+------+---------------------------+-------+---------+--------------+------+----------+-------------+  | id | select_type        | table | partitions | type | possible_keys             | key   | key_len | ref          | rows | filtered | Extra       |  +----+--------------------+-------+------------+------+---------------------------+-------+---------+--------------+------+----------+-------------+  |  1 | PRIMARY            | c     | NULL       | ALL  | NULL                      | NULL  | NULL    | NULL         |    5 |   100.00 | NULL        |  |  2 | DEPENDENT SUBQUERY | c2    | NULL       | ref  | PRIMARY,number,user,email | email | 767     | test.c.email |    3 |   100.00 | Using index |  +----+--------------------+-------+------------+------+---------------------------+-------+---------+--------------+------+----------+-------------+  

The problem is that the query runs on large table with about 500.000 entries, making the query taking about 30 seconds only to query a subset of 50 records. Running the query only with the match for "email" or only with the match for "user" it just takes about 1 second for 50 records.

So I need to optimize the query. I tried to change the OR into an UNION:

SELECT c.number,   (SELECT COUNT(DISTINCT (id)) FROM       ((SELECT u1.id FROM c AS u1 WHERE       u1.email = c.email      )      UNION DISTINCT      (SELECT u2.id FROM c AS u2 WHERE      u2.user = c.user      )) AS u2  ) AS ordercount  FROM c;  

but I'm getting the error: ERROR 1054 (42S22): Unknown column 'c.email' in 'where clause'

Any idea how to make this query using indexes to be faster?

Check if a Driver is Loaded on Windows

Posted: 22 Sep 2021 09:11 AM PDT

I'm effectively trying to implement the following PowerShell function:

# Checks for the presence of a loaded driver.  function Check-Driver($Driver) {      ...  }  

I've looked around and haven't found a good way to do this. If I had a kernel debugger attached, I could just run lm to see everything, but I want to automate something for our CI to validate things are set up in the correct state. I have come up with one way (below) using verifier.exe but I don't like having to change the state of the system just to check this.

# Checks for the presence of a loaded driver.  function Check-Driver($Driver) {      $Found = $false      try {          $Start = verifier.exe /volatile /adddriver $Driver          $Stop = verifier.exe /volatile /removedriver $Driver          $Found = $Stop.Contains("An instance of the service is already running")      } catch { }      $Found  }  

How to refactor a function so that it works for custom slice types holding different but similar structs

Posted: 22 Sep 2021 09:11 AM PDT

I have two different types of activity structs which both have a StartTime. For both of these activity types I have defined a type for a slice of activities. For both of these activity types I want to perform the same processing of their start times. I currently have to have 2 copies of the function, differing only in parameter type, as I cant work out how to get a single function to accept either type.

I've tried adding an interface above the activity types based on the StartTime, but it didnt help due to the custom slice types.

How can I factor out this function so that it can process either activity type?

Here is an example of the problem, with the 2 virtually identical functions: https://play.golang.org/p/pFg8yJwW2Hl

ntlm and wso2 api manager

Posted: 22 Sep 2021 09:10 AM PDT

I ask you to provide me with information on the operation of the ntlm protocol through the wso2 api manager. We are planning to use the wso2 api manager 3.2 product with the purchase of technical support. But for now, we are collecting information about the capabilities of the product. We have endpoints, their authorization works with the ntlm protocol. We are interested in whether the ntlm mechanism will work through wso2 api manager 3.2? Is this a working circuit? We also ask because our colleagues are having difficulties with such an implementation.

Javascript - chunk arrays for custom size

Posted: 22 Sep 2021 09:11 AM PDT

I have an array like:

var myArray = [[1, 2, 3, 4], [5, 6], [7, 8, 9], [10]];  

How I can reorder this array with the following rules:

  1. myArray[0][0] to reduce size to 2 elements (values 1,2 stay, 3,4 goes to next array)
  2. keep all values just move extra array elements to the next array, but all arrays need to keep the current number of elements except last

WHat I already try is:

function conditionalChunk(array, size, rules = {}) {    let copy = [...array],        output = [],        i = 0;      while (copy.length)      output.push( copy.splice(0, rules[i++] ?? size) )      return output  }      conditionalChunk(myArray, 3, {0:2});  

but in that case, I need to put rules for all arrays in the array, I need to know a number of elements for all arrays in the array, and that's what I want to avoid.

Is there any elegant way to do that?

How to extract a table to csv using Python from website without having table id

Posted: 22 Sep 2021 09:10 AM PDT

I am trying to make a csv in a daily basis from a specific website table: https://lunarcrush.com/exchanges

I've tried to use every single piece of advice on the related topics here (eg. How to extract tables from websites in Python , Python Extract Table from URL to csv , extract a html table data to csv file and many many more)

I thought that my initial problem was that I didn't have the table id (such as in other examples, I've only found the (table) class name MuiTable-root. But after a little more digging up I found out that whenever I was reading the url, the HTML code I was getting was completely different, rather than the one I see when I use Inspect(O) click on my browser.

I've tried almost everything I found here, so I am not sure if it helps to quote every singe code. As an example I just quote the following, that I was trying to make it work. The idea is simple (to find the tr part of the table and get the th (header) and td (data), and after that I'd extract them to a csv.

from lxml import etree  import urllib.request    web = urllib.request.urlopen("https://lunarcrush.com/exchanges")  s = web.read()    html = etree.HTML(s)    ## Get all 'tr'  tr_nodes = html.xpath('//table[@class="MuiTableHead-root"]/tr')    ## 'th' is inside first 'tr'  header = [i[0].text for i in tr_nodes[0].xpath("th")]    ## Get text from rest all 'tr'  td_content = [[td.text for td in tr.xpath('td')] for tr in tr_nodes[1:]]    print(td_content)  

Any ideas? I am sorry for my long (and maybe silly) question, I am just starting to use python, and there are still lots to learn!

Tackle the 'Not responding application outside of Microsoft Access' error in the calling Access VBA

Posted: 22 Sep 2021 09:11 AM PDT

I am using the ScriptControl in Access VBA to load the scripts (.vbs files) and execute them for extracting data from a SAP system. For the small data the code works fine.

However, when there is a big data which takes time or stops responding then Access opens a popup window asking me to switch to the app or retry. If I click on retry button or by hand switch to that window, then the script resumes!

Is there any way to tackle this access popup window or a code to press this retry button? Thanks

Mycode:

Open scriptPath For Input As #1      vbsCode = Input$(LOF(1), 1)      Close #1            On Error GoTo ERR_VBS            With CreateObject("ScriptControl")          .Language = "VBScript"          .AddCode vbsCode    '>>>>>>>>>>>>>>>> I get this popup window at this line        End With  

Access popup

Tried :

Sub Test()            Dim oSC As Object            Set oSC = CreateObjectx86("ScriptControl") ' create ActiveX via x86 mshta host      Debug.Print TypeName(oSC) ' ScriptControl      ' do some stuff            CreateObjectx86 Empty ' close mshta host window at the end        End Sub    Function CreateObjectx86(sProgID)           Static oWnd As Object      Dim bRunning As Boolean      Dim vbsCode As String, result As Variant, Script As Object            Open "\My Documents\\Desktop\x.vbs" For Input As #1      vbsCode = Input$(LOF(1), 1)      Close #1                         Set oWnd = CreateWindow()              oWnd.execScript vbsCode, "VBScript"  '>>>>>>>>>Gets an Error says "Error on Script page"              Set CreateObjectx86 = oWnd.CreateObjectx86(sProgID)             End Function    Function CreateWindow()        ' source http://forum.script-coding.com/viewtopic.php?pid=75356#p75356      Dim sSignature, oShellWnd, oProc            On Error Resume Next      Do Until Len(sSignature) = 32          sSignature = sSignature & Hex(Int(Rnd * 16))      Loop      CreateObject("WScript.Shell").Run "%systemroot%\syswow64\mshta.exe about:""<head><script>moveTo(-32000,-32000);document.title='x86Host'</script><hta:application showintaskbar=no /><object id='shell' classid='clsid:8856F961-340A-11D0-A96B-00C04FD705A2'><param name=RegisterAsBrowser value=1></object><script>shell.putproperty('" & sSignature & "',document.parentWindow);</script></head>""", 0, False      Do          For Each oShellWnd In CreateObject("Shell.Application").Windows              Set CreateWindow = oShellWnd.GetProperty(sSignature)              If Err.Number = 0 Then Exit Function              Err.Clear          Next      Loop        End Function  

Reaction Bot DM discord.py

Posted: 22 Sep 2021 09:10 AM PDT

How would I go about having a discord bot in python send a dm to a user when the user reacts to a message with a checkmark. Like, let's say I have my bot in python send a message and when the user reacts to it it will send a dm to that user with info.

Example image

This is the code I was able to build which I guess is how it would work obviously it's not python syntax. Thanks!

if user.reaction == ✅:        member.send("Nice to know you checked the message thanks")  

C Program just freeze when I use scanf in a loop

Posted: 22 Sep 2021 09:11 AM PDT

I am writing a simple algorithm for a question on coursera and while I start entering values through scanf(), my program is just freezing. It's not executing and even existing the loop. When it didn't work in my laptop, I tried it in an online compiler and it didn't work there also. I was facing the same problem with a similar algorithm question of Coursera.

P.S. The complete code was needed to answer the question.

    int main()      {          int distance;          scanf("%d", &distance);          int range;          scanf("%d", &range);          int pumps;          scanf("%d", &pumps);          int disPump[pumps];          for(int i = 0; i < pumps; i++){              scanf("%d", &disPump[i]);          }          //Program is never reaching this line and is just freezing          printf("Loop terminated.");           int minRefuel = calcRefuel(distance, range, disPump, pumps);      }    int calcRefuel(int distance, int range, int disPump[], int pumps){            // Array will be sorted here in ascending order using bubble sort.      for(int i = 0; i < pumps - 1; i++){          for(int j = 0; j < pumps - i - 1; j++){              if(disPump[j] > disPump[j+1]){                  int temp = disPump[j];                  disPump[j] = disPump[j+1];                  disPump[j+1] = temp;              }          }      }        // main algorithm starts here.      int distCovered = 0;      int refill = 0;      while(1){          int nearestPump = locatePump(range, disPump, pumps, distCovered);          distCovered += nearestPump;          refill++;          if((distCovered+range) >= distance){              break;          }      }      return refill;  }    int locatePump(int range, int disPump[], int pumps, int distCovered){      range += distCovered;      int i = 0;      // Doubt about while.      while(range >= disPump[i] && range < disPump[i+1]){          i++;      }      return disPump[i] - distCovered;  }  

Cannot access 'com.android.build.gradle.internal.dsl.Lockable' on Android Studio Arctic Fox | 2020.3.1 Canary 12

Posted: 22 Sep 2021 09:11 AM PDT

how are you doing?

Did you get this kind of error when writing a gradle plugin using kotlin DSL:

Cannot access 'com.android.build.gradle.internal.dsl.Lockable' which is a supertype of 'com.android.build.gradle.BaseExtension'. Check your module classpath for missing or conflicting dependencies  

Here is the complete code:

import org.gradle.api.Project  import com.android.build.gradle.BaseExtension  import org.gradle.kotlin.dsl.getByType    private typealias AndroidBaseExtension = BaseExtension    fun Project.configureAndroid() = this.extensions.getByType<AndroidBaseExtension>().run{      compileSdkVersion(30)  }  

Thanks in advance for your HELP.

AWS opswork cloud formation unable to import

Posted: 22 Sep 2021 09:10 AM PDT

I am trying to import the cloud formation template for a Opswork VPC as per the guide here: https://aws.amazon.com/blogs/aws/aws-opsworks-in-the-virtual-private-cloud/

I tried importing but it keeps telling me that

The following resource types are not supported for resource import: AWS::EC2::VPCGatewayAttachment,AWS::EC2::Route,AWS::EC2::SubnetRouteTableAssociation,AWS::EC2::NetworkAclEntry,AWS::EC2::NetworkAclEntry,AWS::EC2::NetworkAclEntry,AWS::EC2::NetworkAclEntry,AWS::EC2::NetworkAclEntry,AWS::EC2::NetworkAclEntry,AWS::EC2::SubnetNetworkAclAssociation,AWS::EC2::NetworkAclEntry,AWS::EC2::SubnetRouteTableAssociation,AWS::EC2::SubnetNetworkAclAssociation,AWS::EC2::Route  

enter image description here

Does anyone know why?

No comments:

Post a Comment