text:
Q: Multidimensional Key/Value Array into MySQL Table Alright, so I've never done this before. I am not a professional, but I know roughly how MySQL works. I know my way around PHP slightly better but still beginner stages. I also currently have a method in mind to go about it.
However, before I waste 2+ hours learning what I did wrong, I thought I'd ask here first how you guys would do it. Im starting with a (relatively) small array and working to big stuff when I get this understood well.
Array: http://pastebin.com/g8RyxtP5
So.. what would you do to get this into MySQL? Right now my initial thought is to make the table and its looking like this right now:
<?php
include "login.php";
include "createdb.php";

$con = mysqli_connect($mysql_host, $mysql_user, $mysql_pass, $mysql_table)
or die("Some error occurred during connection " . mysqli_error($con));

/*$sql = "CREATE TABLE Career (
ID int NOT NULL AUTO_INCREMENT PRIMARY KEY,
Username varchar(32),
Password varchar(32),
Battletag varchar(32),
Region varchar(2)
)
";*/

$sql = "CREATE TABLE career (
ID int NOT NULL AUTO_INCREMENT PRIMARY KEY,
battletag varchar(32),
lastHeroPlayed varchar(32),
lastUpdated varchar(32),
monsters varchar(32),
elites varchar(32),
hardcoreMonsters varchar(32),
barbarian varchar(32),
crusader varchar(32),
demon-hunter varchar(32),
monk varchar(32),
witch-doctor varchar(32),
wizard varchar(32),
paragonLevel varchar(32),
paragonLevelHardcore varchar(32),

h1name varchar(32),
h1id varchar(32),
h1level varchar(32),
h1hardcore varchar(32),
h1gender varchar(32),
h1dead varchar(32),
h1class varchar(32),
h1last-updated varchar(32),

h2name varchar(32),
h2id varchar(32),
h2level varchar(32),
h2hardcore varchar(32),
h2gender varchar(32),
h2dead varchar(32),
h2class varchar(32),
h2last-updated varchar(32),

h3name varchar(32),
h3id varchar(32),
h3level varchar(32),
h3hardcore varchar(32),
h3gender varchar(32),
h3dead varchar(32),
h3class varchar(32),
h3last-updated varchar(32),

h4name varchar(32),
h4id varchar(32),
h4level varchar(32),
h4hardcore varchar(32),
h4gender varchar(32),
h4dead varchar(32),
h4class varchar(32),
h4last-updated varchar(32),

h5name varchar(32),
h5id varchar(32),
h5level varchar(32),
h5hardcore varchar(32),
h5gender varchar(32),
h5dead varchar(32),
h5class varchar(32),
h5last-updated varchar(32),

h6name varchar(32),
h6id varchar(32),
h6level varchar(32),
h6hardcore varchar(32),
h6gender varchar(32),
h6dead varchar(32),
h6class varchar(32),
h6last-updated varchar(32),

h7name varchar(32),
h7id varchar(32),
h7level varchar(32),
h7hardcore varchar(32),
h7gender varchar(32),
h7dead varchar(32),
h7class varchar(32),
h7last-updated varchar(32),

h8name varchar(32),
h8id varchar(32),
h8level varchar(32),
h8hardcore varchar(32),
h8gender varchar(32),
h8dead varchar(32),
h8class varchar(32),
h8last-updated varchar(32),

h9name varchar(32),
h9id varchar(32),
h9level varchar(32),
h9hardcore varchar(32),
h9gender varchar(32),
h9dead varchar(32),
h9class varchar(32),
h9last-updated varchar(32),

h10name varchar(32),
h10id varchar(32),
h10level varchar(32),
h10hardcore varchar(32),
h10gender varchar(32),
h10dead varchar(32),
h10class varchar(32),
h10last-updated varchar(32),

h11name varchar(32),
h11id varchar(32),
h11level varchar(32),
h11hardcore varchar(32),
h11gender varchar(32),
h11dead varchar(32),
h11class varchar(32),
h11last-updated varchar(32),

h12name varchar(32),
h12id varchar(32),
h12level varchar(32),
h12hardcore varchar(32),
h12gender varchar(32),
h12dead varchar(32),
h12class varchar(32),
h12last-updated varchar(32),
";

if (mysqli_query($con,$sql)) {
   echo "TABLE 'Career' created successfully!
";
} else {
   echo "Error creating table: " . mysqli_error($con)."
";
}

mysqli_query($con, $sql);

After the table is created I was going to do some PHP/MySQL magic (basically learning as I go) to get the array->parse->push to mysql ?
Thanks for any insight.
What should I not be doing/how should I be going about this?
Edit: Okay I think maybe i can make one table still, and include the defining career var "battletag" into each hero separately (along with any vital info i need for each hero). I think that would work better than what I had.
$sql = "CREATE TABLE heros (
ID int NOT NULL AUTO_INCREMENT PRIMARY KEY,
battletag varchar(64) ,
name varchar(32),
id int,
level int,
hardcore bool,
gender bool,
dead bool,
class varchar(32),
last-updated TIMESTAMP
";

$sql2 = "CREATE TABLE career (
ID int NOT NULL AUTO_INCREMENT PRIMARY KEY,
battletag varchar(64),
lastHeroPlayed varchar(32),
lastUpdated TIMESTAMP,
monsters int,
elites int,
hardcoreMonsters int,
barbarian DOUBLE(4,3),
crusader DOUBLE(4,3),
demon-hunter DOUBLE(4,3),
monk DOUBLE(4,3),
witch-doctor DOUBLE(4,3),
wizard DOUBLE(4,3),
paragonLevel int,
paragonLevelHardcore int
";

A: From 1 to 12...
h12name varchar(32),
h12id varchar(32),
h12level varchar(32),
h12hardcore varchar(32),
h12gender varchar(32),
h12dead varchar(32),
h12class varchar(32),
h12last-updated varchar(32),

Below can be 1 column "GAME_NAME" so still you can add....
$sql = "CREATE TABLE career (
ID int NOT NULL AUTO_INCREMENT PRIMARY KEY,
battletag varchar(32),
lastHeroPlayed varchar(32),
lastUpdated varchar(32),
monsters varchar(32),
elites varchar(32),
hardcoreMonsters varchar(32),
barbarian varchar(32),
crusader varchar(32),
demon-hunter varchar(32),
monk varchar(32),
witch-doctor varchar(32),
wizard varchar(32),
paragonLevel varchar(32),
paragonLevelHardcore varchar(32),

I suggest so just create table like this...or you can create 2 join table 1 for game and one for hnn...
name_game varchar(150)
hname varchar(32),
hid varchar(32),
hlevel varchar(32),
hhardcore varchar(32),
hgender varchar(32),
hdead varchar(32),
hclass varchar(32),
hlast-updated varchar(32),

Redundant just put in 1 table..............


text:
Q: Converting a user input to ASCII to set motor speed for Arduino Motor speed needs to be between 0-225 but when I enter a number between 0-9 the correct values don't show up from the equation. Sometimes even negative numbers appear.
void setup() {
  Serial.begin(9600);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(6, OUTPUT);

  Serial.println("For DC motor, Enter F for Forward or R for Reverse");
  Serial.println("For DC motor, Enter 0-9 for speed");
}

void loop() {
  int command;
  command = Serial.read();
  updateMotor(command);
}

void updateMotor(int8_t command) {
  int8_t motorSpeed;
  if (command == 'F' || command == 'f') {
    Serial.println("You entered a direction of Forward");
    digitalWrite(7, HIGH);
    digitalWrite(8, LOW);
  } else if (command == 'R' || command == 'r') {
    Serial.println("You entered a direction of Reverse");
    digitalWrite(7, LOW);
    digitalWrite(8, HIGH);
  } else if (command >= '0' && command <= '9') {
    motorSpeed = (command - '0') * 255 / 9;
    analogWrite(6,motorSpeed);
    Serial.println("You entered a speed of: ");
    Serial.println(motorSpeed);
  }
}

I've tried everything I can think of. I'm new to this stuff so go easy on me.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Code only outputs a single row while trying to draw a rectangle void fyllRektangel(int hojd, int bredd);

    int main(){
        int hojd;       //Height
        int bredd;      //Width
        cin>>hojd;
        cin>>bredd;

        for(int r=1;r<=hojd;r+=1){
            for(int k=1;k<=bredd;k+=1)
                cout<<setw(4)<<"*";
            cout<<endl;

            return 0;
        }
    }

Why does my code only output a single row, but all the columns in my for loop? Im learning about patterns and the output is suppose to be of a rectangle where the width and height is input from the user.

A: your return 0 is inside the first for loop.
int main(){
        int hojd;       //Height
        int bredd;      //Width
        cin>>hojd;
        cin>>bredd;

        for(int r=1;r<=hojd;r+=1){
            for(int k=1;k<=bredd;k+=1)
                cout<<setw(4)<<"*";
            cout<<endl;
        }
       return 0;
    }


text:
Q: populating an array from a text file using fgets I have this program for class where we just need to show that we can read, write and populate an array from both a text and binary file. I didnt have many issued with the binary file but the text file is giving big time brain pains.
I believe this little bit of code is to blame. userInputText[MAXSIZE]is a char array (MAXSIZE is defined at 100000) and both textCount and textCounter are initialized to zero when the program is at this point.
textPointer = fopen("textFile.txt", "r");
if (textPointer)
{
    while (fgets(userInputText, sizeof(userInputText), textPointer) != NULL)
    {
        sscanf(userInputText, "%d", &textCount);
        userInputText[textCounter] = textCount;
        textCounter += 1;
    }
}

When the user first runs the program, this part of the program is skipped and the user is asked to create and write to a text file. The user inputs integers and they are written to a text file and stored in userInputText and displayed to the screen at the end of the program. All of that works fine, the text file is appended correctly every time the program runs. I have tried about every combo I can think of in the above piece of code. I have tried using fopen(r+), sizeof(int and MAXSIZE), experimenting with the %d. In my fprintf part later in the program I have "\n" set as a delimeter, but I have also tried removing it. I switched out the fgets for  fread. Ive gotten to the point where I'm resembling a baboon throwing poo at the problem.
I don't want people to think I am lazy and looking for an easy answer, mentally handicapped maybe but not lazy.
Any suggestions?
Thanks,
Mike

A: Try while( !feof(textPointer) )
     { fgets(userInputText,MAXSIZE,textPointer); }
sizeof(userInputText) will only return the size of a char pointer.


text:
Q: systemd-networkd-wait-online.service causing Artful to take over 2 minutes to boot, but Apport says package is not installed Symptons same on every release after 16.04.3.
At boot, system hangs on the Ubuntu screen with 4 flashing dots for over 2 minutes.
Ran systemd blame which indicated  systemd-networkd-wait-online.service took 1 minute and 38 seconds to run and NetworkManager-wait-online.service took 10 seconds to run.
Ran ubuntu-bug systemd-networkd-wait-online.service which returns that the bug cannot be reported because it concerns a package that is not installed.
Without Apport working, I am unsure how to file the bug on Launchpad.

A: Same problem here with Artful.
2min 52ms systemd-networkd-wait-online.service

As a workaround you can add a timeout for the service. To do that edit the file /lib/systemd/system/systemd-networkd-wait-online.service and adjust the line that starts the service:
ExecStart=/lib/systemd/systemd-networkd-wait-online --timeout 1

Setting the timeout to 1 doesn't seem to have any implications as there's another service with the exact same task (NetworkManager-wait-online.service).

A: Existing answers have suggested editing files in /lib in place or copying them to /etc. I recommend doing the following:
sudo systemctl edit --full systemd-networkd-wait-online.service

Then you can make modifications in the file, as described in the existing answers:
ExecStart=/lib/systemd/systemd-networkd-wait-online --timeout 1

This way systemd will take care of the files for you and it will survive upgrades. If you need to restore the default behavior you can delete the respective file in /etc/systemd/system/.

A: You can make ExecStart=/lib/systemd/systemd-networkd-wait-online --timeout 1 permanent by copying the modified systemd-networkd-wait-online.service file from /lib/systemd/system/ to /etc/systemd/system/ directory, using the following command.
sudo cp /lib/systemd/system/systemd-networkd-wait-online.service /etc/systemd/system/

A: Most people don't even need to wait for network to be up when booting. In this case you can simply disable the waiting:

*

*What does NetworkManager-wait-online.service do?
The above link explains what the service does and tells you how to disable it, as most users without an IT department would want to do.

A: You can create a directory /etc/systemd/system/systemd-networkd-wait-online.service.d/
and file /etc/systemd/system/systemd-networkd-wait-online.service.d/override.conf
with
[Service]
ExecStart=/lib/systemd/systemd-networkd-wait-online --timeout 1

A: The fastest solution I found:

systemctl mask systemd-networkd-wait-online.service

Q.E.D.


text:
Q: How do I set a default line size in plotnine? I've been using plotnine to plot in Python and I would like to set up a default line size for all plots. Unfortunately, changing line inside my custom theme only affects background elements.
In R using ggplot it is possible to run update_geom_defaults("line", list(size = desired size)) to get the desired behaviour. Is there such an alternative for plotnine?

A: I've finally found the solution to this. As indicated by the Plotnine API all geoms have an attribute called DEFAULT_AES containing the default values used for plotting. New default values can be set by changing the values of this dictionary. For instance, to set a new line size one can run:
import plotnine as p9
p9.geoms.geom_line.DEFAULT_AES['size']=desired_size


text:
Q: how to execute the javascript returned by AJAX response in the webpage (response = html+javascript) my buyresult.php page is working properly when i give give the url as buyresult.php?q=Mysore
but the in response i get after ajax call(both html and javascript is response).. the javascript is not working... how to solve it.. I'm new to web programming. Please HELP..
I've googled and got the result as to use
new Ajax.Updater(divID,URL,{asynchronous:true,evalScripts: true});

but i don't know where to put this function
my index.php file is as follows :

Enter City :<input class="w-input" id="city" type="text" placeholder="Enter the city name (required)" name="city" data-name="city" required="required" onchange="showUser(this.value)">

Results will be displayed Here...


text:
Q: WiFi getRssi stops working when the screen is off I am creating an app that has a background service which continuously gets the WiFi RSSI using the getRssi() method and decides what it should do depending on the value.
The service is running OK, however, when the screen is locked the service stops updating the value of RSSI, instead, it gets stuck with the last value read before locking the screen.
I tried holding a partial WakeLock but unfortunately it has no effect.
In the OnStartCommand of the service I added the wake lock as follows :
wifi =(WifiManager)getApplicationContext().getSystemService(WIFI_SERVICE);
    PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
            PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"MyLock");
            wakeLock.acquire();
info = wifi.getConnectionInfo();
            RSSI = info.getRssi();
            System.out.println(RSSI);

I added the Wake Lock permission to the manifest :
<uses-permission android:name="android.permission.WAKE_LOCK" />

Have anyone had a similar problem?
What is the reason behind this?


text:
Q: Symfony2 configuration setting for custom parameters in config.yml I want to use parameters.yml for parameters, but top level name something like data in place of parameters. For this I did following things:
In composer.json in the root directory:
"extra": {
    "symfony-app-dir": "app",
    "symfony-web-dir": "web",
    "incenteev-parameters":
    {
        "file": "app/config/parameters.yml",
        "parameter-key": "data"
    }
}

In parameters.yml and parmeters.yml.dist like this:
data:
    database_driver: pdo_mysql

But still when I am running command php composer.phar update, I get an error:
  [Symfony\Component\Config\Exception\FileLoaderLoadException]
  Cannot import resource "D:\xampp\htdocs\symfony_two\app/config\parameters.y
  ml" from "D:\xampp\htdocs\symfony_two\app/config\config.yml". (There is no
  extension able to load the configuration for "data" (in D:\xampp\htdocs\s
  ymfony_two\app/config\parameters.yml). Looked for namespace "config", found
  "framework", "security", "twig", "monolog", "swiftmailer", "assetic", "doc
  trine", "sensio_framework_extra", "forma_test", "custom_customer", "acme_de
  mo", "web_profiler", "sensio_distribution")

I am not getting. Am I missing something for defining data somewhere?


text:
Q: Scaling a WP eCommerce site Related to this question.
Any recommendation on tools, plugins for optimizing a large eCommerce site on WP.  Currently hitting 1000 items and 5000 more items coming.  It seems the optimizations would be different than a standard blog serving thousands of users.  The number of stores being developed on WP is increasing and putting a package of optimizations together would appear helpful.
MM/RC

A: I've developed a 55k product ecommerce site using Wordpress with the Shopp plugin and can share what I've done to MySQL to eke out better performance, YMMV and some (or all) of these may not apply to your situation.
Determine how much you need to increase buffers/caches by by looking at the output from a "show status" sql command - there are tools which pretty up this output which may be useful, I often just use phpmyadmin to get an idea.  http://blog.mysqltuner.com/ is a handy resource and utility too.
Make sure your query cache is on and that it's large enough to have a very low low memory punes number.  Make sure your the number of key reads is not too high (this being a relative value), increasing key_buffer_size can help with that.  Make sure that the number of temporary tables being created is low, reduce that number by increasing tmp_table_size.
Turn on the slow query log and log slow queries, re-run those queries manually with explain statements, add indexes change column types, etc, as needed.  For one query we were getting insane explain statements (as in comparing many, many more rows than it "should" have been), upgrading to a newer version of MySQL caused that same query to be much better optimized (and much quicker) by MySQL itself.
If you're using full-text indexing I don't believe InnoDB tables are an option - just don't update products during your busy times.  If your ecommerce package supports it you can minimize customer disruption (performance or otherwise) by making changes on your staging server and then moving over just the product tables with a dump from stage and loading onto production - this will not work without some additional work for the rest of your Wordpress installation however.
If your site design and UX can support it guiding the users into a "browsing" mode vs. a "searching" mode (eg: clicking around a site vs typing searches into the search box) can help you take advantage of some very easy database level and Wordpress level caching.
Pre-load your caches - easy caching like query caches and Wordpress-level caching can also be pre-loaded by spidering your site with wget.  You can also pre-load the cache for searches by using user search behavior (via your logs) and re-getting those requests when you need to fill the caches.

A: I was curious about my own comment and have been doing some reading, here is where I am at.
First off, I would give W3 Total Cache a try. Also, install APC PHP extension on your server and set W3 Total Cache to use it. It will use APC to cache Database objects, PHP, even help minify your CSS and JS. It might provide enough. Especially if you incorporate some MySQL cache already. W3 Total Cache also can work with Memcache as a caching backend.
For the Database, caches the queries is very useful. I found this link and he explains how he did somethings for his MU blog. To Quote:

The Query Cache is a nifty little feature in MySQL, where it stores — in a dedicated are within main memory — any results of a query for a table which has not recently changes.
That is, assuming a request comes in to retrieve a specific row in a table — and that table has not recently been modified in any way — and the cache has not filled up requiring purging/cleaning — the query/data can be satisfied from this cache. The major benefit here of course is the to satisfy the request — the database does not need to go to the disk (which is generally the slowest part of the system) and can be immediately satisfied.

So this is pretty cool, and will help a lot since the products themselves won't be changing much. Another thing the article mentions is to make sure you have lot so memory to hold the database in Ram, this will help the speed the queries dramatically.
He also talks about the table types, and using MyISAM over InnoDB for the mostly read-only tables, while this he reasoning is a bit MU oriented, it could be useful.
In regards to setting up the indexes. If you have a lot of them, they can slow down the inserts, and take up more disk space. But as I don't imagine a large amount of products being added on a regular basis, I think this is acceptable. And with disk space being cheap ...


text:
Q: React Native Error undefined is not an object (evaluating 'navigator.userAgent.indexOf') We're getting this problem when creating an application with react-native init.
The error is "undefined is not an object (evaluating 'navigator.userAgent.indexOf')"  When we do remote debugging in the browser, this doesn't happen. It runs fine in that situation.
Also when we build it out as a standalone APK, the app immediately crashed.


text:
Q: linux-tools dependency problem After upgrading from Ubuntu 16.04 to 18.04, I get the following dependency problem:
Preparing to unpack .../linux-tools-4.15.0-34_4.15.0-34.37_amd64.deb ...
Unpacking linux-tools-4.15.0-34 (4.15.0-34.37) ...
dpkg: error processing archive /var/cache/apt/archives/linux-tools-4.15.0-34_4.15.0-34.37_amd64.deb (--unpack):
 trying to overwrite '/usr/lib/libcpupower.so.4.15.0-34', which is also in package linux-hwe-tools-4.15.0-34 4.15.0-34.37~16.04.1
dpkg-deb: error: paste subprocess was killed by signal (Broken pipe)
Errors were encountered while processing:
 /var/cache/apt/archives/linux-tools-4.15.0-34_4.15.0-34.37_amd64.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)

Any ideas how to fix this?

A: The package linux-hwe-tools-4.15.0-34 is a leftover from 16.04 and should be removed (sudo apt remove linux-hwe-tools-4.15.0-34).


text:
Q: SF Connector with Apps Script I have connected my gsheet to SF using the Data connector for Salesforce and have imported a report.
Is there a way to refresh this report using Apps Script? Or even import another report?

A: The Data connector for Salesforce has an option to automatically refresh the data in your sheets (see image below). I think this answers what you're looking for.
Salesforce data connector
If you want to build sales tools in a spreadsheet (find leads, automate reporting, etc) you might want to check rows.com . We combine a spreadsheet editor with built-in integrations and automation (Salesforce, Linkedin, Crunchbase, ...), all using formulas, without code.
Here's our integration with Salesforce
https://rows.com/integrations/salesforce


text:
Q: Getting list of questions that has not been shown or answered I have two tables :
Question table where contains :

And then I have another table that is called
UserAnswerQuestion that contains :

That has reference to the question via question_id
The thing is that every time user answers a question I create a row in db saying :
question_id user_id has answered it and then I check if the answer is correct or not, if it's correct I put passed as a True, otherwise I put passed as a false.
Ok, from now is all ok, the thing that I can not get is I'm creating a method that returns to me the nextQuestion not answered, but I'm not able to do this method correctly.
What I'd like is to have a query that first return all questions that user have not answered yet, and then another query that returns just a question that user has not answered yet.
Note: This shown attribute was added because I want first to iterate over other questions instead of showing the ones that user has failed recently.
Is the question clear?
What I've tried?
I've tried to get the questions List<UserAnswerQuestion> findAllByUserEmailAndPassedFalseAndShownFalse(String email); but it doesn't work because with this table I can know every answer in every try that user does, so for example if I have a question that have 4 answers and 1 correct, this table can contain 4 row with the same question_question_id because the user perhaps has failed 3 times and then at the fourth it answers correctly.
Edit
I have already the questions that user can answer with this method :
public List<Question> getAllQuestionsThatUserCanAnswer(String email, Long topic){
        List<Question> mList = this.questionRepository.findAllByTopicParentId(topic);
        if(mList==null) return null;
        List<UserAnswerQuestion> userAnswerQuestionList = this.userAnswerQuestionRepository.findAllByUserEmail(email);

        for (UserAnswerQuestion userAnswerQuestion : userAnswerQuestionList) {
            if(mList.contains(userAnswerQuestion.getQuestion())){
                if(userAnswerQuestion.getPassed()){
                    mList.remove(userAnswerQuestion.getQuestion());
                }
            }
        }
        return mList;
    }

Now I'm trying to do the getNext of this method but I do not know how to iterate over it.

A: Focus on SQL query that solve your problem
select * from Question q
left join Answer a on q.id = a.question_id
where a.id is null OR (a.passed != 'true' AND a.user_id = 1)
order by a.passed

Check scratch here


text:
Q: Upload files from android app to my S3 bucket I'm pretty confused about what method should I use. OK here's what I'm actually trying to do:

*

*User registers with my app need to upload multiple files/images

*These files/images need to be uploaded to my s3 bucket

Uploading these files using presigned URL seems to be out of the question since I need to upload multiple files/images and it seems presigned URL is only good for a single file.1
I then look at AWS SDK for Java 2.0, and this seems what I need; however, when I read the [setup credentials][1] I become confused because:

*

*It seems this will use the credentials setup in our OS environment. So how will my app use these credentials later when it's installed in other users' devices?

*I have multiple AWS credentials profile in my OS. I'm still unclear on how to actually load my credentials profile, as it's not the default profile

So upon further reading the link, it seems supply credentials explicitly with
AwsSessionCredentials awsCreds = AwsSessionCredentials.create(
    "your_access_key_id_here",
    "your_secret_key_id_here",
    "your_session_token_here");

should fit me the best. But if I put my access_key_id, secret_key_id in my app's strings.xml file, wouldn't it be a security issue?
1 FYI I have successfully implemented upload single image using presigned URL for another activity. I use retrofit which connects to my lambda function which then returns the presigned URL, and made another retrofit PUT request to the presigned URL


text:
Q: limit $\lim_\limits{x\to\infty} f(x)=x^a\left(1-\frac {0.1\prod_{t=1}^x(1-y(t))}{10}\right)^{x-a} $ How can we solve the following limit. Also, is f(x) monotonically increasing/decreasing.
$$\lim_\limits{x\to\infty} f(x)=x^a\left(1-\frac {0.1\prod_{t=1}^x(1-y(t))}{10}\right)^{x-a} $$
where $a\in Z^+$ is constant, and $x\in Z^+$. $0<y(t)<1$ and $\{y(t)\}$ is a none increasing sequence of numbers with the limit value of 0.
Also, if the behavior of f(x) depends on the sequence $\{y(t)\}$ , what conditions should $\{y(t)\}$  possess to guarantee convergence of f(x) to 0.

A: Set
$$z_n=c\prod_{i=1}^n(1-y_i)\tag1$$
Here $c=0.01$. We're interested in the asymptotic behavior of
$$f(n)=n^a(1-z_n)^n(1-z_n)^{-a}$$
From the information we have about $(y_n)$, we can deduce that $(z_n)$ is a strictly decreasing positive sequence. Thus the factor $(1-z_n)^{-a}$ converges to some limit between $0$ and $1$, so for our purposes this is basically equivalent to the study of
$$f(n)=n^a(1-z_n)^n$$
In general not much can be said about such a sequence. Of course if $z_n$ does not converge to $1$, the geometric factor crushes the polynomial factor $n^a$ and $f(n)\to 0$. But when $z_n\to 1$, the behavior of $f(n)$ has to do with how fast that convergence is. If $z_n$ goes to $1$ quickly enough, then it "beats" the power of $n$ and $(1-z_n)^n$ does not converge to $0$, so $f(n)\to+\infty$. If $z_n$ goes to $1$ more slowly, then $(1-z_n)^n$ converges to $0$, and if this converges is itself sufficiently fast, it may dominate the polynomial factor and we'll have $f(n)$ bounded or maybe even $f(n)\to 0$.
Of course, we're not working in the fully general case: we have a formula for $z_n$. But how much information does this formula really give us? How does the information we have about $(y_n)$ restrict which sequences $(z_n)$ can be? We can express $y_n$ in terms of $z_n$ like so:
$$y_n=1-\frac{z_n}{z_{n-1}}\tag2$$
We know that $0<y_n<1$, that $(y_n)$ is non-increasing and converges to $0$, therefore the same is true of the right hand side of the equation. In fact, the two conditions (1) and (2) are equivalent if we take $c=1-z_1$. This means that as long as we choose $(z_n)$ so that the right hand side of (2) is non-increasing, contained in $(0, 1)$ and converging to $0$, then we can set $y_n$ according to (2) and we will have (1). This allows us to forget about the sequence $(y_n)$ and forget about infinite products, and focus on the (I think) simpler problem:

Consider
  $$f(n)=n^a(1-z_n)^n$$
  for $a$ a positive integer. If we know that the successive ratios $\frac{z_n}{z_{n-1}}$ are in $(0, 1)$, non-decreasing and converge to $1$, what can we say about the asymptotic behavior of $f(n)$?

The condition on the successive ratios of $(z_n)$ is basically a slowness condition: if $z_n$ converges to $1$, it does so "slowly", so we have reason to hope we can show $f(n)$ is bounded.
Unfortunately, it turns out that that hope is in vain. If we set $z_n=\frac1n$, it satisfies our slowness condition, and yet $f(n)\to+\infty$.
We need more information about $(y_n)$.


text:
Q: shared array with mmap is not visible between different processes I'm trying to write an implementation of malloc and free and a shared stack (that gets commands to push pop and top from clients connecting to server).
For some reason when I open 2 clients the memory of the stack is not visible to both of them. (top of the stack is different).
I'll mention that when I implemented this exercise with threads and sbrk it worked perfectly so I suspect it has something to do with how I use the mmap function.
This is the malloc function:

#include<stddef.h>
# include "funcs.hpp"
#include <sys/mman.h>
#include <stdlib.h>

char* memory= (char*)mmap(NULL, sizeof(char)*40000, PROT_READ|PROT_WRITE , MAP_SHARED | MAP_ANONYMOUS, -1, 0);
struct block* mata_data_list=(struct block*)memory;
void initialize(){
    mata_data_list->size= 40000 - sizeof(struct block);
    mata_data_list->is_available=1;
    mata_data_list->next_meta_data=NULL;
}

void split(struct block *old, size_t size){
    struct block *new_block=(struct block*)((int*)old + size + sizeof(struct block));
    new_block->size= (old->size) - size - sizeof(struct block);
    new_block->is_available=1;
    new_block->next_meta_data=old->next_meta_data;
    old->size=size;
    old->is_available=0;
    old->next_meta_data=new_block;
}

void *malloc(size_t number_of_bytes){
    struct block *curr;
    void *result;
    if(!(mata_data_list->size)){
        initialize();
    }
    curr=mata_data_list;
    while((((curr->size) < number_of_bytes) || ((curr->is_available) == 0)) && (curr->next_meta_data != NULL)){
        curr=curr->next_meta_data;
    }
    if((curr->size) == number_of_bytes){
        curr->is_available=0;
        result=(void*)(++curr);
        return result;
    }
    else if((curr->size)>(number_of_bytes + sizeof(struct block))){
        split(curr, number_of_bytes);
        result=(void*)(++curr);
        return result;
    }
    else{
        result=NULL;
        return result;
    }
}

void merge(){
    struct block *curr;
    curr=mata_data_list;
    while((curr->next_meta_data) != NULL){
        if((curr->is_available) && (curr->next_meta_data->is_available)){
            curr->size+= (curr->next_meta_data->size) + sizeof(struct block);
            curr->next_meta_data=curr->next_meta_data->next_meta_data;
        }
        curr=curr->next_meta_data;
    }
}

void free(void* ptr) throw(){
    if(((void*)memory<=ptr)&&(ptr<=(void*)(memory+40000))){
        struct block* curr=(struct block*)ptr;
        --curr;
        curr->is_available=1;
        merge();
    }
}

void *calloc(size_t nitems, size_t size){
    void* ptr = malloc(nitems*size);
    memset(ptr, 0, nitems*size);
    return ptr;
}

This is the relevant server code:
if (!fork()) { // this is the child process
            int pid = getpid();
            handle_stack(pid, new_fd);
        }


text:
Q: Javascript: Check if Element has Changed I want to know, if it's possible, how to check in javascript if an element has changed or an attribute of it?
I mean something like window.onhashchange for an element something like:
document.getElementById("element").onElementChange = function();

As I know onchange is something like this, but will it work if I want to know in this way:
var element = {};
element.attribute = result;

element.attribute.onchange = function();

A: As far as I understand you want onChange on javascript object Properties. The answer is no, it doesn't exist as far as I know.
But you can make a setter function like this (As a proof of concept):
var element = {};

element.setProperty = function(property, value) {
  if (typeof(element.onChange) === 'function') {
    element.onChange(property, element[property], value);
  }

  element[property] = value;
};

element.onChange = function(property, oldValue, newValue) {
  alert(property + ' changed from ' + oldValue + ' to ' + newValue);
};

element.setProperty('something', 'Hello world!');

now you get an alert box with 'something changed from undefined to Hello World!'. And (element.something === 'Hello World!') will return true.
if you now call:
element.setProperty('something', 'Goodbye world!');

you get an alert box with 'something changed from Hello World! to Goodbye World!'.
Off course you have to set the property only via the setProperty method in all of your code if you want to capture this event!
Edit:
At some time in the future, you might be able to use Object.observe().
Edit 2:
Now there's also proxies.

A: You might consider a mutation observer.
to do this you first create a callback (fired when the dom element changes)
assign it to an observer var observer = new MutationObserver(callback);
Then tell the observer what to watch observer.observe('

', observerOptions);
From:
Mozilla page on Mutation Observers

A: I guess you'd need a way to capture the event which triggered the change in attribute rather than the change in attribute. The change in attribute could only either be due to your CSS or your javascript, both being manifestations of the user's actions.

A: I believe there is no such event. However, you can use setInterval or setTimeout to watch for element changes and use it to react accordingly.

A: I did this.  It works pretty well. I would have used the setProperty method if I had known.
function searchArray(searchValue, theArray, ChangeValue){
    for (var i=0; i < theArray.length; i++) {
        if (theArray[i].id === searchValue) {
            theArray[i].changed = ChangeValue;
        }
    }
}

function getArrayIindex(elementid, theArray){
    for (var i=0; i < theArray.length; i++) {
        if (theArray[i].id === elementid) {
            return i;
        }
    }
}

function setInputEvents(hiddenObject) {

        var element;

        for (var i = 0; i < document.forms[0].length; i++) {
            element = document.forms[0].elements[i];

            //Check to see if the element is of type input
            if (element.type in { text: 1, password: 1, textarea: 1 }) {

                arrFieldList.push({
                    id: element.id,
                    changed:false,
                    index: i,
                });

                element.onfocus = function () {
                    if (!arrFieldList[getArrayIindex(this.id, arrFieldList)].changed) {
                        hiddenObject.value = this.value;
                        this.value = '';
                    }
                }

                element.onblur = function () {
                    if (this.value == '') {
                        this.value = hiddenObject.value;
                    }
                }

                element.onchange = function () {
                    searchArray(this.id, arrFieldList, true);
                }
            }

        }


text:
Q: SSH Connection Limitations I have a network of 100 machines, all with ubuntu Linux.
Is there a limit to the number of machines that can connect to one single machine (at the same time)?
For example, can I have 99 of my machines maintain continuous ssh connection to the 100th machine? Can I have every one of my machines (every one of the 100) maintain a continuous ssh connection to all other 99 machines?
How much memory does each such a connection take?

A: The number of total connections is limited mostly by the number of ports they can come in on, and the capability of the system. There are configuration options (Max_Sessions and Max_Startup) but they only apply to the number of connections FROM a single IP, and the number of concurrent requested startup connections...Basically they're DDOS protection.
There is no easy way to tell how much memory a connection is going to use: it is entirely dependent on the amount of traffic. One extremely heavily utilized connection can use more resources than 10,000 connections that are doing nothing.
All that being said, it's almost always going to be a better idea to have the connections established when they're needed, and closed when they're not.

A: I think you can.  I routinely have 3 or so on my home box, and at my office we can have up to 10.  It only really depends on what your computer can handle.
There are settings in sshd_config that you may have to change.  Here's a link to the man page.  It is found in /etc/ssh/sshd_config. Default is 10. You'll need to increase this.
I found this resource that talked about how to increase the maximum.  Here's a little explanation:

*

*/proc/sys/net/core/somaxconn- maximum TCP connections (SSH connects over TCP)

*/proc/sys/net/core/netdev_max_backlog- not as big of a deal, this is the max packet queue

You can just edit these numbers if you need to increase it.  My default somaxconn is 128, so you should be good.
EDIT:
Other options
Use websockets with NodeJS.

*

*For the client

*For the server
This should get you started.  If you don't want to learn how to use websockets, just send HTTP Post requests to a webserver.  They don't have too much overhead and you can send a lot of data this way.  I would personally opt for the websockets because they're real-time and are not too difficult to set up.


text:
Q: Understanding Kubernetes networking and public/private addressing I'm trying to set up a Kubernetes cluster for production (with kubeadm) on a private cloud (IONOS Cloud). I've been trying to figure it all out and configure it as best as possible for a few weeks now. Still there is one thing I don't quite understand or see if it is possible.
The initial cluster would be 5 nodes, 3 masters and 2 workers. The master servers with a load balancer and the workers with another load balancer. Each server has 2 interfaces, one for the public network and one for the private network (192.168.3.0/24). Each server has a firewall that by default blocks all packets.
In order not to have to create firewall rules on each server, so that they can see each other over the public network, I would like any kind of communication between Kubernetes nodes to be over the private network.
I can think of other reasons to use the private network for inter-node communication, such as: speed, latency, security...
However, I have not been able to configure it and I don't know if it is really possible to create this scenario. The problems I encounter are the following:

*

*In order to access the API (e.g. kubectl) of the cluster from outside I need to expose the control-plane endpoint with the public IP of the balancer. If I do this, then the database endpoints etcd are exposed on the public network. Then, the other nodes, in the process of joining the cluster (kubeadm join) need to get some information from the databases etcd, therefore, they necessarily need visibility over the public network between them.

*Once all the nodes are joined, the "kubernetes" service has the endpoints of all the control-plane endpoints (public). When I try to deploy Calico (or another CNI) they never finish deploying because they make queries to the kubernetes service, and if they don't have visibility between them, it fails.

It seems that whatever I do, if I publish the API on the public network, I need all the nodes to see each other over the public network.
Maybe I'm making my life too complicated, and the simplest thing to do is to open a firewall rule for each node, but I don't know if this is a good practice.
Architecture diagram (I still cannot embed images)


text:
Q: React component doesn't update When I change the data file where I have stored my array of data, component where that data is being displayed doesn't change. I have tried to filter the original data and get only the selected values and it worked well but the display hasn't changed even after the data was changed.
Here are the code of key components and a screenshot
Single item component:
function Item() {
  let [data, setData] = useContext(DataContext);

  let Array = data.map((item) => {
    return (

{item.name}

{item.desc}

{item.price}

        <Link to={`/product/${item.path}`}>

See details

        </Link>

    );
  });

  return <>{Array}</>;
}

Data component:
export let DataContext = createContext();

export let DataProvider = (props) => {
  let [data, setData] = useState([
    {
      name: "Toshiba",
      desc: "Laptop copmuter",
      price: 299,
      url:
        "https://images.pexels.com/photos/3975677/pexels-photo-3975677.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
      path: "Toshiba",
      type: "laptop",
      details:
        "Some words just to fill this space Some words just to fill this space Some words just to fill this space Some words just to fill this space Some words just to fill this space Some words just to fill this space Some words just to fill this space Some words just to fill this space",
    },
    {
      name: "Lenovo",
      desc: "Laptop copmuter",
      price: 399,
      url:
        "https://images.pexels.com/photos/3975677/pexels-photo-3975677.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
      path: "Lenovo",
      type: "laptop",
      details:
        "Some words just to fill this space Some words just to fill this space Some words just to fill this space Some words just to fill this spaceSome words just to fill this space Some words just to fill this space Some words just to fill this space Some words just to fill this space",
    },
    {
      name: "Asus",
      desc: "Laptop copmuter",
      price: 199,
      url:
        "https://images.pexels.com/photos/3975677/pexels-photo-3975677.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
      path: "Asus",
      type: "laptop",
      details:
        "Some words just to fill this space Some words just to fill this space Some words just to fill this space Some words just to fill this space Some words just to fill this space Some words just to fill this space Some words just to fill this space Some words just to fill this space",
    },
    {
      name: "HP",
      desc: "Laptop copmuter",
      price: 299,
      type: "laptop",
      url:
        "https://images.pexels.com/photos/3975677/pexels-photo-3975677.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
      path: "HP",
      details:
        "Some words just to fill this space Some words just to fill this space Some words just to fill this space Some words just to fill this space Some words just to fill this space Some words just to fill this space  Some words just to fill this space Some words just to fill this space Some words just to fill this space Some words just to fill this space ",
    },
    {
      name: "Apple",
      desc: "Laptop copmuter",
      price: 299,
      type: "laptop",
      url:
        "https://images.pexels.com/photos/3975677/pexels-photo-3975677.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
      path: "Apple",
      details:
        "Some words just to fill this space Some words just to fill this space Some words just to fill this space Some words just to fill this spaceSome words just to fill this space Some words just to fill this space Some words just to fill this space Some words just to fill this space",
    },
    {
      name: "Apple",
      desc: "Android",
      price: 299,
      type: "mobile",
      url:
        "https://images.pexels.com/photos/3975677/pexels-photo-3975677.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
      path: "Apple",
      details:
        "Some words just to fill this space Some words just to fill this space Some words just to fill this space Some words just to fill this spaceSome words just to fill this space Some words just to fill this space Some words just to fill this space Some words just to fill this space",
    },
  ]);

  return (
    <DataContext.Provider value={[data, setData]}>
      {props.children}
    </DataContext.Provider>
  );
};

Shop component:
function Shop() {
  let [data, setData] = useContext(DataContext);
  function mobileClick(e) {
    setData((prev) =>
      prev.filter((item) => {
        if (item.type === e.target.id) {
          return true;
        }
      })
    );
    console.log(data);
  }
  return (

Filter

        <form>

            Mobile
            <input type="checkbox" id="mobile" onClick={mobileClick} />

            Laptop
            <input type="checkbox" id="laptop" />

            PC
            <input type="checkbox" id="PC" />

            Touchpad
            <input type="checkbox" id="Touchpad" />

        </form>

        <DataProvider>
          <Item />
        </DataProvider>

  );
}

A: Sorry for the previous wrong answer so i edited this one.
Your issue is you are accessing the state outside of the Provider.
As you will need to wrap the Shop Component with the Provider first and then you will have to access the state inside it.
function App(){
  return (
    <Provider>
      <Shop />
    </Provider>
  )
}

function Shop(){
  const [state, setState] = useContext(defaultState);
  return (
     // YOUR REST JSX HERE...
  )
}

A: Remove the additional DataProvider for Item. You already would have provided one in wrapping your whole app. Currently your Item is not receiving the updated data from that one instead it must be receiving the unchanged one from it's nearest DataProvider.
Shop should simply be :-
function Shop() {
  let [data, setData] = useContext(DataContext);
  function mobileClick(e) {
    setData((prev) =>
      prev.filter((item) => {
        if (item.type === e.target.id) {
          return true;
        }
      })
    );
    console.log(data);
  }
  return (

Filter

        <form>

            Mobile
            <input type="checkbox" id="mobile" onClick={mobileClick} />

            Laptop
            <input type="checkbox" id="laptop" />

            PC
            <input type="checkbox" id="PC" />

            Touchpad
            <input type="checkbox" id="Touchpad" />

        </form>

          <Item />

  );
}

Here is a codesandbox to see it (don't mind the css)

Note :- : Also currently selecting mobile would set your state to the filtered array permanently which will not allow you to apply any further filters on the original array successfully. You would always need to maintain a copy of original array for filteration purposes.


text:
Q: Pull subsequent values So let's say I have the following table

 Employee_ID Supervisor_ID
 001         123
 178         123
 002         178
 154         178
 003         154
 004         201

I'm attempting to pull all employees that fall under the supervision of Supervisor_ID 123 along with all other supervisors within that branch (ie 178, 158) so it would spit out the following employees 001, 178, 002, 154, 003. How would I achieve this ? My apologies for the lack of wording in the title.

A: We can use a recursive hierarchical query here:
WITH cte AS (
    SELECT Employee_ID, Supervisor_ID
    FROM yourTable
    WHERE Employee_ID = 123
    UNION ALL
    SELECT t1.Employee_ID, t1.Supervisor_ID
    FROM yourTable t1
    INNER JOIN cte t2
        ON t2.Employee_ID = t1.Supervisor_ID
)

SELECT Employee_ID
FROM cte
WHERE Employee_ID <> '123'
ORDER BY Employee_ID;

Demo
Note that your sample table seems to be lacking an actual record where employee 123 appears as an employee.  My query above assumes that such a record would be present.


text:
Q: Get SKPhysicsBody to update as textures are animated (Swift) So I've got an 'SKSpriteNode(texture: someTexture)' object that I run an 'SKAction' on which animates it (walking animation) with a couple of textures.
I set it's physicsBody using the texture parameter so that the physicsBody would be a perfect outline of my character, only thing is I can't quite figure out how to get the physicsBody to change as the texture changes (due to the animation).
I tried the obviously wrong choice of assigning the object a new SKPhysicsBody (in update method) with texture of object.texture (for current texture in animation), but that doesn't retain all the other properties I originally set. I searched for methods in the documentation for someway I could achieve this but found nothing.
What would be the best way to go about this?

A: Normally you would design your game such that the same physics shape applies to all animation frames. It often does not matter at all whether a human character's limbs are all properly outlined in the shape, generally a rectangle often suffices.
Your approach was correct btw, you would have to create a new physics body every time and you would have to copy over the properties of the previous body before you replace it with a new one. However that is not a good solution anyway because the internal state of the body can't be preserved, and different shapes will not case the now-animating physics shapes to have proper physics behavior. For example if the character is swinging a bat, hitting the ball, it would basically just move the ball away from the bat but not apply any force from the swinging motion.
In essence what you are trying to achieve is not (really) possible. Instead give the node a shape that is a good compromise over all animation frames. Typically it's best to use the smallest possible shape. Alternatively you could compose the character of multiple sprites to be able to compose it of multiple (connected) bodies.


text:
Q: Convert NOAA JSON value to data frame in python From NOAA API, I can get Boston hourly weather forecast information via JSON file. Here is the link: https://api.weather.gov/gridpoints/BOX/70,76
(This JSON file is too long to present comprehensively here, please kindly click the link to see it)
I want to convert some of the weather variables into data frame to proceed further calculation.
The expected format is as below for temperature. I will use the same format to get precipitation, snowfall, humidity, etc.
expected dataframe format
Now I cannot figure out how to convert it to the dataframe I want. Please kindly help....
For now, here is the best I can do, but still cannot extract validTime and values from Temperature
    import requests
    import pandas as pd
    response = requests.get("https://api.weather.gov/gridpoints/BOX/70,76")
    # create new variable forecast
    forecast=response.json()
    df1 = pd.DataFrame.from_records(forecast['properties']).reset_index()
    df2=df1.loc[ :1 , ['temperature','quantitativePrecipitation', 'snowfallAmount', 'relativeHumidity',  'windGust', 'windSpeed', 'visibility']]
    df2

current output


text:
Q: How to get the error causing rows in try and except using python? I am new to python. I am looking for a way to get the error causing rows into a new data frame. So, I have a data frame from where I want to check if a date column is in a particular date format or not. Though I have written the code and getting the output correct, I want to get the error causing rows into a new data frame. How do I do it?
My code:
df =

   Date         cars
0  2020-01-02   two
1  01-02-2020   three
3  01022020     four
4  080920201    five

import dateutil.parser

for row in df.Date:
    try:
        valid = dateutil.parser.parse(row)
        print(valid)
    except ValueError:
        invaild = "error caused row"
        print(invalid)

Execpted output:
    valid
    0  2020-01-02  00:00:00
    1  2020-01-02  00:00:00
    3  2020-01-02  00:00:00
 Invaild

4  080920201    five

A: To print something different, depending on whether a row was valid, print it either in the try clause or in the except clause:
for row in df.Date:
    try:
        valid = dateutil.parser.parse(row)
        print(row, "was a valid row")
    except ValueError:
        print(row, "caused an error")

Or to collect all rows causing an error in a list, call the list append method inside the except clause:
invalid_rows = []
for row in df.Date:
    try:
        valid = dateutil.parser.parse(row)
    except ValueError:
        invalid_rows.append(row)

See https://docs.python.org/3/tutorial/errors.html#handling-exceptions:

The try statement works as follows.

*

*First, the try clause (the statement(s) between the try and except keywords) is executed.

*If no exception occurs, the except clause is skipped and execution of the try statement is finished.

*If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named
after the except keyword, the except clause is executed, and then
execution continues after the try statement.


text:
Q: We have used stash and are migrating to Bitbucket. How can we migrate pull request data and review comments from stash to bitbucket? We have used stash and are migrating to Bitbucket. How can we migrate pull request data and review comments from stash to bitbucket?
what is the best way to do this?
Anyone has similar experience?

A: If you are moving to Bitbucket Server 4.x it is a lot like any other Stash upgrade you've done before. The product was renamed but the underlying architecture it's much the same. See the upgrade guide at https://confluence.atlassian.com/bitbucketserver/bitbucket-server-upgrade-guide-776640551.html


text:
Q: Need clarification for the Copy sharing mode of Files Connect We want to connect Google Drive as a Connected Source. We want also share files with external users. That's why Reference sharing mode is not an option in our case. While reading the documentation:
Enable Salesforce Files Connect for Your Organization
Files Connect Setup Guide
I didn't understand the Copy file sharing option to its full extent. So my questions are the following:

*

*Does the Copy sharing mode consume File Storage?

*If it consumes the storage, is it possible to select which files would be copied to Salesforce and which wouldn't? Because there are many files (100 GB in total) in Google Drive, we don't want to keep them all in Salesforce. However, from the documentation I got an impression that it's all or nothing.


text:
Q: How to make a rectangle fill up some space given the position of neighbouring rectangles? I am trying to create a figure consisting two stacks of rectangles, side by side. The right stack contains three rectangles, the left one two. The height of the rectangles depends on the text contents. The text contents in both stacks are the same, but given that the text is split over three rectangles in the right stack and that the rectangles are separated by some spacing, this stack is a bit higher.
I prefer to let TikZ figure out the sizes and positions of the rectangles. My strategy is to start with creating the boxes for the right stack and finish with the left stack. My question is how to get the top rectangle of the left stack to take up exactly as much space as to make the top of the stacks align.
I have tried the following, and the result is OK. I don't like the inner sep=0pt part though, which seems a hack and makes the upper lines of text in both stack not align horizontally. Also, the upper left rectangle seems a bit off.
Does anybody know of a way to insert the upper left rectangle such that it fits perfectly and the upper lines of text in both stacks align horizontally? Or is there maybe a better way to achieve the result I want?
Edit: Note that not each line of text in each stack needs to be horizontally aligned. I would like the first line of both upper rectangles to align horizontally. Subsequent lines within a box can just use the default line spacing. So item 7 (and item 1) should ideally be horizontally aligned.
Thanks in advance!
Kor
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{fit, positioning}

\pgfmathsetmacro \spacing {{0.07}}

\begin{document}
    \begin{tikzpicture}[
            level/.style={draw=black, text=black, align=center, minimum width=8.5em},
            bottom level/.style={level, fill=red},
            middle level/.style={level, fill=green},
            top level/.style={level, fill=blue},
        ]

        % Right, higher stack
        \node (r1) [bottom level] {item 1};
        \node (r2) [middle level, above=\spacing of r1]
            {item 6\\item 5\\item 4\\item 3\\item 2};
        \node (r3) [top level, above=\spacing of r2] {item 7};

        % Left stack, whose top should align with right stack
        \node (l1) [bottom level, left=(3 * \spacing) of r1] {item 1};
        \node (l2) [top level,
                    fit=(l1.west |- r2.south) (l1.east |- r3.north),
                    inner sep=0pt,
                ]
            {item 7\\item 6\\item 5\\item 4\\item 3\\item 2};
    \end{tikzpicture}
\end{document}

A: A possible solution. Arrange the text into a matrix with two columsn. This way text in both columns is perfectly aligned. The color can be added through a background layer and it covers the text bau also the space between rows.
\documentclass[tikz, border=2mm]{standalone}
\usetikzlibrary{matrix, backgrounds, fit}

\begin{document}
\begin{tikzpicture}

\matrix(A) [matrix of nodes, nodes={minimum width=3cm, minimum height=8mm}, row sep=1mm, column sep=1mm]
{
item 7 & item 7\\
item 6 & item 6\\
item 5 & item 5\\
item 4 & item 4\\
item 3 & item 3\\
item 2 & item 2\\
item 1 & item 1\\
};

\begin{scope}[on background layer]
\node[draw, fit={(A-1-1)(A-6-1)}, inner sep=0pt, fill=blue!70]{}; \node[draw, fit={(A-7-1)}, inner sep=0pt, fill=red!70]{};

\node[draw, fit={(A-1-2)}, inner sep=0pt, fill=blue!70]{};
\node[draw, fit={(A-2-2)(A-6-2)}, inner sep=0pt, fill=green!70]{}; \node[draw, fit={(A-7-2)}, inner sep=0pt, fill=red!70]{};

\end{scope}
\end{tikzpicture}
\end{document}

A: I'm not sure to understand the question but if the intention is to adjust boxes, a tcbposter can be an alternative. I don't know how OP want to compensate differences between vertical spaces due to different number of boxes, so this is just another alternative to star to work with.
\documentclass[a4paper]{article}
\usepackage[most]{tcolorbox}
\usepackage{lipsum}

\begin{document}
\begin{tcbposter}[
    poster={spacing=2mm, columns=2, height=13cm},
    boxes={sharp corners, notitle},
]
\posterbox{name=L1}{This is some text that will be repeated. This is some text that will be repeated. This is some text that will be repeated. This is some text that will be repeated.}

\posterbox[colback=red!30]{name=Lbottom, above=bottom}{This is some text that will be repeated. This is some text that will be repeated. This is some text that will be repeated. This is some text that will be repeated. This is some text that will be repeated. This is some text that will be repeated. This is some text that will be repeated. This is some text that will be repeated.}
\posterbox[colback=blue!20]{name=L2, between=L1 and Lbottom}{This is some text that will be repeated. This is some text that will be repeated. This is some text that will be repeated. This is some text that will be repeated. This is some text that will be repeated.}

\posterbox[colback=green]{name=R1, column=2}{This is some text that will be repeated. This is some text that will be repeated. This is some text that will be repeated. This is some text that will be repeated. This is some text that will be repeated. This is some text that will be repeated.}

\posterbox[colback=purple!30]{name=R2, column=2, below=R1}{This is some text that will be repeated. This is some text that will be repeated. This is some text that will be repeated.}

\posterbox[colback=blue!20]{name=Rbottom, column=2, above=bottom}{This is some text that will be repeated. This is some text that will be repeated. This is some text that will be repeated. This is some text that will be repeated. This is some text that will be repeated.}

\posterbox[colback=purple!30]{name=R2, column=2, between=R2 and Rbottom}{This is some text that will be repeated. This is some text that will be repeated.}
\end{tcbposter}
\end{document}

A: I have used the approach using tcbposter to draw my picture and it worked out well. For completeness, this is an example of how I used it. It is even possible to annotate the boxes, which is another requirement I have.
\documentclass{standalone}
\usepackage[most]{tcolorbox}
\usetikzlibrary{decorations.pathreplacing}

\begin{document}
    \begin{tcbposter}[
            poster={
                rowspacing=0.7mm,
                colspacing=5mm,
                columns=2,
                height=13em,
                width=20em,
            },
            boxes={
                sharp corners,
                notitle,
                colframe=black!70,
                halign=center,
            },
            coverage={
                top=0cm,
                bottom=0cm,
                left=0cm,
                right=0cm,
                width=25em,
            },
        ]
        \posterbox[colback=red!70]{name=l1, column=1, above=bottom}{item 1}
        \posterbox[colback=blue!70]{name=l2, column=1, between=top and l1}
            {item 7\\item 6\\item 5\\item 4\\item 3\\item 2}
        \posterbox[colback=red!70]{name=r1, column=2, above=bottom}{item 1}
        \posterbox[colback=blue!70]{name=r3, column=2, below=top}{item 7}
        \posterbox[colback=green!70]{name=r2, column=2, between=r3 and r1}
            {item 6\\item 5\\item 4\\item 3\\item 2}

        \draw [decorate, decoration={brace, amplitude=8pt}, thick]
            (TCBPOSTER@r3.north east) -- (TCBPOSTER@r3.south east)
            node [black, midway, xshift=1em, anchor=west] {top};

        \draw [decorate, decoration={brace, amplitude=8pt}, thick]
            (TCBPOSTER@r2.north east) -- (TCBPOSTER@r2.south east)
            node [black, midway, xshift=1em, anchor=west] {middle};

        \draw [decorate, decoration={brace, amplitude=8pt}, thick]
            (TCBPOSTER@r1.north east) -- (TCBPOSTER@r1.south east)
            node [black, midway, xshift=1em, anchor=west] {bottom};
    \end{tcbposter}
\end{document}


text:
Q: Duplicating extbase repository object In my extbase/fluid project,in addition to standard actions such as create,delete,list etc, I want to create a duplicate of a model class object which are stored in a repository. Using findall(), all objects are displayed in a list and corresponding actions such as delete,edit are displayed next to each. For duplicating an object, I have created a duplicate action in the corresponding controller and here is the code:
public function dupcliateAction(Tx_CcCompanylogin_Domain_Model_MyObject $testObject)
{
 $this->myObjectRepository->add($testObject);
 $this->redirect('list');//Lists the objects again from the repository
}

Seems straitforward enough but no new object is added to the repository and I am not getting an error.I have checked the documentation and there is no explicit method available for duplicating.

A: For those who may concern:
You don't need to call the reflection-api at this point.
You only need to implement a method called e.g. resetUid() in your model like this:
public function resetUid() {
  $this->uid = NULL;
  $this->_setClone(FALSE);
}

then you can use the magic clone method to clone the object in your controller. after that you have to call the new resetUid() method and then you are able to persist the new object with the old properties.

A: Note : When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. Any properties that are references to other variables, will remain references.
Alternative you can use reflection to create a (deep) copy of your object.
    $productClone = $this->objectManager->create('Tx_Theext_Domain_Model_Product');

// $product = source object
    $productProperties = Tx_Extbase_Reflection_ObjectAccess::getAccessibleProperties($product);
    foreach ($productProperties as $propertyName => $propertyValue) {
        Tx_Extbase_Reflection_ObjectAccess::setProperty($productClone, $propertyName, $propertyValue);
    }

// $productAdditions = ObjectStorage property
    $productAdditions = $product->getProductAddition();
    $newStorage = $this->objectManager->get('Tx_Extbase_Persistence_ObjectStorage');
    foreach ($productAdditions as $productAddition) {
        $productAdditionClone = $this->objectManager->create('Tx_Theext_Domain_Model_ProductAddition');
        $productAdditionProperties = Tx_Extbase_Reflection_ObjectAccess::getAccessibleProperties($productAddition);
        foreach ($productAdditionProperties as $propertyName => $propertyValue) {
            Tx_Extbase_Reflection_ObjectAccess::setProperty($productAdditionClone, $propertyName, $propertyValue);
        }
        $newStorage->attach($productAdditionClone);
    }
    $productClone->setProductAddition($newStorage);
// This have to be repeat for every ObjectStorage property, or write a service.

A: For me, the Solution "Clone $Object and resetUid() in the Modell" does not work .. maybe this solution had worked in older TYPO3 Versions but in 7.6. LTS it throws an exception
#1222871239: The uid "61" has been modified, that is simply too much.

so maybe someone can find my solution helpful as it is much less code than the other reflection Solution: (and you do not have to think about to set all single properties .. )
Given: an Object called $registrant with all Data.
Wanted Result: a copy of that Object with same Data, but new Uid ..
/** @var \JVE\JvEvents\Domain\Model\Registrant $newregistrant */

$newregistrant = $this->objectManager->get( "JVE\\JvEvents\\Domain\\Model\\Registrant")  ;

$properties = $registrant->_getProperties() ;
unset($properties['uid']) ;

foreach ($properties as $key => $value ) {
    $newregistrant->_setProperty( $key , $value ) ;

}

A: I think the add command ignores objects that already exist.
You could try to clone the object and then add the clone to the repository $copy_of_object = clone $object;. Or maybe create a new Object with all the same properties.


text:
Q: How to splice an existing date-bounded row of data into two new rows based on the date of a new variable? In my longitudinal data set, each row represents a time period of observation for each person, and each row is bounded by a start and end date. The rows are numbered ('episode'), and contain many row-specific variables (eg, 'edu_level') that I need to retain throughout the following steps.
I created a new date variable, hx_start, which can relate to the start and end date of each row of data in 1 of 3 ways (below). For each scenario, I need to edit (splice) the existing row of data accordingly, using dplyr:
1. Between a given row's start and end date (ie, as it does for persons 2 and 4)
In this case, I want to splice the existing row into two new ones, so that the date of
hx_start is the start date of one of the rows. The other row would retain the original row's
start date and its end date would be one day before the date of hx_start.
2. On the same date as someone's row start date (ie, person 1)
In this case, no change is needed.
3. On the same date as someone's row end date (ie, person 3)
Same as #1: I need to splice the existing row into two new ones, so that the date of hx_start
is the start date of one of the rows. The other row would retain the original row's
start date and its end date would be one day before the date of hx_start.
So far, I have created a new data set that has 2 duplicates of each row, assuming that I will need to edit up to 2 rows per existing row, and then drop the originals (or retain only the original, in the case of person 1). Importantly, I need a way to carry forward all of the other variables from the original row to all new rows without naming them all, if possible (there are many in my real data set).
#Load packages
library(lubridate)
#>
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#>
#>     date, intersect, setdiff, union

#Create data set
person <- c(1, 2, 3, 4)
episode <- c(33, 50, 65, 70)
start <- c('2013-01-01', '2010-01-21', '2009-09-18', '2010-05-26')
end <- c('2013-06-04', '2010-06-19', '2009-12-31', '2010-12-24')
hx_start <- c('2013-01-01', '2010-03-09', '2009-12-31', '2010-07-04')
edu_level <- c(2, 3, 2, 1)

#Populate data frame
d <- cbind(person, episode, start, hx_start, end, edu_level)
d <- as.data.frame(d)
#Format dates and add to data frame
d$start <- as.Date(start, format = '%Y-%m-%d')
d$end <- as.Date(end, format = '%Y-%m-%d')
d$hx_start <- as.Date(hx_start, format = '%Y-%m-%d')

#Create 2 duplicates of this row for each person
d1 <- d[rep(seq_len(nrow(d)), each = 3), ]

d1
#>     person episode      start   hx_start        end edu_level
#> 1        1      33 2013-01-01 2013-01-01 2013-06-04         2
#> 1.1      1      33 2013-01-01 2013-01-01 2013-06-04         2
#> 1.2      1      33 2013-01-01 2013-01-01 2013-06-04         2
#> 2        2      50 2010-01-21 2010-03-09 2010-06-19         3
#> 2.1      2      50 2010-01-21 2010-03-09 2010-06-19         3
#> 2.2      2      50 2010-01-21 2010-03-09 2010-06-19         3
#> 3        3      65 2009-09-18 2009-12-31 2009-12-31         2
#> 3.1      3      65 2009-09-18 2009-12-31 2009-12-31         2
#> 3.2      3      65 2009-09-18 2009-12-31 2009-12-31         2
#> 4        4      70 2010-05-26 2010-07-04 2010-12-24         1
#> 4.1      4      70 2010-05-26 2010-07-04 2010-12-24         1
#> 4.2      4      70 2010-05-26 2010-07-04 2010-12-24         1

Created on 2022-03-23 by the reprex package (v2.0.0)

A: You can do this by creating a small helper function. I've done this using data.table formatting
library(data.table)

f <- function(s,m,e) {
  if(m>s) return(list("start" = c(m,s),"hx_start" = c(m,m),"end" = c(e,m-1)))
  if(m == s) return (list("start" = s,"hx_start" = m,"end" =e))
}

setDT(d)[,!c(3:5)][d[ ,f(start,hx_start,end), by=person], on=.(person)]

Output:
   person episode edu_level      start   hx_start        end
1:      1      33         2 2013-01-01 2013-01-01 2013-06-04
2:      2      50         3 2010-03-09 2010-03-09 2010-06-19
3:      2      50         3 2010-01-21 2010-03-09 2010-03-08
4:      3      65         2 2009-12-31 2009-12-31 2009-12-31
5:      3      65         2 2009-09-18 2009-12-31 2009-12-30
6:      4      70         1 2010-07-04 2010-07-04 2010-12-24
7:      4      70         1 2010-05-26 2010-07-04 2010-07-03

Notice that:

*

*For person 2,4, one row now has hx_start as the start date, and the other row has the  original start date, while the end date is one day before the hx_start date.

*For person 1, there has been no change

*For person 3, one row now has hx_start as the start date, and the other row has the  original start date, while the end date is one day before the hx_start date.

Tidyverse option (also uses function above)
inner_join(
  d %>% select(-c(start,hx_start,end)),
  d %>%
  rowwise() %>%
  summarize(person = max(person),
            dates = list(f(start,hx_start,end))) %>%
  unnest_wider(dates) %>%
  unnest(cols=everything()),
  by = "person"
)

Output:
   person episode edu_level      start   hx_start        end
1:      1      33         2 2013-01-01 2013-01-01 2013-06-04
2:      2      50         3 2010-03-09 2010-03-09 2010-06-19
3:      2      50         3 2010-01-21 2010-03-09 2010-03-08
4:      3      65         2 2009-12-31 2009-12-31 2009-12-31
5:      3      65         2 2009-09-18 2009-12-31 2009-12-30
6:      4      70         1 2010-07-04 2010-07-04 2010-12-24
7:      4      70         1 2010-05-26 2010-07-04 2010-07-03


text:
Q: Node.JS - Filename won't accept a variable doesn't work:
console.log(obj.html_template);    // outputs "myfile.html"
var html = fs.readFileSync(JSON.stringify(obj.html_template)); // file not found.

works:
console.log(obj.html_template);    // "myfile.html"
var html = fs.readFileSync("myfile.html"); // Works.

I'm going crazy.

A: > JSON.stringify('myfile.html')
""myfile.html""

Your code is looking for the file "myfile.html" (note the superfluous quotes) in the filesystem.  It doesn't exist.
Just look for it without stringification:
var html = fs.readFileSync(obj.html_template);

A: When you call JSON.stringify, it will convert all the Strings to the JSON format Strings, with surrounding double quotes. Quoting ECMAScript 5.1 Specification for JSON.stringify,

If Type(value) is String, then return the result of calling the abstract operation Quote with argument value.

And the Quote operation, is defined here, which basically surrounds the string with " and takes care of special characters in the String.
So JSON.stringify converts, a string, for example, abcd.txt to "abcd.txt", like this
console.log(JSON.stringify("abcd.txt"));
// "abcd.txt"

which is not equal to abcd.txt.
console.log(JSON.stringify("abcd.txt") == "abcd.txt");
// false

but equal to "abcd.txt".
console.log(JSON.stringify("abcd.txt") == '"abcd.txt"');
// true

So, your program searches for a file named "abcd.txt" instead of abcd.txt. That is why it is not able to find the file and fails.
To fix this problem, just drop the JSON.stringify and pass the string directly, like this
var html = fs.readFileSync(obj.html_template);

A: why are you using JSON.stringify in the first place? you should be able to just do
var html = fs.readFileSync(obj.html_template);


text:
Q: Can I make a cooccurence network with groups clustered spacially in R? I'd like to make a figure like the image below - a microbiome cooccurrence network grouped spatially by phyla. I have the list of nodes and edges, I'm just looking for a simply way to ordinate them in space as groups. Any ideas? Thanks
Example dataframes if that's helpful
#nodes
id label group
1 species1 1
2 species2 1
3 species3 2
4 species4 2
5 species5 2
6 species6 3
7 species7 3
8 species8 3
9 species9 3
10 species10 3

#edges
from to
1 2
1 3
3 4
2 5
2 4
2 7
5 7
5 8
6 9
6 10


text:
Q: How to know whether Send/Discard/Cancel button pressed in Email Compose Activity - Android I have launched email compose Activity by using Intent.ACTION_SEND.
Can someone please tell me how I can get the confirmation/callback when user Send, Discard or  Cancel email?

A: You can't. There is no standardized intent returned by email apps in response to ACTION_SEND. The best way to do it would be to provide the form for creating the email yourself, and only send the intent off if the user chooses to actually send it.


text: Q: What does "control of a deformation problem" mean? Is the expression "control of a deformation problem' ever defined? There are of course many examples relating a dg-Lie or L-infty algebra to a deformation problem, and the phrase is evocative. Is it ever defined?


text:
Q: Wordpress plugin languages not recognized by wordpress.org I'm the developer of the plugin https://wordpress.org/plugins/supplier-and-purchase-order-management-for-woocommerce/
I have a problem with wordpress.org not recognizing all languages of the plugin. It includes several forms of English, Spanish and German. German is not recognized at all. Each language is in the language folder of the plugin and in the main php file i declare the folder as such:
add_action( 'init', 'spom_wpdocs_load_textdomain' );

function spom_wpdocs_load_textdomain() {
    load_plugin_textdomain( 'supplier-and-purchase-order-management-for-woocommerce', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
}

While also defining it in the header:  * Domain Path:       /languages
Inside the folder are all languages mo and po files duly translated in the format of: supplier-and-purchase-order-management-for-woocommerce-en_US.mo and supplier-and-purchase-order-management-for-woocommerce-en_US.po
As you can see looking at the link they are not really recognized.
What am I doing wrong?


text:
Q: Finding unknown integer-valued polynomials using inequalities I've come across this interesting inequalities problem recently, which seemed straight-forward at first glance but has proven interesting enough to ask about it here.
Suppose you are given the degree of an unknown polynomial, and are told that all the coefficients are integers and are all within $min \le a\_k \le max$. Also, you have access to an oracle who will evaluate p(q), the unknown polynomial, and compare it to your guess $g\_q$, where q is the number of previous guesses you have made, and determine if your guess was less, greater than, or exactly equal to the unknown polynomial.
What is the optimal method of choosing guesses, given previous results, in order to make a correct guess as soon as possible in the worst case?
If the degree is d and the coefficients are bounded by [min, max] then it would seem the best possible method would require slightly less than $ \frac {d \log (max - min + 1)}{\log 2}$ by binary search. Its slightly less because with an answer of > from the oracle, you exclude both the values less than and those equal to the guess, which could be more than 50% of possibilities.
If the median of the evaluated values at q of all of the remaining possible polynomials can be found, than guessing that value would be guaranteed to eliminate at least half of the possibilities. But is there any efficient way to find the median of a function of a set of polynomials that are only identified by inequalities?
For the first guess, q is zero and therefore all but the constant term of the polynomial are irrelevant. It makes sense then to make g(0) to be $\frac {min + max}{2}$. But after that, the best way of finding the median quickly seems elusive.
As an example, make min = -100, max = 100 and d = 1. $\frac {-100 + 100}{2}$ = 0, so g(0) should be 0. If the oracle returns > then we know $0 < a\_0 \le 100$ or $1 \le a\_0 \le 100$ since we are dealing with integer coefficients.
An ideal method would include an efficient way to find the median and characterize the set of possibilities given the previous answers from the oracle. But medians can be hard to calculate so an efficient method to calculate the mean of p(q) for the set of possibilities would be close enough if an efficient method doesn't exist for medians.

A: Just determine the coefficient at the highest power first by plugging in huge numbers and doing binary search (comparing to what you'd get for the half-integer coefficients). Once you know it, you can easily figure out the coefficient at the next power in the same way and so on.
Now, if you also have a bound on $q$ you can plug in, it becomes interesting.
Oops, sorry for misunderstanding.
OK, you can easily do $Cd^M\log N$ then. The trick is that no matter how you split the d-dimensional simplex of volume 1 by a hyperplane through its center and no matter which piece you'll take, you'll be able to find a simplex of volume $1-d^{-m}$ conatining this piece where $m$ is some fixed number, which I will need some time to compute precisely (my educated guess would be m=4). Now just use this fact to obtain a simplex of either volume less than $N^{-2d}$ or with one vertex outside the ball of radius $N^{3d}$ containing the set of remaining polynomials after just $O(d^M\log N)$ steps. In both cases, you'll be able to find a linear dependence between the coefficients that is precise up to $N^{-2}$, which means that you can eliminate one coefficient from the polynomial entirely (the $d$-th power of the variable is still well below $N$, so the precision is enough to distinguish the integer values and each exactly attained equality which will not allow you to tell for sure which half you are in gives you food for interpolation).
Sorry if it is too sketchy. I'll try to edit it into something more reasonable later unless somebody gives a better solution.


text:
Q: Mongoid query only when field exist I have a news collection with documents, which may (or may not) have limited time of activity.
I have 3 fields which indicate if news is valid.  active, valid_from, valid_to. Normally I would do this kind of query:
where active = true and (valid_from = null or valid_from < Time.now) and (valid_to = null or valid_to > Time.now). OK. Time.now is ruby only, but I hope you understand.
Can this be done with Mongoid and how?

A: You can try something like:
Model.where(active: true)
     .any_of({valid_from: nil}, {:valid_from.lt => Time.now})
     .any_of({valid_to: nil}, {:valid_to.gt => Time.now})


text:
Q: RestAssured strage behaviour with SpringBoot Problem statement - Path-params sent from RestAssured test case received as null.
An API definition like,
@RequestMapping("myapp")
public interface MyApi {

    @GetMapping(path = "getItem/{path1}/{path2}/{path3}")
    public ResponseEntity<MyResponse> getItem(@PathVariable("path1") String path1,
        @PathVariable("path2") String path2, @PathVariable("path3") String path3);
}

@RestController
public class MyController implements MyApi {

    public ResponseEntity<MyResponse> getItem(String path1, String path2, String path3) {
        return myService.delegateToMethod(path1, path2, path3);
    }

}

This setup fine and gives result.Functional-test code described in shortPart of Test class code
@Test
public void getItemTest() {
    MyResponse response = apiStub.callGetItem("1","2","3");
    Assert.notNull(response);
}

Part of Stub class
public MyResponse callGetItem(String param1, String param2, String param3) {
    return given().port(servicePort)
        .pathParam("path1", param1)
        .pathParam("path2", param2)
        .pathParam("path3", param3)
        .when().get("/myapp/getItem/{path1}/{path2}/{path3}")
        .then().statusCode(200)
        .extract()
        .as(MyResponse.class);
}

Observation Test assertion fails. By putting debug point in controller class, I see path-values are being received as nullWhat's Interesting If I put API definition directly in controller, it works !!DISCLAIMER Code is kept short for brevity, shall expand on sections as requested.Request If duplicate question or bug, request re-direction.

A: You need to put @RestController on API definition as well as the implementing controller.
@RestController
@RequestMapping("myapp")
public interface MyApi {

    @GetMapping(path = "getItem/{path1}/{path2}/{path3}")
    public ResponseEntity<MyResponse> getItem(@PathVariable("path1") String path1,
        @PathVariable("path2") String path2, @PathVariable("path3") String path3);
}

UPDATE Root-Cause was spring-boot version. I was using old version(2.0.8.RELEASE). Segregation of API and Controller, as described does not work. Such end-point results as,
http://localhost:8080/myapp/getItem/{path1}/{path2}/{path3}?path1=v1&path2=v2&path3=v3

Same code, upgraded to spring-boot version 2.4.5, worked correctly.

A: Try to store your params values in the Map object and pass it to .pathParams(Map map) method instead of invoking the same method multiple times.


text:
Q: Provide incbin path as a predefined macro in both NASM and GCC I want to embed a binary file in an executable, in a way that is portable to both Windows and Linux.
For achieving this, I want to use an assembly file with the directive incbin. For example:
.intel_syntax noprefix

      .global _img0_start
      .global _img0_end
      .global _img0_size

_img0_start:   .incbin "img0.bin"
_img0_end:
_img0_size:    .quad  $ -  _img0_start

I can't know where the binary files will be before compiling the above assembly file, so I want to replace img0.bin by a macro, and define it within the command line arguments as if I were using the gcc option -D for defining a macro constant.
I have seen that there exists the -d Option: Pre-Define a Macro, that allows to do exactly the above but only for numeric values (I need to provide a path to a file). (font: https://www.nasm.us/doc/nasmdoc2.html#section-2.1.19)
Is there anything like -d, but that allows to define strings, and works for moth gas and nasm?

A: I have read more and I have realized that there is no need for a macro that expands to a string.
Instead, what can be done is just providing a fixed name for the binary file, in my case, img0.bin, and then use the -I option for providing extra paths for searching such file.
In other words, with the same assembly file as above (let it be assembly_file.s), just do:
gcc -c assembly_file.s -I<path_to_folder_that_contains_img0.bin> -o <output_file_name>

A: NASM macros and the C preprocessor both allow arbitrary strings.
NASM equ constants have to be integers, but %define foo eax or nasm '-DIMG="foo.bin"' both work.
Notice that the macro definition includes the double quotes.  CPP makes it easy to expand a macro inside double quotes, but I didn't bother to check if NASM can easily do that.
It's normally easy to create a double-quoted string like that in Make or whatever.

;;; foo-nasm.asm  NASM source
incbin IMG

# foo-gas.S   GAS source (capital S gets GCC to run it through CPP)
.incbin IMG

hi.bin contains B8 68 69 00 00, the 32/64-bit machine code for  mov eax, 'hi'

 $ gcc -c foo-gas.S -DIMG='"hi.bin"'
 $ nasm -felf64 foo-nasm.asm -DIMG='"hi.bin"'

$ disas foo-gas.o
...
0000000000000000 <.text>:
   0:   b8 68 69 00 00          mov    eax,0x6968

$ disas foo-nasm.o
...
0000000000000000 <.text>:
   0:   b8 68 69 00 00          mov    eax,0x6968


text:
Q: How to compare and concatenate several data in a 2D array on google app script I have a google sheet "test" with the following data
Each user mail has a name associated to it.
I would like to merge on one line the emails that are repeated and concatenate the first names associated with them to obtain the following result on column C and D like that :

I tried this code below because I think that the solution must be solved with a 2D array because the google sheet can receive a large number of emails and different first names.
function myFunction() {
var test = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("test");
const [,...value] = test.getDataRange().getValues(); // Get the values of the arrays

const arrayValue = value.flatMap(([a1,v1]) =>
value.map(([a2,v2]) => {
  const verif = a1==a2 && v1!=v2 ? a2.concat(','+v1+','+v2):'no';
  const name = verif == a2.concat(','+v1+','+v2) ?  v1.concat (','+v2):'';
  const mail = name != '' ? a2:'';
    return [mail,name];
  })
);
 test.getRange(1, 3, arrayValue.length,2).setValues(arrayValue);
}

Today with my code I only obtain this result

It's been several weeks that I'm looking for a solution to my problem and I haven't found anything to solve it. Do you have an idea?
Thanks!

A: Try this:
function lfunko() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("Sheet0");
  const osh = ss.getSheetByName("Sheet1");
  osh.clearContents();
  const vs = sh.getDataRange().getValues();
  let obj = { pA: [] };
  vs.forEach((r, i) => {
    if (!obj.hasOwnProperty(r[0])) {
      obj[r[0]] = [r[1]];
      obj.pA.push(r[0]);
    } else {
      obj[r[0]].push(r[1]);
    }
  });
  let oA = [];
  obj.pA.forEach(p => {
    oA.push([p,obj[p].join(',')])
  })
  osh.getRange(1,1,oA.length,oA[0].length).setValues(oA);
}

Data:

A
B

one@domain.com
name1

one@domain.com
name2

one@domain.com
name3

two@domain.com
name4

two@domain.com
name5

three@domain.com
name5

output:

A
B

one@domain.com
name1,name2,name3

two@domain.com
name4,name5

three@domain.com
name5


text:
Q: count number of columns that have data for each row I have table with 8 columns, and 5000+ rows.
I needed help writing t-sql select that would count for each row the number of columns that are not null.

A: Pure Transact SQL (not using dynamic SQL call which is not part of TSQL):
SELECT
    CASE WHEN c1 IS NULL THEN 0 ELSE 1 END
  + CASE WHEN c2 IS NULL THEN 0 ELSE 1 END
  + CASE WHEN c3 IS NULL THEN 0 ELSE 1 END
  + CASE WHEN c4 IS NULL THEN 0 ELSE 1 END
  + CASE WHEN c5 IS NULL THEN 0 ELSE 1 END
  + CASE WHEN c6 IS NULL THEN 0 ELSE 1 END
  + CASE WHEN c7 IS NULL THEN 0 ELSE 1 END
  + CASE WHEN c8 IS NULL THEN 0 ELSE 1 END
FROM T

A: Try this, replacing the two occurrences of "Catalog" with the name of your table. This has been tested successfully on SQL Server 2008 R2 Dev Edition in the default ReportServer database.
DECLARE @Sql nvarchar(max)
SET @Sql = 'SELECT 0'

SELECT
    @Sql = @Sql + '
+ CASE WHEN [' + [sys].[columns].[name] + '] IS NULL THEN 1 ELSE 0 END'
FROM [sys].[columns]
WHERE [sys].[columns].[object_id] = OBJECT_ID('Catalog')
    AND [sys].[columns].is_nullable = 1

SET @Sql = @Sql + '
AS [NullValuesCount] FROM [Catalog]'

PRINT @Sql

EXEC sp_executesql @Sql

Note that this approach is susceptible to a SQL-Injection attack if you can't trust the source of the column names (e.g. if end users can causes columns to be created with names under their control).


text:
Q: How to change intents order dynamically in DialogFlow I have created several Intents in DialogFlow.
I am controlling the conversational flow of DiglogFlow using context.
I want to change the conversational flow dynamically using Firebase and Intents already created.
I think fullfillment can be a solution to this.
For example:
Let's say there are 2 Intents now: Booking a flight and Trip Course.
After Booking a flight, Trip course is executing now.
I want to add a Trip plan between Booking a flight and Trip course.
How can i use fullfillment at this time?


text:
Q: Unable to Access Content of iFrame Within Blogger Post Page Using Selenium
And it's HTML :

 rwerwer

I am getting NoSuchElementException error when trying to enter the above iframe. Below is the code. I just want to enter the text box and use send_keys.
I tried to this for entering iframe:
driver.switch_to.frame(driver.find_element(By.TAG_NAME, "iframe"))
element = driver.find_element(By.XPATH, '//*[@id=""]/p')
element.send_keys("Hello")

It seems blogger uses a different id for each post post screen so I tried using the id number but failed. I try to use CLASS_NAME but still I keep getting the same error. I guess I can't get inside the iframe. Can you help me? The whole code block is below.
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException

#information
title = ""
response = ""
blogpost_email = ""
blogpost_password = ""

#blogger entering
driver = uc.Chrome(use_subprocess=True)
url1 = 'https://www.blogger.com/'
driver.get(url1)

#waiting page
time.sleep(5)

driver.find_element(By.XPATH, '/html/body/header/div[1]/div[2]/a[1]/span').click()
#waiting page
time.sleep(5)

#entering information
email_block = driver.find_element(By.XPATH, '//*[@id="identifierId"]')
email_block.send_keys(blogpost_email)
driver.find_element(By.XPATH, '//*[@id="identifierNext"]/div/button').click()

#waiting page
time.sleep(10)

#entering information
block_password_block = driver.find_element(By.XPATH, '//*[@id="password"]/div[1]/div/div[1]/input')
block_password_block.send_keys(blogpost_password)
driver.find_element(By.XPATH, '//*[@id="passwordNext"]/div/button/span').click()

#controlling there is no blog
try:
driver.find_element(By.XPATH, '//*[@id="yDmH0d"]/c-wiz/div/div/div/div[2]/div[4]/div[1]/button/span').click()
except NoSuchElementException:
    pass

#waiting page
time.sleep(30)

#entering new post
driver.find_element(By.CLASS_NAME, 'MIJMVe').click()

#waiitng page
time.sleep(10)

#entering information
post_title = driver.find_element(By.XPATH, '//*[@id="yDmH0d"]/c-wiz[2]/div/c-wiz/div/div[1]/div[1]/div[1]/div/div[1]/input')
post_title.click()
post_title.send_keys(title)

driver.switch_to.frame(driver.find_element(By.TAG_NAME, "iframe"))
element = driver.find_element(By.XPATH, '//*[@id=""]/p')
element.send_keys("Hello")
driver.switch_to.default_content()

#publishing
publish_button = driver.find_element(By.CLASS_NAME, 'ZFr60d CeoRYc')
publish_button.click()

#submiting
submit_button = drive.find_element(By.CLASS_NAME, 'RveJvd snByac')
submit_button.click()

A: Notice that these commands are different
driver.find_element(By.TAG_NAME, 'iframe') # the one you are using
driver.find_elements(By.TAG_NAME, 'iframe')

The first one returns the first iframe found in the html, while the second one returns the list of all the iframe. The page to create a post contains several iframe, moreover the number of iframe and their ids change each time you create a new post. Also, the iframe you want is never the first one in the html, so when in your code you run
driver.switch_to.frame(driver.find_element(By.TAG_NAME, "iframe"))

you are switching to the wrong iframe. The iframe you want has the following unique xpath
xpath = "//c-wiz[contains(@style,'visibility: visible')]/descendant::iframe[contains(@class,'ZW3ZFc')]"

so you can switch to it with
driver.switch_to.frame(driver.find_element(By.XPATH, xpath))

and then write text with
textbox = driver.find_element(By.CSS_SELECTOR, 'body.editable')
textbox.send_keys("Hello")


text:
Q: Bind kafka to 0.0.0.0:9092 I have set up Kafka on my amazon ec2 machine running ubuntu-18 following this blog plost and this is how it is exposing the ports.
tcp        0      0 127.0.0.53:53           0.0.0.0:*               LISTEN      772/systemd-resolve
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1220/sshd
tcp        0      0 0.0.0.0:3004            0.0.0.0:*               LISTEN      1041/mongod
tcp6       0      0 :::45827                :::*                    LISTEN      2059/java
tcp6       0      0 :::9092                 :::*                    LISTEN      2136/java
tcp6       0      0 :::2181                 :::*                    LISTEN      2059/java
tcp6       0      0 :::32851                :::*                    LISTEN      2136/java
tcp6       0      0 :::22                   :::*                    LISTEN      1220/sshd

how can I bind it to 0.0.0.0:9092?

A:
how can I bind it to 0.0.0.0:9092

:::9092 should be all you need for binding on IPv6.
If you want to force IPv4, please refer kafka binding to ipv6 port even though ipv4 address specified in config

You can also add this to server.properties to explicitly bind to all interfaces
listeners=PLAINTEXT://0.0.0.0:9092

But when set, you also need to set (and uncomment) advertised.listeners to the external interface address (IP or hostname) that clients should use to communicate to that server, as mentioned in the property file.
# If not set, it uses the value for "listeners".
#advertised.listeners=PLAINTEXT://your.host.name:9092
More details here if you need something more complex https://www.confluent.io/blog/kafka-listeners-explained

A: I am doing this on aws ec2 running ubuntu 18, the blog post shared in the first answer provides detailed information on how to go about this kind of challenge. The main challenge was failing to get a broker connection from the machine.
What worked is to add your machines public DNS(ec2......com) to advertised listeners.
I made the edit in server.properties file and like
advertised.listeners=PLAINTEXT://public DNS(ec2......com):9092


text:
Q: R 3d array to 2d matrix Let's assume I have a 3d array of dimensions (x,y,z) and would like to restructure my data as a matrix of dimensions (x*y,z), something like:
my_array <- array(1:600, dim=c(10,5,12))
my_matrix<-data.frame()

for (j in 1:5) {
  for (i in 1:10) {
     my_matrix <- rbind (my_matrix, my_array[i,j,1:12])
 }
}

Could you suggest a faster and more elegant way?
thanks

A: Change the dimension of the array:
dim(my_array) <- c(10 * 5 , 12)

A: We can convert to a matrix by calling the matrix and specifying the dimensions
res <- matrix(my_array, prod(dim(my_array)[1:2]), dim(my_array)[3])
all.equal(as.matrix(my_matrix), res, check.attributes=FALSE)
#[1] TRUE

NOTE: This will not change the original 'my_array`.  Also, in fact, the code can be simplified to
matrix(my_array, 10*5, 12)

and make it compact.
nchar("matrix(my_array, 10*5, 12)")
#[1] 26

nchar("dim(my_array) <- c(10 * 5 , 12)")
#[1] 31

A: Both @akrun and @Lars Arne Jordanger's solutions work and generate the same results.
The two solutions work by:
(1) concatenating the first rows of all matrices together and placing these rows in the top of the combined matrix; and then
(2) concatenating the second rows of all matrices together and placing these rows under the concatenation of the first rows, and so on.
The following example illustrates the idea very well:
> threeDimArray <- array( NA, dim=c(3,3,4) )
> dims <- dim( threeDimArray )
>
> constants <- c(1, 10, 100)
> for( id in 1:length(constants) ){
   const <- constants[id]
   threeDimArray[id,,] <- matrix( (1:prod(dims[2:3]))*const, dims[2], dims[3] )
 }
> threeDimArray[1,,]
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12
> threeDimArray[2,,]
     [,1] [,2] [,3] [,4]
[1,]   10   40   70  100
[2,]   20   50   80  110
[3,]   30   60   90  120
> threeDimArray[3,,]
     [,1] [,2] [,3] [,4]
[1,]  100  400  700 1000
[2,]  200  500  800 1100
[3,]  300  600  900 1200
> # solution 1:
> twoDimMat <- matrix(threeDimArray, prod(dims[1:2]), dims[3])
> twoDimMat
      [,1] [,2] [,3] [,4]
 [1,]    1    4    7   10
 [2,]   10   40   70  100
 [3,]  100  400  700 1000
 [4,]    2    5    8   11
 [5,]   20   50   80  110
 [6,]  200  500  800 1100
 [7,]    3    6    9   12
 [8,]   30   60   90  120
 [9,]  300  600  900 1200
>
> # solution 2:
> threeDArray <- threeDimArray
> dim(threeDArray) <- c(prod( dims[1:2] ), dims[3])
> threeDArray
      [,1] [,2] [,3] [,4]
 [1,]    1    4    7   10
 [2,]   10   40   70  100
 [3,]  100  400  700 1000
 [4,]    2    5    8   11
 [5,]   20   50   80  110
 [6,]  200  500  800 1100
 [7,]    3    6    9   12
 [8,]   30   60   90  120
 [9,]  300  600  900 1200
>