text:
Q: Run second javascript script after first one is completed - animated text effect I'm using this futuristic style text effect and would like to create effect like this:
First it should animated  phrase:
Test phrase
After that adds a word after this phrase, like:
dog
cat
So the end phrase would be:
Test phrase dog
or
Test phrase cat
First phrase would animate only once, and second would interchange, showing dog first, then cat, and repeat.
I currently found a workaround by using CSS to make the second phrase appear after some time but it's not an ideal situation. Is it possible to set it in JavaScript?
Additionally, for some reason second phrase, when it appears at first, it doesn't have the space before it, making it like:
Test phrasecat
What could be the reason for this?

// Futuristic Resolving/Typing Text Effect
// Copyright (c) by Kevin (https://codepen.io/qkevinto/pen/WQVNWO)
// License (MIT): https://choosealicense.com/licenses/mit/

var resolver = {
  resolve: function resolve(options, callback) {
    // The string to resolve
    var resolveString = options.resolveString || options.element.getAttribute('data-target-resolver');
    var combinedOptions = Object.assign({}, options, { resolveString: resolveString });

    function getRandomInteger(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
    };

    function randomCharacter(characters) {
      return characters[getRandomInteger(0, characters.length - 1)];
    };

    function doRandomiserEffect(options, callback) {
      var characters = options.characters;
      var timeout = options.timeout;
      var element = options.element;
      var partialString = options.partialString;

      var iterations = options.iterations;

      setTimeout(function () {
        if (iterations >= 0) {
          var nextOptions = Object.assign({}, options, { iterations: iterations - 1 });

          // Ensures partialString without the random character as the final state.
          if (iterations === 0) {
            element.textContent = partialString;
          } else {
            // Replaces the last character of partialString with a random character
            element.textContent = partialString.substring(0, partialString.length - 1) + randomCharacter(characters);
          }

          doRandomiserEffect(nextOptions, callback);
        } else if (typeof callback === "function") {
          callback();
        }
      }, options.timeout);
    };

    function doResolverEffect(options, callback) {
      var resolveString = options.resolveString;
      var characters = options.characters;
      var offset = options.offset;
      var partialString = resolveString.substring(0, offset);
      var combinedOptions = Object.assign({}, options, { partialString: partialString });

      doRandomiserEffect(combinedOptions, function () {
        var nextOptions = Object.assign({}, options, { offset: offset + 1 });

        if (offset <= resolveString.length) {
          doResolverEffect(nextOptions, callback);
        } else if (typeof callback === "function") {
          callback();
        }
      });
    };

    doResolverEffect(combinedOptions, callback);
  }

  /* Some GLaDOS quotes from Portal 2 chapter 9: The Part Where He Kills You
     * Source: http://theportalwiki.com/wiki/GLaDOS_voice_lines#Chapter_9:_The_Part_Where_He_Kills_You
     */ };
var strings = [
'Test phrase '];

var counter = 0;

var options = {
  // Initial position
  offset: 0,
  // Timeout between each random character
  timeout: 5,
  // Number of random characters to show
  iterations: 10,
  // Random characters to pick from
  characters: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'x', 'y', 'x', '#', '%', '&', '-', '+', '_', '?', '/', '\\', '='],
  // String to resolve
  resolveString: strings[counter],
  // The element
  element: document.querySelector('[data-target-resolver]')

  // Callback function when resolve completes
};function callback() {
  setTimeout(function () {
    counter++;

    if (counter >= strings.length) {
      counter = 0;
    }

    var nextOptions = Object.assign({}, options, { resolveString: strings[counter] });
    resolver.resolve(nextOptions, callback);
  }, 100000000);
}

resolver.resolve(options, callback);

// Futuristic Resolving/Typing Text Effect
// Copyright (c) by Kevin (https://codepen.io/qkevinto/pen/WQVNWO)
// License: (MIT) https://choosealicense.com/licenses/mit/

var resolver = {
  resolve: function resolve(options, callback) {
    // The string to resolve
    var resolveString = options.resolveString || options.element.getAttribute('data-target-resolver2');
    var combinedOptions = Object.assign({}, options, { resolveString: resolveString });

    function getRandomInteger(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
    };

    function randomCharacter(characters) {
      return characters[getRandomInteger(0, characters.length - 1)];
    };

    function doRandomiserEffect(options, callback) {
      var characters = options.characters;
      var timeout = options.timeout;
      var element = options.element;
      var partialString = options.partialString;

      var iterations = options.iterations;

      setTimeout(function () {
        if (iterations >= 0) {
          var nextOptions = Object.assign({}, options, { iterations: iterations - 1 });

          // Ensures partialString without the random character as the final state.
          if (iterations === 0) {
            element.textContent = partialString;
          } else {
            // Replaces the last character of partialString with a random character
            element.textContent = partialString.substring(0, partialString.length - 1) + randomCharacter(characters);
          }

          doRandomiserEffect(nextOptions, callback);
        } else if (typeof callback === "function") {
          callback();
        }
      }, options.timeout);
    };

    function doResolverEffect(options, callback) {
      var resolveString = options.resolveString;
      var characters = options.characters;
      var offset = options.offset;
      var partialString = resolveString.substring(0, offset);
      var combinedOptions = Object.assign({}, options, { partialString: partialString });

      doRandomiserEffect(combinedOptions, function () {
        var nextOptions = Object.assign({}, options, { offset: offset + 1 });

        if (offset <= resolveString.length) {
          doResolverEffect(nextOptions, callback);
        } else if (typeof callback === "function") {
          callback();
        }
      });
    };

    doResolverEffect(combinedOptions, callback);
  }

  /* Some GLaDOS quotes from Portal 2 chapter 9: The Part Where He Kills You
     * Source: http://theportalwiki.com/wiki/GLaDOS_voice_lines#Chapter_9:_The_Part_Where_He_Kills_You
     */ };
var strings = [
'cat',
'dog'];

var counter = 0;

var options = {
  // Initial position
  offset: 0,
  // Timeout between each random character
  timeout: 5,
  // Number of random characters to show
  iterations: 10,
  // Random characters to pick from
  characters: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'x', 'y', 'x', '#', '%', '&', '-', '+', '_', '?', '/', '\\', '='],
  // String to resolve
  resolveString: strings[counter],
  // The element
  element: document.querySelector('[data-target-resolver2]')

  // Callback function when resolve completes
};function callback() {
  setTimeout(function () {
    counter++;

    if (counter >= strings.length) {
      counter = 0;
    }

    var nextOptions = Object.assign({}, options, { resolveString: strings[counter] });
    resolver.resolve(nextOptions, callback);
  }, 3000);
  // }, 3000);
}

// setTimeout(resolver.resolve(options, callback), 5000);
resolver.resolve(options, callback);
.second-line {
      -webkit-animation: appear 2.5s ease-out;
              animation: appear 2.5s ease-out; }

@keyframes appear {
  0% {
    opacity: 0;
    display: none;
    position: absolute; }
  80% {
    opacity: 0;
    display: none;
    position: absolute; }
  100% {
    opacity: 1; } }

A: For the space issue, you could add a non-breaking space ( ) between the spans and remove/ignore the space in the script.
For the chaining of function calls (1=resolve "Test phrase", 2=resolve "Cat", etc) you could put your resolve call for resolving 2 inside the callback function of 1 (resolver.resolve(options, callback)). This will get called after the first sentence is done animating. (And remove the CSS animation entirely.)


text:
Q: Proof of $ \cos \alpha + \sin \beta + \cos \gamma = 4* \sin( \frac\alpha2 + 45°)* \sin \frac\beta2 * \sin (\frac\gamma2 + 45°) $ Proof of
$$ \cos \alpha + \sin \beta + \cos \gamma = 4* \sin( \frac\alpha2 + 45°)* \sin \frac\beta2 * \sin (\frac\gamma2 + 45°) $$
if $ \alpha + \beta + \gamma = \fracπ2 $
I tried to simplify right side:
$4(-\frac12(\cos(\alpha/2+\gamma/2+π/2)-\cos(\alpha/2-\gamma/2))*\sin(\beta/2)=$
$=-2*\sin(\beta)*\cos(\alpha/2+\gamma/2+π/2)+2\cos(\alpha/2-\gamma/2)*\sin(\beta/2)= $
$=-\sin(\beta/2+\alpha/2+\gamma/2+π/2)-\sin(\beta/2-\alpha/2-\gamma/2-π/2)+\sin(\beta/2+\alpha/2-\gamma/2)+\sin(\beta/2-\alpha/2+\gamma/2) $
Is it possible to simplify this to the left hand side?

A: use that $$\sin\left(\frac{x}{2}+\frac{\pi}{4}\right)=\frac{1}{\sqrt{2}}\left(\left(\sin(\frac{x}{2}\right)+\cos\left(\frac{x}{2}\right)\right)$$

A: I think the second angle should be $\dfrac\beta2 + 45^\circ$
Let  $\displaystyle\frac\alpha2 + 45^\circ=x, \frac\beta2 + 45^\circ=y, \frac\gamma2 + 45°=z$
$90^\circ=\alpha+\beta+\gamma=2x-90^\circ+2y+2z-90^\circ\iff x+y+z)=180^\circ$
$\implies \sin(x+y)=\sin z,\cos(x+y)=-\cos z$
So, the left hand side reduces to $$\sin2x+\sin2y+\sin2z$$
$$=2\sin(x+y)\cos(x-y)+2\sin z\cos z$$
$$=2\sin(z)\cos(x-y)+2\sin z\{-\cos(x+y)\}$$
Can you take it from here?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating a dictionary in julia using set of arrays as keys and values? I have used the following code to create a dictionary using arrays as keys and values.
For Example:
k = [1,2,3,4]
v = [2,3,4,5]

for i in 1:length(k)
    get!(d, k[i], v[i])
end

#Output
Dict{Int64,Int64} with 4 entries:
  4 => 5
  2 => 3
  3 => 4
  1 => 2

May I know is there any simpler approach (preferably single line) to achieve this operation?
Thanks!

A: julia> Dict(zip(k,v))
Dict{Int64, Int64} with 4 entries:
  4 => 5
  2 => 3
  3 => 4
  1 => 2

A: Another option is to use broadcasting on the pair operator:
julia> Dict(k .=> v)
Dict{Int64, Int64} with 4 entries:
  4 => 5
  2 => 3
  3 => 4
  1 => 2


text:
Q: Vulnerability scan report public MQTTClient(MQTTConnectionInfo conn, ConnectionMgr conmgr) throws Exception {
        try {
            clientId = conn.getClientId();
            mqttClient = ClientFactory.getConnection(conn, conmgr);
            username =conn.getUsername();
            log.info("-- inside MqttClient == While Connecting : "+username.toString() + mqttClient.getState());
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

    }

This resource is not properly closed and released in all situations.
how to close getConnection()

A: You could use a finally block which is executed after the try or the catch:
        try {
            mqttClient = ClientFactory.getConnection(conn, conmgr);
            ...
        } catch (Exception e) {
            ...
        } finally {
            mqttClient.close();
        }

Or if the client class implements java.lang.AutoClosable you could use a try-with-resources statement:
        try (MQTTClient mqttClient = ClientFactory.getConnection(conn, conmgr)) {

            mqttClient.doSomething()
        } catch (Exception e) {
            ...
        }


text:
Q: git rebase vs git cherry-pick of detached branch I have two branches:

*

*master

*tmp

tmp branch is detached
I need to put tmp branch on top of master with resolving conflicts in priority of tmp
When I do
git checkout tmp
git rebase --strategy=recursive -X theirs master

I got error
First, rewinding head to replay your work on top of it...
fatal: Could not parse object '0a722ac51071ecb4d00b1ef45384aac227b942a0^'
Unknown exit code (128) from command: git-merge-recursive 0a722ac51071ecb4d00b1ef45384aac227b942a0^ -- HEAD 0a722ac51071ecb4d00b1ef45384aac227b942a0

When I do
git checkout tmp
git cherry-pick --strategy=recursive -X theirs 0a722ac..384144a

Works fine
What the difference or how can I do the same with rebase ?

A: You're getting the rebase error because you didn't explicitly tell it which commit to start with, and because you did explicitly tell it to invoke merge, it went looking for the merge base1.  To tell it not to bother, to just take the whole branch, specify --root:
git checkout tmp
git rebase --strategy=recursive -X theirs --root master

Your cherry-pick didn't do what you think it did.  The .. construct means "not the commit on the left or anything reachable from it ...", in particular, in this case, it means "not 0a722ac".  It didn't cherry-pick the whole branch.  Since cherry-pick is built to expect single commits, you do have to explicitly specify a range, the way to do it here is to simply default the exclusion set to HEAD (since HEAD has nothing in common with tmp, nothing will be excluded):
git checkout master
git cherry-pick --strategy=recursive -X theirs  ..tmp

The asymmetry in the range specification is just a consequence of the two commands' most common usage: rebase applies to the whole of the current branch, while cherry-pick is generally used for one or more single commits..

1 not very intelligently, but rebasing branches with their own complicated merge history wholesale (linear whole-branch rebase works fine) is going to itch so very few people I doubt you'll be able to drum up much desire to help scratch it.

A: A rebase is done by moving all commits after a certain commit: here after the parent of 0a722ac.
A cherry-pick take a list of commits and replicate them: 0a722ac..384144a
Since 0a722ac^ isn't accessible (that is the case, for instance, for an orphan branch, where 0a722ac would be the very first commit), rebase will fail, cherry-pick (which doesn't need to access to the parent of 0a722ac) will succeed.
See more at "How to cherry pick a range of commits and merge into another branch".


text:
Q: Should we use Thread.sleep( ) when doing something with timeout? Consider the following two blocks:
    // block one
    long start = System.currentTimeMillis();
    while (System.currentTimeMillis() - start < TIMEOUT) {
        if( SOME_CONDITION_IS_MET ) {
            // do something
            break;
        } else {
            Thread.sleep( 100 );
        }
    }

    // block two
    long start = System.currentTimeMillis();
    while (System.currentTimeMillis() - start < TIMEOUT) {
        if( SOME_CONDITION_IS_MET ) {
            // do something
            break;
        }
    }

The difference between the two is that the first one has a Thread.sleep(), which seemingly can reduce condition checking in while and if. However, is there any meaningful benefit by having this sleep, assuming the if condition doesn't have a heavy computation? Which one would you recommend for implementing timeout?

A: One key difference is that the second method involves busy waiting. If SOME_CONDITION_IS_MET doesn't involve any I/O, the second approach will likely consume an entire CPU core. This is a wasteful thing to do (but could be perfectly reasonable in some -- pretty rare -- circumstances). On the flip side, the second approach has lower latency.
I agree with Boris that, in a general setting, both approaches are basically hacks. A better way would be to use proper synchronization primitives to signal the condition.


text:
Q: Update color of an image or Background color of Image I am making Image Editor App.I want to add QColorDialog for update Color of image.
I have set image on QLabel.
This is my code that run fine but not able to change color of image.
void ImageViewer::updateColor()
{
    QColor color = QColorDialog::getColor(Qt::white,ui->imageHolder);

    if(color.isValid())
    {
//        QPixmap pixmap = *ui->imageHolder->pixmap();
//        pixmap.fill(color);**  //this is also not change color of image
        ui->imageHolder->setPalette(QPalette(color));
        ui->imageHolder->setAutoFillBackground(true);
        ui->imageHolder->update();
    }
}

I have no idea how to change color of image or backbround color of that image...
is it posible?
Any idea?
Thanks...

A: What is the type of your imageHolder widget ?
I would recommend using Qt Style Sheet to change the background color of a widget.
As Qt documentation states :

Using a QPalette isn't guaranteed to work for all styles, because style authors are restricted by the different platforms' guidelines and by the native theme engine.

To change the background color of your widget (there might be some restriction depending on the type of imageHolder), here is what you could do something like this :
ui->imageHolder->setStyleSheet("background-color : " + color.name());

A: If you are trying to change the pixel values of the image QPalette is not what you think it is for. It's for changing the colors of the UI elements.
If the background color is all you want to change, QPalette can do the job but you will need a image that contains alpha channel or transparency mask. Load a PNG with alpha into your image holder and see if that works.


text:
Q: What is the meaning of "constructed" in the following text? What is "they" referring to in the following sentence? Informational and statistical visualizations engender the rhetoric
of clarity, precision, and fact, though "they" are, of course, constructed interpretations.

A: 'They' refers to 'Informational and statistical visualisations'  - which means 'ways of presenting information graphically'.
'Constructed' means that the said 'informational and statistical visualisations' have been made by somebody - and therefore presumably are subject to that person's 'construction method', perspective, foibles, viewpoint, mood, desired effect, and way of using the data - to create a 'picture' of it.
The 'picture' takes on the appearance of 'clarity, precision, and fact' - perhaps because it is 'physicalised' - however it still is merely an interpretation - a point of view, of the data.


text:
Q: Submitting formatted JSON with PHP form Files
index.php
<form name="postform" action="post.php" method="post" enctype="multipart/form-data">

    Date:	<input type="text" name="startDate">

    Title:	<input type="text" name="headline">

    Article:	<textarea id="text" rows="5" cols="30" type="text" name="text"></textarea>

    Image address:	<input type="text" name="media">

    Image caption:	<input type="text" name="caption">

    	 <input type="submit" value="Submit Entry">

</form>
</form>

post.php
<?php
// check if a form was submitted
if( !empty( $_POST ) ){
// convert form data to json format
$json = json_encode( $_POST );
// make sure there were no problems
//if( json_last_error() != JSON_ERROR_NONE ){
    //exit;  // do your error handling here instead of exiting
// }
$file = 'entries.json';
// write to file
//   note: _server_ path, NOT "web address (url)"!
file_put_contents( $file, $json, FILE_APPEND);
}

Question
I am trying to create a form that will allow my users to add entries to the site. Entries are stored in a JSON file. I have created a form that submits to the JSON form and is formatted like this:
{"startDate":"example",
"headline":"example",
"text":"example",
"media":"example",
"caption":"example"}

Media and caption relate to an image, video or other multimedia, i need them to be stored as a separate object like the example below.
 {"startDate":"example",
 "headline":"example",
 "text":"example",
 "asset" :{"media":"example",
          "caption":"example"}
 }

A: <?php
// check if a form was submitted
if( !empty( $_POST ) ){

// convert form data to json format
    $postArray = array(
      "startDate" => $_POST['startDate'],
      "headline" => $_POST['headline'],
      "text" => $_POST['text'],
      "asset" => array(
         "media" => $_POST["media"],
         "caption" => $_POST['caption']
        )
    ); //you might need to process any other post fields you have..

$json = json_encode( $postArray );
// make sure there were no problems
//if( json_last_error() != JSON_ERROR_NONE ){
    //exit;  // do your error handling here instead of exiting
// }
$file = 'entries.json';
// write to file
//   note: _server_ path, NOT "web address (url)"!
file_put_contents( $file, $json, FILE_APPEND);
}

A: You know json_encode? Simply pass an assisiative array to this function with the given structure
Create an new array i.e and pass it to json_encode
$array = array(
    "startDate" => $_POST['startDate'],
    //..
    "assets" => array(
            "media" => $_POST["media"]
            //..
    )
);
$json = json_encode($array);


text:
Q: How to correlate each row pair to the previous column? I have the following dataframe:

(shape is 72,22)
I would like to correlate each country to each other country, every year. This would result in 21 dataframes of shape 72*72. I guess what's confusing me is that correlation is defined as the relationship of the change between variables, and I'm unsure of how to shift the dataframe to compare the current year to the previous year(hence 21 instead of 22).
I've tried
corr = {}
for x in dfpivot.columns:
    corr[x] = dfpivot[x].corr()

And
corr = {}
for x in dfpivot.T.index:
    corr[x] = dfpivot.T.loc[x].corr()

And I get TypeError: corr() missing 1 required positional argument: 'other'
So I did:
corr = {}
for x in dfpivot.columns:
    corr[x] = dfpivot[x].corr(dfpivot.loc[:,x])

But this correlates each row to itself (meaning that I get all values of 1).
So this last one seemed to me what should work, yet it doesn't.
Why does this return one value per year?:
corr = {}
for x in dfpivot.columns:
    for y in dfpivot.columns[1:]:
        corr[x] = dfpivot[x].corr(dfpivot.loc[:,y])

result:
{'1999-01-01': -0.7847692673880999,
 '2000-01-01': 0.5179357977713173,
 '2001-01-01': -0.8006230706819144,
 '2002-01-01': -0.8608851552658657,
 '2003-01-01': -0.23298450629551196,
 '2004-01-01': -0.792648030305533,
 '2005-01-01': 0.6711413744370501,

Can anyone help?
Data:
['1999-01-01',
 '2000-01-01',
 '2001-01-01',
 '2002-01-01',
 '2003-01-01',
 '2004-01-01',
 '2005-01-01',
 '2006-01-01',
 '2007-01-01',
 '2008-01-01',
 '2009-01-01',
 '2010-01-01',
 '2011-01-01',
 '2012-01-01',
 '2013-01-01',
 '2014-01-01',
 '2015-01-01',
 '2016-01-01',
 '2017-01-01',
 '2018-01-01',
 '2019-01-01',
 '2020-01-01']

['Africa',
 'All Countries Total',
 'Argentina',

[ 2299., -1538.,    nan, -1851.,  1604., -1827., -2047.,  -216.,
          985.,  1338.,  4694.,    16., -2143.,  2830., -2395.,   140.,
         -406.,  5675.,  1110., -2973., -1380.,  1414.]

[ 61756., -12431.,  11624.,  26483.,  -6609.,  20039., -15386.,
        -21390., -17339., -31049.,  48324., -41960.,  17528.,  17136.,
        -12768.,   2743., -17969., -20280., -38804.,  90313., -98720.,
        -66081.]

[  914.,   137.,   151.,  -623.,  -693.,   634.,    nan,    nan,
           nan,   -71.,   427., -3659.,    nan,    nan,   452.,   443.,
         -495., -1097.,   557., -5454.,   910.,    nan]

A: I may be out of my league here but it sounds like you're not after corr().
The way I understand this, is you want to perform a corr() on a dataframe consisting of current year(2020) and 1 other year for every year. That's just 2 columns in every dataframe. Not enough?
If you want to do it it'll only return 1s or -1s for every year, at least that's what I'm getting for every year:
lets transpose your dataframe:
df2 = df.transpose()

now it looks more like this:
          Africa    All C...Total   Argentina
1999-01-01  2299.0    61756.0   914.0
2000-01-01  -1538.0  -12431.0   137.0
2001-01-01  NaN      11624.0    151.0
2002-01-01  -1851.0  26483.0    -623.0
2003-01-01  1604.0   -6609.0    -693.0
2004-01-01  -1827.0  20039.0    634.0
2005-01-01  -2047.0 -15386.0    NaN
2006-01-01  -216.0  -21390.0    NaN
2007-01-01  985.0   -17339.0    NaN
...

apparently we need a list to store our dataframes (naming them in a loop is not pythonic - I've just learned that from this answer)
list_of_df = list()  # <-- here we're going to store the dataframes for each year
index_list = df2.index
current_year = index_list[-1]
for i in range(len(index_list)):
    df_corelated = df2.loc[[index_list[i] , current_year]].corr()
    list_of_df.append(df_corelated)

now everything is ready in a list, want the... say fourth year?:
list_of_df[3]

               Africa   All Countries Total Argentina
Africa                   1.0    -1.0    NaN
All Countries Total     -1.0    1.0     NaN
Argentina                NaN    NaN     NaN

just 1s and -1s


text:
Q: Unable to register AWS Batch Job Definition with Secrets Manager secret When I attempt to register an AWS Batch job definition with secrets from AWS Secrets Manager (specifying an execution role and secrets per the documentation)
aws batch register-job-definition \
    --job-definition-name poc_secrets_job \
    --region us-east-2 \
    --type container \
    --container-properties '{
  "image": "busybox",
  "vcpus": 1,
  "memory": 120,
  "command": [
    "echo",
    "Hello world"
  ],
  "executionRoleArn":  "arn:aws:iam::<AWS-ACCOUNT-ID>:role/<EXECUTION-ROLE-NAME>",
  "jobRoleArn":  "arn:aws:iam::<AWS-ACCOUNT-ID>:role/<EXECUTION-ROLE-NAME>",
  "secrets": [{"name": "TEST_SECRET", "valueFrom": "arn:aws:secretsmanager:us-east-2:<AWS-ACCOUNT-ID>:secret:<SECRET-NAME>"}]
}'

I get the error message:

Parameter validation failed:

Unknown parameter in containerProperties: "secrets", must be one of: image, vcpus, memory, command, jobRoleArn, volumes, environment, mountPoints, readonlyRootFilesystem, privileged, ulimits, user, instanceType, resourceRequirements, linuxParameters

Unknown parameter in containerProperties: "executionRoleArn", must be one of: image, vcpus, memory, command, jobRoleArn, volumes, environment, mountPoints, readonlyRootFilesystem, privileged, ulimits, user, instanceType, resourceRequirements, linuxParameters

I've also been unable to get this to work with Terraform's aws_batch_job_definition resource.

A: Turns out I was on an older version of the aws cli tool.  I upgraded to the latest version 2 (2.1.21) and this now works.


text:
Q: When tracking which elements were clicked e.target.id is sometimes empty I am trying to test the following JavaScript code, which is meant to keep track of the timing of user responses on a multiple choice survey:
document.onclick = function(e) {

    var event = e || window.event;
    var target = e.target || e.srcElement;

    //time tracking
    var ClickTrackDate = new Date;
    var ClickData = "";
    ClickData = target.id + "=" + ClickTrackDate.getUTCHours() + ":" +
        ClickTrackDate.getUTCMinutes() + ":" +
        ClickTrackDate.getUTCSeconds() +";";

    document.getElementById("txtTest").value += ClickData;
    alert(target.id); // for testing
}

Usually target.id equals to the the id of the clicked element, as you would expect, but sometimes target.id is empty, seemingly at random, any ideas?

A: Probably because the element that was clicked didn't have an ID.  This will happen for example if you have HTML like this:

This is some example text.

and someone clicks on the boldface word "example", so that the event target will be the b element instead of the div.
You could try walking up the DOM tree until you find an element that does have an ID, something like this:
var target = e.target || e.srcElement;

while (target && !target.id) {
    target = target.parentNode;
}
// at this point target either has an ID or is null

A: just use e.currentTarget instead of e.target.


text:
Q: Does Gagliardo-Nirenberg inequality in unbounded domain still hold? Often we have the following Gagliardo-Nirenberg inequality: Let $1\leq p_1, p_2\leq \infty$, $0\leq r<l (r, l\in Z_+)$. Suppose that the number
$$
\theta=\frac{n/p-n/p_1-r}{n/p_2-n/p_1-l}
$$
satisfies the inequality $r/l\leq \theta<1$. Then
$$\|u\|_{r, p}\leq C\|u\|_{0, p_1}^{1-\theta}\|u\|_{l, p_2}^\theta.$$
We have known that the inequality holds if the domain is bounded with regular boundary.
I wonder if it still holds when the domain is unbounded in $R^n$ with $n\leq 3$?
It seems true because some people usually use the fact in proving some theorems.
Thanks for your reply!


text:
Q: how to create a custom function for use in a .xlsx in onlyoffice I want to edit a .xlsx document in Onlyoffice, and in a cell, write "=TOLETTER(E1)" where TOLETTER is a function that I define.
I know how to do that in Excel (with a VBA Script).
I have done it in Google Sheet (with JS).
I have not found documentation or an example for Onlyoffice. Onlyoffice macros or plugins are closures and I lack the info how to define/export a function that will be visible from the cell.

A: Currently Onlyoffice doesn't support user defined functions, only macros as you mentioned, using JavaScript and the Document Builder API.


text:
Q: Blackberry Jad file testing not possible? Recently i developed an application in the phonegap. When i build the application i got all the output files like apk,xpa,ipa,jad. All the windows,ios and android outputs are working fine.
Coming to the blackberry i got the .jad file. When i install the instaltion is not possible. I don't know why it is happened. I downloaded BlackBerry Smartphone Simulators 6.0.0 when i goto file browse that is asking only cod file.
If i want to install can i convert that to cod file?is there any converts for cod file? If we want cod file what is the use of jad when i got from the phonegap build. please clarify me.
Thanks&Regards
Shankar

A: A JAD file is a directory for a Java MIDlet that is normally accompanied by a JAR file. In the BBOS architecture the JAR file is replaced with a COD file. I just had a look at the Cordova getting started with BlackBerry document which specifies using a tool delivered with the SDK to install the application on the simulator. Perhapse this tool can find the COD file.
http://cordova.apache.org/docs/en/2.5.0/guide_getting-started_blackberry_index.md.html


text:
Q: Returning string and int from same method public static int getInfo(string info)
    {
        string inputValue;
        int infor;
        Console.WriteLine("Information of the employee: {0}", info);
        inputValue = Console.ReadLine();
        infor = int.Parse(inputValue);
        return infor;

    }

In the above code, how can I get the name(string) and salary(int) of a person? Specifications are that I need to call the method twice for the information retrieval.

A: You can pass it separately or better if you create a class which holds of info and the salary
 public static int getInfo(string info,int salary)

or create a class,
 public class MyInfo
    {
        public int info { get; set; }
        public int salary { get; set; }

    }

and the method signature goes as,
 public static int getInfo(MyInfo info)

If you want to return both string and int , better to change the method signature as of type class MyInfo
 public static MyInfo getInfo(MyInfo info)

A: You could make it return a tuple with both values like this:
internal Tuple<int, string> GetBoth(string info)
{
    string inputValue;
    int infor;
    Console.WriteLine("Information of the employee: {0}", info);
    inputValue = Console.ReadLine();
    infor = int.Parse(inputValue);
    return new Tuple<int, string>( infor, inputValue );
}

internal void MethodImCallingItFrom()
{
    var result = GetBoth( "something" );
    int theInt = result.Item1;
    string theString = result.Item2;
}

A: For returning multiple values from a method we can use Tuples or (DataType, DataType,..).
Tuples are readonly. As a result assigning values is possible only via constructor at the time of declaration.
Below example is using multiple data types as return type. Which is both read and write enabled.
    public (string, int) Method()
    {
        (string, int) employee;
        employee.Item1="test";
        employee.Item2=40;

        return employee;
    }

You can call the above method in your main code, as shown below:
    static void Main(string[] args)
    {

        (string name,int age) EmpDetails = new Program().Method();
        string empName= EmpDetails.name;
        int empAge = EmpDetails.age;

        //Not possible with Tuple<string,int>
        EmpDetails.name = "New Name";
        EmpDetails.age =  41;
    }

However, the best practice is to use class with properties, as mentioned in above answers.

A: public static void Main(string[] args)
    {
        string eName, totalSales;
        double gPay, tots, fed, sec, ret, tdec,thome;
        instructions();
        eName = getInfo("Name");
        totalSales = getInfo("TotalSales");
        tots = double.Parse(totalSales);
        gPay = totalGpay(tots);

}
public static string getInfo(string info)
    {
        string inputValue;
        Console.WriteLine("Information of the employee: {0}", info);
        inputValue = Console.ReadLine();

        return inputValue;

    }

This is what was required. Could have done with other tricks mentioned by you guys. Anyway thank you.

A: Why dont you just return a String array with a size of 2? at the first (array[0]) there is the string and at the second (array[0]) there is the int...
public static string[] GetInfo (string info)

I hope I understood your question right ^^

A: you need to create a person class and read name and salary
public class Person
{
    public string Name {get; set;}
    public decimal Salary {get; set;}
}

and your function will be:
public static Person getInfo(string info)
{
    string inputName;
    string inputSalary;

    Console.WriteLine("Information of the employee: {0}", info);

    Console.WriteLine("Name:");
    inputName = Console.ReadLine();

    Console.WriteLine("Salary:");
    inputSalary = Console.ReadLine();

    Person person = new Person();
    person.Name = inputName;
    person.Salary = int.Parse(inputSalary);
    return person;

}

A: If you want one method to return different types of information, then I would use generics:
public static T GetInfo<T>(string name);

// This can be called as following:
string name = GetInfo<string>("name");
int salary = GetInfo<int>("salary");

There's one problem, though: Console.ReadLine returns a string, while our method could return any type. How can it convert a string to its 'target' type? You could check T and write custom logic for all types you want to support, but that's cumbersome and brittle. A better solution is to let the caller pass in a little function that knows how to transform a string into a specific type:
public static T GetInfo<T>(string name, Func<string, T> convert);

// This can be called as following:
string name = GetInfo<string>("name", s => s);
int salary = GetInfo<int>("salary", int.Parse);

Now how do you implement that method?
public static T GetInfo<T>(string name, Func<string, T> convert)
{
    Console.WriteLine("Please enter " + name);
    string input = Console.ReadLine();
    return convert(input);
}

A few notes:

*

*Type parameters are often just named T, but I find it useful to give them more descriptive names, such as TInfo.

*The <string> and <int> parts can be left out in the second example, because the compiler has sufficient information to infer their types.

*I've left our error handling to keep the examples short and simple. In production code, you'll want to come up with a strategy to handle invalid input, though.


text:
Q: One database table that is referenced by almost all the others I have a relational database similar to the one in the diagram where there is one table called app instance which is the foreign key in almost all other tables in the database. It is meant to represent instances of the same web app.
Essentially if I need to run a test version of the app, I could create a new record in the app instance table. Then all records in the other tables would reference the test app instance keeping the data for the various app instances separate.
Having an app instance table makes it easy to reference all objects related to that app without going through various tables to get to the objects.
Here is the situation I'm dealing with shown in a crow's foot diagram with which I hope to illustrate what I think is a misuse of the idea:

The app instance table is used to represent a group/franchise of stores. Although there are connections from the app instance table to all the other tables, I have left it out of the diagram. A connection from sale to app instance makes sense if I want to query all sales made by a group of stores owned by the same franchise/entity.
However, the other connections to app instance are questionable. items sold in one group's stores can easily be sold in another, the same with the brands. They do not belong to one app instance only.
I think that the right way would be to have separate group and app instance tables. Where app instance keeps ALL the data separate from another instance in the same database.
But in that case, why not just use multiple databases? Is there ever a use case for having one table that references all the other tables in this fashion? Is it possible that having a app instance table would have unwanted effects if it is in the database but not used? Or would there be unwanted effects if only one app instance is ever created?

A: The alternative to this design would probably what you already suggested: giving each web app instance a database or database instance of its own. So this is a trade-off between these two design approaches.
Benefits of the multiple-database approach:

*

*better separation from the perspective of safety and security (if one app instance corrupts its database because of a bug, other instances are not affected; backup-recovery can be done per instance)

*easier scaling - databases can be easier distributed to different machines, if necessary

*the DB schema is simpler and does not cause the confusions you observed

*it is easier to run different app instance versions in parallel when they require different database schemas
Benefits of the single-database approach:

*

*backup can be done for all app instances in one step (note that "recovery" must be done in one step, too, which is not necessarily a benefit)

*cross-instance queries are simpler to implement

*cross-instance data (like a common user table) can be probably managed easier (in a multiple-database approach, one needs usually a separate database instance for this)

*setting up and running multiple database instances may require more effort and costs for certain kind of databases. This depends heavily on the kind of DBMS involved.


text:
Q: Can you change backgroundcolor of an layout resource in Android Studio? I have an activity with a button "Select color" and a edittxt (insert hex code for color). When user hit the button the backgroundcolor of the resourcefile must change to hex code. The color is now set on XML file. How can I change this XML file with user input?
package com.gade.tabletcolor;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

public class PickColor extends AppCompatActivity {

    View view;
    EditText addColor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pick_color);

        ImageButton button = findViewById(R.id.imageBtn11);
        Button AddColor = findViewById(R.id.colorBtn);
        addColor = findViewById(R.id.txtColor);
        view = this.getWindow().getDecorView();

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nextpage();
            }
        });

        AddColor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                setContentView(R.layout.pickcolor);

            }
        });

    }

    public void nextpage(){
        Intent intent = new Intent(this,MainActivity.class);
        startActivity(intent);
    }
}

A: View someView = findViewById(R.id.screen);
View root = someView.getRootView();
root.setBackgroundColor(getResources().getColor(color.white));

or
yourView.setBackgroundColor(Color.parseColor("#ffffff"));

A: Adding to the previous answer.
AddColor.setOnClickListener(new View.OnClickListener() {
  @Override
     public void onClick(View v) {
               yourView.setBackgroundColor(Color.parseColor(<editText>.parseInputToString()));
            }
        });


text:
Q: Android Studio gone nuts all of a sudden
Firstly, Look at the screenshot that I've attached, It is giving me red lines (look to the right) in my entire code (386 errors in 766 lines) all of a sudden (This project was working perfectly fine last time I tested it), It is saying that the import package line is not valid, I thought it would be something with the SDK so I redownloaded Dart SDK but still getting the same error, I redownloaded flutter zip file and added it to my path, also updated it's path in project settings still didn't work, I tried running flutter doctor command and it is saying everything is perfect, I have selected Android SDK too still no help, I even tried reinstalling Android Studio, didn't work either.
(Please help me out with it :( My First Internship is starting soon and I cannot work without android studio)
I have a feeling that it has to do something with the configuration but I can't figure out what to change :/

A: Try any or all of these

*

*Try cleaning/rebuilding the project

*Change SDK path

*Go to your projects main folder in the file explorer and delete the .gradle. Close the project, reopen and let Android Studio redownload the deleted files.

*Update Android Studio

*Uninstall Android Studio and make sure to delete all Android Studio's app data. Once you've done that go to the android page and download Android Studio from the so you have the latest version. Sometimes the IDE has old files that somehow affect your projects.

*Check your gradle-wrapper.properties in your app within Android Studio. Make sure the second line distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip is the latest version which is 7.2.

A: This happens to me sometimes. I do the following which usually fixes it.

*

*Click the build menu then Clean Project.

*Click file, Invalidate Caches.

*Check off all the options on the box that appears.

*Restart Android Stuido.

The project will rebuild when Android Studio starts back up and the errors should be gone.

A: Actually It was very easy to fix, Just run
flutter pub get

It will work after running this command


text:
Q: Updating GUI Popup Menu in Seperate Callback Function I am writing a basic programme that can output a number of different signals (sin, sawtooth, etc) and vary them using mutliple sliders. I cannot get the dropdown menu to update.
I am using 'updateAll', so that all sliders dropdowns, etc update the graph simultaneously when used.
Thanks in advance!
function popChoice_Callback(hObject, eventdata, handles)
contents = cellstr(get(hObject,'String'));
popChoice = contents(get(hObject,'Value'));
if (strcmp(popChoice,'Sine'))
    popVal = 1;
elseif (strcmp(popChoice,'Square'))
    popVal = 2;
elseif (strcmp(popChoice,'Sawtooth'))
    popVal = 3;
elseif (strcmp(popChoice,'Triangular'))
    popVal = 4;
end
assignin('base','popVal',popVal)
updateAll()
%%Some other unrelated coder (sliders, etc) is between these functions
function updateAll
f=round(getappdata(0,'f'));
S_rate=round(getappdata(0,'S_rate'));
t=round(getappdata(0,'t'));
phi=round(getappdata(0,'phi'));
popVal = getappdata(0,'popVal');
if popVal == 1
    Sin_Wave(f,phi,S_rate,t)
elseif popVal == 2
    Square_Wave(f,phi,S_rate,t)
elseif popVal == 3
    Sawtooth_Wave(f,phi,S_rate,t)
elseif popVal == 4
    Triangle_Wave(f,phi,S_rate,t)
end


text:
Q: Chrome uploading image no longer works; other browsers are fine We recently implemented the ability of our members to upload an image. It has worked fine for several months. Recently it has stopped working in Chrome, but continues to work in Firefox, Safari, and Internet Explorer.
The error message that Chrome is generating is as follows:
Uncaught TypeError: Failed to set the 'files' property on 'HTMLInputElement': The provided value is not of type 'FileList'.
The code section that is having the problem is as follows:
    $(window).load(function()
    {
        var aFiletypesAllowed = ["png","gif","jpeg","jpg"];
        var FileTypesPrintable = 'png, gif, jpeg, jpg"';
        var form = document.getElementById('image-submit');
        var options =
        {
            thumbBox: '.thumbBox',
            imgSrc: ''
        }
        var cropper = $('.imageBox').cropbox(options);
        $('#file').on('change', function()
        {
            var reader = new FileReader();
            reader.onload = function(e)
            {
                options.imgSrc = e.target.result;
                cropper = $('.imageBox').cropbox(options);
            }
            reader.readAsDataURL(this.files[0]);
            this.files = [];
            fileSize = this.files[0].size;
            fileName = this.value;
        })
        $('#btnCrop').on('click', function()
        {
            //file validation
            var filetype = fileName.split('.').pop().toLowerCase();
            fileWidth = cropper.getWidth();
            fileHeight = cropper.getHeight();

            //check file type
            if (aFiletypesAllowed.indexOf(filetype) < 0)
            {
                var filenameUsed = fileName.split('\\').pop();
                jConfirm('Invalid Filetype', filenameUsed + ' is not an allowed file type. Allowed filetypes are ' + FileTypesPrintable, '', '', '', '', '', '', '', '', 180);
                document.getElementById('file').value = '';
            }
            //check image dimensions -- at least one dimension must be over the limit to ensure a crop occurs, and the image is modified in some way
            else if (fileWidth < 200 && fileHeight < 200)
            {
                jConfirm('Image too Small', 'Minimum allowed image size is 200 x 200. Your image is ' + fileWidth + ' x ' + fileHeight + '. Please choose a larger image.', '', '', '', '', '', '', '', '', 180);
                document.getElementById('file').value = '';
            }
            //validation passed, perform crop
            else
            {
                var img = cropper.getDataURL();
                $('.cropped').html('<img id="cropped-img" src="'+img+'">'); //image to display
                $('#cropped-to-send').val(img); //dataURL to upload
            }
        })

The error message appears to be generated by the line of code "this.files = [];". After that error occurs, another error is thrown by line "var filetype = fileName.split('.').pop().toLowerCase();". The error on that line is "fileName is not defined".
As stated above, this function ran fine for several months in Chrome, and continues to work fine in Firefox, Safari and Internet Explorer.

A: I don't really understand how this function works, because it was implemented by another programmer based on a library. However, while inspecting the code, the one line "this.files = [];" seems to be problematic. That initializes an empty array; then the next two lines attempt to access elements of that array for later use. Of course, they will be empty.
So on a hunch, I re-arranged the order of some of the lines. The lines from the above code are as follows:
 reader.readAsDataURL(this.files[0]);
 this.files = [];
 fileSize = this.files[0].size;
 fileName = this.value;

I re-arranged them as follows:
reader.readAsDataURL(this.files[0]);
fileSize = this.files[0].size;
fileName = this.value;
this.files = [];

To me the function of these lines is as follows:

*

*perform the data read;

*assign some values

*set this.files to an empty array

After doing this, the function now appears to work properly in Chrome.
My question now is more like: why was it working at all before in any browser? It seems that clearing the array, then trying to use the array is doomed.
And the second mystery is why did it work for several months? I have verified that this particular code has not changed in that period.

A: I had similar problem. Removing the line this.files = []; seams to fix the error, and since reader.readAsDataURL(this.files[0]); has already been called I don't think it will cause any much harm to the file upload. I think the error occurs because it expects a value of type FileList but does not match []


text:
Q: How do you use trackchanges with a citation in a journal template Since I originally posted this, I learned that trackchanges has a known bug in dealing with citations. Some workarounds are given at
workarounds
The one that worked for me was using \protect
I am trying to use trackchanges to make revisions in a manuscript with a journal template and having trouble with citations. If I use
\documentclass{article}
\usepackage[inline]{trackchanges}
\begin{document}
Remove this reference
\remove{
This is a sentence with a reference
\cite{Ells2013}
Will it be removed?
}
This is the end.
\end{document}

I get the error "! Argument of @citex has an extra }." And I get the same error if I use the journal document class. If I add extra brackets as suggested in the thread ; i.e. {\cite{Ells2013}}, it runs and compiles successfully. If, however, I use the journal template
\documentclass[draft]{agujournal2019}
\usepackage{soul}
\usepackage[inline]{trackchanges}
\begin{document}
Remove this reference
\remove{
This is a sentence with a reference
{\cite{Ells2013}}
Will it be removed?
}
This is the end.
\end{document}

I get the error "! Package soul Error: Reconstruction failed.
See the soul package documentation for explanation"
Looking at the agujournal2019 class file was way beyond me and I could not understand the soul package documentation. Does anyone have some suggestions?


text:
Q: Get Last Added Product ID of Cart without using checkout session I am using RESTful APIs of Magento and I want to get the last added product id of in the cart. All of my searches are using the Checkout Session method of Magento which is
$this->checkoutSession->getLastAddedProductId();
But this is not applicable on my end since I am using the RESTful APIs.
Can someone help me if there are any available functionality where I can put a one liner method and class to get this with Quote.
My other solution is to fetch by
Quote :: getAllVisibleItems() and get the last item's product id but I believe it would affect the performance.
Thank you for your help folks.

A: Try below code
public $cart;

public function __construct(\Magento\Checkout\Model\Cart $cart)
{
    $this->cart = $cart;
}

public function getLastQuoteProduct(){
    $itemsCollection = $this->cart->getQuote()->getItemsCollection();
    $itemsCollection->getSelect()->order('created_at DESC');
    $latestItem      = $itemsCollection->getLastItem();
    $product         = $latestItem->getProduct();
    echo 'ID: '.$latestItem->getProductId().'
';
    echo 'Name: '.$latestItem->getName().'
';
    echo 'Sku: '.$latestItem->getSku().'
';
    echo 'Quantity: '.$latestItem->getQty().'
';
    echo 'Price: '.$latestItem->getPrice().'
';
    echo "
";
}

I hope this will work for you...!!!


text:
Q: Can somebody help we draw following complex figure using tikz? Can somebody help we draw following complex figure using tikz?

A: I can't help you with TikZ, but here is an effort in Metapost.  I've only done the first bit so far

Here is the source. Compile with mpost.
prologues := 3;
outputtemplate := "%j%c.eps";
def ? = infont"pcrr8r"scaled.9
rotated 2 normaldeviate enddef;
beginfig(1);
    -z1 = z2 = 100 right; z3 = z2 rotatedabout(z1, 61);
    path t; t = z1 -- z2 -- z3 -- cycle;
    drawoptions(withpen pencircle scaled 2);
    draw t;
    draw for i=1, 5, 7, 2.2, 4, 8: point i/3 of t shifted (normaldeviate, normaldeviate) -- endfor cycle;

    z0 = 1/3 (z1 + z2 + z3);
    label("text1"?, 1/3 (point 5/3 of t + point 6/3 of t + point 7/3 of t));
    label("text2"?, 1/3 (point 7/3 of t + point 8/3 of t + z0));
    label("text3"?, 1/3 (point 7/3 of t + point 5/3 of t + z0));
    label("text4"?, 1/3 (point 4/3 of t + point 5/3 of t + z0));
    label("text5"?, 1/3 (point 0/3 of t + point 1/3 of t + point 8/3 of t));
    label("text6"?, 1/3 (z0 + point 1/3 of t + point 8/3 of t));
    label("text7"?, 1/3 (z0 + point 1/3 of t + point 2.2/3 of t));
    label("text8"?, 1/3 (z0 + point 2.2/3 of t + point 4/3 of t));
    label("text9"?, 1/3 (point 2.2/3 of t + point 3/3 of t + point 4/3 of t));

    label.bot("text"?, origin);

    picture brk; brk = image(draw origin {dir 40} ... {dir 82} 2(5, 15) withpen pencircle scaled 2;
    draw origin {dir -30} ... {dir -84} 2(6, -13) withpen pencircle scaled 2;);

    z10 = point 2 of t shifted -(50, 30);  draw brk shifted z10; label.lft("text10" ?, z10);
    z12 = point 0 of t shifted (-16, 27);  draw brk shifted z12; label.lft("text12" ?, z12);
    z11 = point 3/2 of t shifted 36 right; draw brk reflectedabout(up, down) shifted z11; label.rt("text11"?, z11);

endfig;
end.

(PS. Don't take this too seriously...)


text:
Q: move iOS apps from one developer account to another? We have released 2 version of app in itunesconnect.
One user using version 1 and another user using version 2.
I am going to transfer the version 2 from one account to another account.
version 1 will it work?

A: No, if both versions are in same account. (check the status of version 1, probably it must be inactive and won't become active again, once you replace/upload a higher version of build and if it is active only then it will work.)
If both are in different developer accounts, then you can transfer. (In a same account, both version cannot remain active. Only higher version can remain active).
Note: You can't move single version of app from one to other account. You must move entire application.

A:
As per your question, I think you are trying to ask, if the app with version 1, on existing user's device will keep on running or stop, once you move the app to other account?

if that is your question, then the answer will be YES, the apps with the version 1 on one user will keep on running. However, if you wants to move the application from one account to other then the whole app with all it's previous version information will be moved to new account.

A: @Krunal  and @Bhavin
After App transfer i created the distribution and provisional certificate in new account.
and I tried to update it by uploading the newest version on application loader from new account. At the end, I received the following message:
Potential Loss of Keychain Access - The previous version of software has an application-identifier value of ['teamid1.com.xxx.xxxx.xxxxx'] and the new version of software being submitted has an application-identifier of ['teamid2.com.xxx.xxxx.xxxxx']. This will result in a loss of keychain access.
What i do now??


text:
Q: firebase createUserWithEmailAndPassword not setting current user live When i create a user it dosn't set the auth state i need to refresh to see it why?
with signInWithEmailAndPassword it set the current user right but on createUserWithEmailAndPassword somebody can help?

A: When you use this method createUserWithEmailAndPassword, you create a new authenticated user.
When you use this method signInWithEmailAndPassword, you sign in the authenticated account.
Now when using the first method, it is better to add a loading screen as it takes some time to be able to get the new authenticated user. That is why many websites/app, first you create an account then you sign in.
You can do this:

*

*create account

*sign in with new account

or

*

*create account

*add a loading dialog

*go to home screen


text:
Q: C# Socket(server) Receives only half data I have a program like this:
class FTServerCode
    {
        IPEndPoint ipEnd;
        Socket sock;
        public FTServerCode()
        {
           ipEnd = new IPEndPoint(IPAddress.Any, 5656);
           sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
           sock.Bind(ipEnd);
        }
        public static string receivedPath;
        public static string curMsg = "Stopped";
        public  void StartServer()
        {
            try
            {
                curMsg = "Starting...";
                sock.Listen(100);

                curMsg = "Running and waiting to receive file.";
                Socket clientSock = sock.Accept();

                byte[] clientData = new byte[1024 * 5000];

                int receivedBytesLen = clientSock.Receive(clientData);
                curMsg = "Receiving data...";

                int fileNameLen = BitConverter.ToInt32(clientData, 0);
                string fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);

                BinaryWriter bWrite = new BinaryWriter(File.Open(receivedPath +"/"+ fileName, FileMode.Append)); ;
                bWrite.Write(clientData, 4 + fileNameLen, receivedBytesLen - 4 - fileNameLen);

                curMsg = "Saving file...";

                bWrite.Close();
                clientSock.Close();
                curMsg = "Reeived & Saved file; Server Stopped.";
            }
            catch (Exception ex)
            {
                curMsg = "File Receving error.";
            }
        }
    }

This program works but instead of receiving let's say total file size of 600KB it only receives 6KB of file. The program doesn't crash or anything but it only receives small fraction of file. What's wrong?

A: Problem : you are reading only once by calling the Receive() one time only.
Soution : You need to read the data until unless the Receive function gives you.use while loop to determine whether data is available or not.
Try This:
    int recv=0;
    byte[] data = new byte[1024];

    StringBuilder sb= new StringBuilder();
    while ((recv=clientSock.Receive(data)) > 0)
    {
        sb.Append(Encoding.ASCII.GetString(data, 0, recv));
    }

Complete Code:
class FTServerCode
{
   IPEndPoint ipEnd;
   Socket sock;
   public FTServerCode()
   {
      ipEnd = new IPEndPoint(IPAddress.Any, 5656);
      sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
      sock.Bind(ipEnd);
   }
   public static string receivedPath;
   public static string curMsg = "Stopped";
   public  void StartServer()
   {
      try
      {
         curMsg = "Starting...";
         sock.Listen(100);

         curMsg = "Running and waiting to receive file.";
         Socket clientSock = sock.Accept();

         byte[] clientData = new byte[1024];
         StringBuilder sb= new StringBuilder();
         int receivedBytesLen = 0;
         int fileNameLen = 0;
         string fileName = "";
         BinaryWriter bWrite;
         while((receivedBytesLen =clientSock.Receive(clientData))>0)
         {
            curMsg = "Receiving data...";
            fileNameLen = BitConverter.ToInt32(clientData, 0);
            fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);

            bWrite = new BinaryWriter(File.Open(receivedPath +"/"+ fileName, FileMode.Append)); ;
            bWrite.Write(clientData, 4 + fileNameLen, receivedBytesLen - 4 - fileNameLen);
         }
         curMsg = "Saving file...";

         bWrite.Close();
         clientSock.Close();
         curMsg = "Reeived & Saved file; Server Stopped.";
      }
      catch (Exception ex)
      {
         curMsg = "File Receving error.";
      }
   }
}

A: Most likely you need to put this in a loop until the read call returns 0
 int receivedBytesLen = clientSock.Receive(clientData);


text:
Q: Python create image with new camera position I'm struggling with a specific computer vision task right now. Imagine we have a camera frame of a road for example. Now I want to generate a new frame with the imaginary camera translated horizontally. In addition, there's also a tiny camera angle added. To illustrate this, I uploaded a demonstration image:

How can I create the new frame out of the original one in python?
For my other computer vision tasks I was using OpenCV already.

A: I was struggling with this for a while too until I saw this helpful post that shares some example codes. I understood in theory that you can get the new frame using OpenCV's warpPerspective function if you have the homography matrix. Since you have the exact translation and rotation values, you can derive the matrix yourself given the camera's intrinsic parameters. However it wasn't until I tried out with codes myself that I fully see how it's done.
We know that for a 3D point in space to a 2D image projection the homography matrix is given by
H = K[R|T]
To transform the points from one 2D image to another you simply have to inverse project the points to 3D first and then reproject them to the new image plane.
x' = K * [R2|T2] * [R1|T1](inv) * K(inv) * x
The [R2|T2] * [R1|T1](inv) equates to a single transformation matrix that gives the relative transformation from one camera pose to another. All the matrices are shaped as 4x4 by appending with [0, 0, 0, 1] wherever needed.
Here's some sample codes which are adapted from the codes from the same post.
import cv2
import numpy as np

f = 500
rotXval = 90
rotYval = 90
rotZval = 90
distXval = 500
distYval = 500
distZval = 500

def onFchange(val):
    global f
    f = val
def onRotXChange(val):
    global rotXval
    rotXval = val
def onRotYChange(val):
    global rotYval
    rotYval = val
def onRotZChange(val):
    global rotZval
    rotZval = val
def onDistXChange(val):
    global distXval
    distXval = val
def onDistYChange(val):
    global distYval
    distYval = val
def onDistZChange(val):
    global distZval
    distZval = val

if __name__ == '__main__':

    #Read input image, and create output image
    src = cv2.imread('test.jpg')
    src = cv2.resize(src,(640,480))
    dst = np.zeros_like(src)
    h, w = src.shape[:2]

    #Create user interface with trackbars that will allow to modify the parameters of the transformation
    wndname1 = "Source:"
    wndname2 = "WarpPerspective: "
    cv2.namedWindow(wndname1, 1)
    cv2.namedWindow(wndname2, 1)
    cv2.createTrackbar("f", wndname2, f, 1000, onFchange)
    cv2.createTrackbar("Rotation X", wndname2, rotXval, 180, onRotXChange)
    cv2.createTrackbar("Rotation Y", wndname2, rotYval, 180, onRotYChange)
    cv2.createTrackbar("Rotation Z", wndname2, rotZval, 180, onRotZChange)
    cv2.createTrackbar("Distance X", wndname2, distXval, 1000, onDistXChange)
    cv2.createTrackbar("Distance Y", wndname2, distYval, 1000, onDistYChange)
    cv2.createTrackbar("Distance Z", wndname2, distZval, 1000, onDistZChange)

    #Show original image
    cv2.imshow(wndname1, src)

    k = -1
    while k != 27:

        if f <= 0: f = 1
        rotX = (rotXval - 90)*np.pi/180
        rotY = (rotYval - 90)*np.pi/180
        rotZ = (rotZval - 90)*np.pi/180
        distX = distXval - 500
        distY = distYval - 500
        distZ = distZval - 500

        # Camera intrinsic matrix
        K = np.array([[f, 0, w/2, 0],
                    [0, f, h/2, 0],
                    [0, 0,   1, 0]])

        # K inverse
        Kinv = np.zeros((4,3))
        Kinv[:3,:3] = np.linalg.inv(K[:3,:3])*f
        Kinv[-1,:] = [0, 0, 1]

        # Rotation matrices around the X,Y,Z axis
        RX = np.array([[1,           0,            0, 0],
                    [0,np.cos(rotX),-np.sin(rotX), 0],
                    [0,np.sin(rotX),np.cos(rotX) , 0],
                    [0,           0,            0, 1]])

        RY = np.array([[ np.cos(rotY), 0, np.sin(rotY), 0],
                    [            0, 1,            0, 0],
                    [ -np.sin(rotY), 0, np.cos(rotY), 0],
                    [            0, 0,            0, 1]])

        RZ = np.array([[ np.cos(rotZ), -np.sin(rotZ), 0, 0],
                    [ np.sin(rotZ), np.cos(rotZ), 0, 0],
                    [            0,            0, 1, 0],
                    [            0,            0, 0, 1]])

        # Composed rotation matrix with (RX,RY,RZ)
        R = np.linalg.multi_dot([ RX , RY , RZ ])

        # Translation matrix
        T = np.array([[1,0,0,distX],
                    [0,1,0,distY],
                    [0,0,1,distZ],
                    [0,0,0,1]])

        # Overall homography matrix
        H = np.linalg.multi_dot([K, R, T, Kinv])

        # Apply matrix transformation
        cv2.warpPerspective(src, H, (w, h), dst, cv2.INTER_NEAREST, cv2.BORDER_CONSTANT, 0)

        # Show the image
        cv2.imshow(wndname2, dst)
        k = cv2.waitKey(1)

A: If you are trying to translate, change the plane of the image, that can be done with Homography matrix. Check about perspective transform.  Here .

You need to play with the values H(0,2) and H(2,0) of the matrix to translate along X and then change the image to an angle, like in your image.
First find the Homography matrix with the same image and then change the above position values of the matrix and warp it. You will get as you wanted.
Edit: Homography is simply a 3x3 matrix. Each matrix element corresponds to a specific manipulation on the image.
Like The element in 0x0 position stretches the image horizontally. The element at 1x0 position skew'es the image. Like keeping the left edge still and pulling down the right edge. Like wise, other elements do their respective operations.
Now in the homography matrix, the elements at 2x0 and 0x2 are assigned for the task you wanted. ie, Shifting the plane and Moving along the X direction. By changing (playing) with those values, you get different perspectives of the image. This is hence also called perspective transform.


text:
Q: Limiting access to objects in Django I have a particular model and that model has finegrained access settings. Something like:
class Document(models.Model):
    ...
    access = models.ManyToManyField(Group)

Groups consist of particular tags, and those tags are linked to users. Long story short, one way or another the documents are only accessible by particular users. It is very important that this check does not slip through the cracks. So I can see a number of options. One is that every time I access a Document, I add the check:

Document.objects.filter(access__group__tag__user=request.user)

But there are two drawbacks: a) I query the documents model > 100 times in my views so I will have a LOT of repeated code, and b) it's quite likely that someone will at some point forget to add this restriction in, leaving documents exposed.
So I am thinking that overwriting the objects() makes most sense, through a custom manager. That way I don't duplicate code and I don't risk forgetting to do this.
class HasAccessManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().filter(access__group__tag__user=request.user)

class Document(models.Model):
    ...
    access = models.ManyToManyField(Group)
    objects = HasAccessManager()

However, the problem becomes that request is not accessible there:

name 'request' is not defined

How to solve this? Or are there better solutions?

A: Create a mixin that your views inherit from. This will prevent having duplicated code everywhere. You'll want to write unit tests to make sure your views are locked down appropriately.
class HasAccessMixin(object):
    def get_queryset(self):
        qs = super().get_queryset()

        # you can still leverage a custom model manager here if you want
        # qs = qs.custom_method(access__group__tag__user=self.request.user)

        qs = queryset.filter(access__group__tag__user=self.request.user)
        return qs

class SomeListView(HasAccessMixin, ListView):
    ...

class SomeDetailView(HasAccessMixin, DetailView):
    ...


text:
Q: (How) can I split the Windows 8 Dev Preview + Dev Tools ISO in 2 DVD's? I downloaded the W8DP with Developer tools, but it's 4.8 Gb, just to taunt me (as standard capacity DVD's are 4.7 Gb).
Is it possible to split it on 2 CD's? Or if not, how would I install it?
I would run it in a VM (like VirtualBox), but my CPU doesn't support 64-bit emulation, so I can't.
While waiting for the answer, I'll download the (puny) 32-bit non-dev preview, just in case it's impossible.

A: Install Windows 8 from a USB stick

A: You have several options of other media that can support the size requirement:

*

*Boot from a USB stick (and download.cnet.com link)

*A portable HD (same guide as USB stick)

*Dual Layer DVD

*Blu-ray Disc, requires expensive disc and a blu-ray drive.

A: Or you can install whatever version you like and then install the FULL VERSION of Visual Studio 11 Developer Preview. The Win8x64withTools ISO only has the express edition.
I don't think most people realize that you don't have to have MSDN to get the full VS11 preview. And the full version will even install on Windows 7, although on my quick look it doesn't seem to have the WinRT 'Metro-style' stuff in a Win7 install. I can't answer if there are WinRT/Metro templates if you install it on Win8.


text:
Q: Selenium JS Executor Failure: "Failed to execute elementsFromPoint on Document" I'm running code that fetches a span by the value of its text and then goes to rightclick it using this function:
public void rightClickElement(WebElement element) {
        Actions action = new Actions(driver);
        actions.contextClick(element).perform();
    }

Basically I iterate over a list of filenames and select the element I want to manipulate by its filename by using the following XPATH:
//span[contains(text(), 'PLACEHOLDER')]

with a function that replaces PLACEHOLDER by the current value of the array of filenames I'm iterating over.
This is my code:
*Note: getAssertedElement is just a function I wrote that asserts an element's existence and returns it at the same time.
List<WebElement> textFilesElements = driver.findElements(By.xpath("//span[(@class='document') and contains(text(), '.txt')]"));
ArrayList<String> filesToDelete = new ArrayList<String>();
waitSeconds(1);
for (int i = 0; i < textFilesElements.size(); i++) {
    filesToDelete.add(textFilesElements.get(i).getText());
}

for (int i = 0; i < filesToDelete.size(); i++) {
    WebElement elementToDelete = getAssertedElement("Cannot find the current element",
            replacePlaceholderInString(
                    "//span[contains(text(), 'PLACEHOLDER')]",
                    filesToDelete.get(i)
                    ),
            "xpath");
    System.out.println("FICHIER TO DELETE" + elementToDelete.getText());
    rightClickElement(elementToDelete);
    // do things with element
    ...
}

This works fine the first time through the second for statement, but when I move on to the next filename, even though the element is visible and clickable, the test fails with the following error when it reaches the rightClickElement call:
javascript error: Failed to execute 'elementsFromPoint' on 'Document': The provided double value is non-finite.

I don't understand why, much less how to fix it.


text:
Q: How can i also get count of records between 2 dates in grails i have a query below i want the count between 2 dates within the same gorm query
    def view = StackHash.createCriteria().list(params) {
        if(params?.process){
            eq("process",params.process)
            between("lastDateOfOccurence", fromDate, upToDate)
        }
        order("occurrence", "desc")
    }

    [
        title              : title,
        filter             : CommonService.makeFilterParams(params),
        subtitle           : subtitle,
        view               : view,
        reportInstanceTotal: StackHash.count() ///this is getting total number of records in the database irrespective of dates
    ]

A: You can use the totalCount attribute of the results if you want to know the total number of records that match your criteria:
def view = StackHash.createCriteria().list(params) {
        if(params?.process){
            eq("process",params.process)
            between("lastDateOfOccurence", fromDate, upToDate)
        }
        order("occurrence", "desc")
    }

    [
        title              : title,
        filter             : CommonService.makeFilterParams(params),
        subtitle           : subtitle,
        view               : view,
        reportInstanceTotal: view.totalCount
    ]

Note that view.totalCount is not necessarily the same as view.size().  .size() will tell you how many records are in the result set where .totalCount will tell you how many records match the search criteria.  Those numbers could be different.  For example, if there are 1,000 records in your database, 500 of the records match your criteria and params contains something like [max: 10, offset: 0] then .size() would be 10 but .totalCount would be 500.
I hope that helps.


text:
Q: iOS Safari how to disable autocomplete-like functionality There is a feature in ipad/iphone safari that I would like to disable, but I'm not sure what it is called so im having trouble searching for a solution.
On ipad/iphone, if I am entering some text in to an input text box, there will be a white label that appears under the textbox that has the last value I entered. This little label has an x on the left side for closing. I hope someone knows what im talking about!
I have implemented jquery ui's autocomplete on these input boxes and the label from safari is getting in the way.
Let me know if more details are needed. Thanks!

A: Auto complete is an operating system's setting which the user (not the developer) decides about. The proper solution for this is, to disable any custom autocomplete logic for ios (and most probably for all android devices as well)


text:
Q: Gradle unable to find android_native_app_glue I have a native library which I am trying to build with gradle. If I invoke the ndk-build command from the gradle file, I am able to build the native library. But if I try to use the ndk build functionality built in the android gradle plugin I an unable to build.
I get fatal error: android_native_app_glue.h: No such file or directory
The relevant section of the gradle file is:
buildTypes.debug.jniDebugBuild true

defaultConfig {
    ndk {
      moduleName 'myModule'
      stl 'gnustl_static'
      cFlags '-UNDEBUG -Werror -Wunused-variable -Wunused-but-set-parameter -Wtype-limits -Wmissing-field-initializers -Wreturn-type -Wuninitialized'
      ldLibs 'log', 'GLESv2'
    }
    productFlavors {
      armv7{
        ndk {
          abiFilter 'armeabi-v7a'
        }
      }
    }
}

Is there a way to tell the ndk build where to find the android_native_app_glue.h file?
On a side note, is there a way to pass the verbose flag to ndk-build, the equivalent of ndk-build V=1 ?

A: I had the same issue and I fixed it by adding "-I{path_to_android-ndk}/sources/android/native_app_glue" to cFlags, see here

A: One way to do this is to add it to your LOCAL_C_INCLUDES in Android.mk, like this:
LOCAL_C_INCLUDES += /path/to/ndk/sources/android/native_app_glue

Make sure the path is correct, by doing an ls on /path/to/ndk/sources/android/native_app_glue/native_app_glue.h

A: As of:

*

*gradle-experimental:0.6.0-alpha2

*gradle-2.9-all.zip

One way to do it (Or to integrate any code that can be compiled and link as a static library) is to create in your project a new module, and change the gradle file of that module to be:
apply plugin: 'com.android.model.library'

Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
def ndkDir = properties.getProperty('ndk.dir')

model {
    android {
        compileSdkVersion = 23
        buildToolsVersion = "23.0.2"
        defaultConfig.with {
            minSdkVersion.apiLevel = 21
            targetSdkVersion.apiLevel = 23
            versionCode = 1
            versionName = "0.0.1"
        }
        compileOptions.with {
            sourceCompatibility=JavaVersion.VERSION_1_7
            targetCompatibility=JavaVersion.VERSION_1_7
        }
    }
    android.ndk {
        moduleName = "native-activity"
        cppFlags.add("-Werror")
        ldLibs.addAll(["log", "android"])
        stl        = "gnustl_static"
        ldFlags.add("-c")
    }
    android.sources {
        main {
            jni {
                source {
                    srcDir "${ndkDir}/sources/android/native_app_glue"
                }
            }
        }
    }
}

Then in your module's gradle.mk you should just add:
apply plugin: 'com.android.model.application'

Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
def ndkDir = properties.getProperty('ndk.dir')

model {
    android {
        [...]
    }
    android.ndk {
        [...]

        cppFlags.add("-I${file("${ndkDir}/sources/android/native_app_glue")}".toString())
    }
    android.sources {
        main {
            jni {
                dependencies {
                    project ":native-activity" linkage "static"
                }
            }
        }
    }
}

dependencies {
    compile project(':native-activity')
}

A: add these line in your cMakeList.txt file
//line1
include_directories(${ANDROID_NDK}/sources/android/native_app_glue)

//line2
add_library(native_app_glue STATIC
        ${ANDROID_NDK}/sources/android/native_app_glue/android_native_app_glue.c)

also add native_app_glue in target_link_libraries.
It come in effect only after click on RUN or shift + F10

A: Add to cmake
include(AndroidNdkModules)
android_ndk_import_module_native_app_glue()

target_link_libraries(
        native_app_glue
)


text:
Q: Advantage Database Server: in-memory queries As far as I know, ADS v.10 tries to keep result of query in memory until it is a quite huge. The same should be true for the __output table and for temporary tables. When the result becoming large, swapping stated.
The question is what memory limit is set for a query, a worker, whatever? Could this limit be configured?
Thanks.

A: The overall limit is controlled by the MAX_CACHE_MEMORY configuration parameter.  I don't think there is currently any configuration parameter or mechanism to control it on a per-user basis.
In general, an LRU scheme is used to remove old pages when the limit is reached.  In addition, it uses a scaling algorithm to control how much memory each user can get to avoid allowing one connection to constantly be acquiring overly large portions of the cache.


text:
Q: Compare list of string with list of webelements For sure it's trivial case but I'm having list of webelements and array of strings. I need to check if list of webelements contains string inside that array.
public IList<IWebElement> PaymentNames => driver.WaitForElementsVisible(By.XPath(paymentNameLocator));
string[] expectedPaymentNames = {"Cash","Card"};

    public bool ArePaymentNamesCorrectlyShown(string[] paymentNames)
    {
       return  PaymentNames.Any(t => t.Text == ????);
    }

I was trying to do it by linqu but no idea how to compare it with array...

A: You are pretty close. You cannot compare t.Text to one thing. You need to see if the text is contained in the expected payment names:
return PaymentNames.Any(t => paymentNames.Contains(t.Text));

This particular Contains(...) method is in the System.Linq namespace, which you should already be using in this C# file.


text:
Q: Pandas dataframe values reassignment by index I have rand_df1:
np.random.seed(1)
rand_df1 = pd.DataFrame(np.random.randint(0, 40, size=(3, 2)), columns=list('AB'))
print(rand_df1, '\n')

    A   B
0  37  12
1   8   9
2  11   5

Also, rand_df2:
rand_df2 = pd.DataFrame(np.random.randint(0, 40, size=(3, 2)), columns=list('AB'))
rand_df2 = rand_df2.loc[rand_df2.index.repeat(rand_df2['B'])]
print(rand_df2, '\n')

    A  B
1  16  1
2  12  7
2  12  7
2  12  7
2  12  7
2  12  7
2  12  7
2  12  7

I need to reassign values in the first dataframe col 'A' with values in 'A' of the second dataframe by index. Desired output of rand_df1:
    A  B
0  37  12
1  16  1
2  12  7
2  12  7
2  12  7
2  12  7
2  12  7
2  12  7
2  12  7

A: If I've interpreted your question correctly, you are looking to append new rows onto rand_df2. These rows are to be selected from rand_df1 where they have an index which does not appear in rand_df2. Is that correct?
This will do the trick:
rand_df2_new = rand_df2.append(rand_df1[~rand_df1.index.isin(rand_df2.index)]).sort_index()

A: Thanks to Henry Yik for his solution:
rand_df2.combine_first(rand_df1)

    A  B
0  37  12
1  16  1
2  12  7
2  12  7
2  12  7
2  12  7
2  12  7
2  12  7
2  12  7

Also, tested this with extra column in one dataframe, that doesn't appears in second dataframe and backward situation. It works good.


text:
Q: Alternatives to a!=null I am a new intern in a C# course. I was reading about using null. What can be written instead of a != null?
I already know that instead of a == null I can use a is null.
What is the different between a == null and a is null. Why should I use one of them over the other one?
Is there any equivalent code to a != null?


text:
Q: gRPC context.interceptCall() and SimpleForwardingServerCallListener
*

*Can someone explain or point me into the right direction where I can understand when to use ForwardingServerCallListener.SimpleForwardingServerCallListener or Contexts.interceptCall in gRPC intercept call on the server side.

*In REST a thread gets associated with a request and does the same happen in gRPC too or when a request gets delegated a new thread is created?


text:
Q: change style of span by focusing on an input I want to show word "test" by focusing on text input.
(when text input get focused z-index of text change to 0)
but it didn't work.
(using css.)
my code is just here:
.text{
        position: absolute;
        z-index: -1;

    }
    .main{
        background: #ababab;
    }
    .input-textbox input:focus + span {
        z-index: 0;
    }

        <input type="text" class="input-textbox">
        test

A: wrong selector, change to the following
.input-textbox:focus + span {
    z-index: 0;
}

here is the demo

A: Try the selector like this....
input.input-textbox:focus + span {
        z-index: 0;
}


text:
Q: Is there any way to get all the media with information by one API request Instagram Graph API? Facebook recently changes its Instagram API. Now I can get all the media ids by requesting from this endpoint-
https://graph.facebook.com/v7.0/{ig-user-id}/media?access_token=...

But it only returns the media Ids, not any other media information such as caption, media_url, comments_count, likes_count etc.
For getting these data, I have to request from the API-
https://graph.facebook.com/v7.0/{ig-media-id}?fields=caption,media_url,comments_count&access_token=...

This is working well but the problem is I have to hit this API for each and every {ig-media-id} which is not a good thing.
So, is there any way to get all the media with information (caption, media_url, comments_count, likes_count) by one API request like-
 https://graph.facebook.com/v7.0/{ig-user-id}/media?fields=caption,media_url&access_token=...

A: I solve the problem using Nested Request. Special thanks to @Cbroe.
I've gained the result by using one query after changing the 1st API like this-
https://graph.facebook.com/v7.0/{ig-user-id}?fields=media.limit(4){id,caption,media_url}&access_token=...


text:
Q: Remedy or remedies Dictionaries say the word "remedy" is a countable noun. I found phrases "access to remedy" and "access to effective remedy" without an article in the text of the UN Guiding Principles on Business and Human Rights." For example, "Access to effective remedy has both procedural and substantive aspects." Could anyone explain why the word is used as an uncountable noun?  I can google the expression "access to remedies" in English-language posts. Are both correct?

A: The mistake is believing dictionaries that say the word "remedy" is a countable noun (although, in fairness, it does not say it is only a countable noun).
The uncountable "remedy" is not common and usually refers to the class of of legal actions that will correct an injustice. Nouns are not usually "only countable" or "only uncountable": "countability" is an attribute that can change.

THE Supreme Court's momentous decisions last week on affirmative action, voting rights and same-sex marriage overshadowed a disturbing trend: in the final two weeks of its term, the court ruled in favor of big business and closed the courthouse doors to employees, consumers and small businesses seeking remedy for serious injuries. (New York Times)
In response to their claims, insurance companies formed a posse with their friends in government and are spending their time and resources trying to prevent victims and their families from seeking remedy for their pain, instead of accepting responsibility, paying their debt to society, and changing their ways. (Huffington Post


text:
Q: Flink, multiple time windows? We read data from kafka, the message could be simplified to a Tuple2, here String is the key, and Integer is the type (could be 1, 2, 3), something like,
('key001', 1)
('key001', 2)
('key001', 3)
('key001', 3)
('key002', 1)
('key002', 2)
('key003', 1)
('key004', 1)

We want to get some statistics info, for a 10 minutes window,

*

*count the keys which have type 1,

*count the keys which have both type 1 and type 2,

*count the keys which have all 3 types

I have tried below code, seems works, but look twisted to me, is this correct way to go?
I have to use time window twice here, since using one time window doesn't give what I want, I'm still not clear about the way it works, can anyone explain what happens when apply multiple time windows to the stream?
SingleOutputStreamOperator<Tuple2<String, Long>> x = ds.keyBy(0)
        .timeWindow(Time.seconds(600))
        .process(new ProcessWindowFunction<Tuple2<String, Integer>, Tuple2<String, Long>, Tuple, TimeWindow>() {

            @Override
            public void process(Tuple key,
                    ProcessWindowFunction<Tuple2<String, Integer>, Tuple2<String, Long>, Tuple, TimeWindow>.Context ctx,
                    Iterable<Tuple2<String, Integer>> elements, Collector<Tuple2<String, Long>> out) throws Exception {

                boolean hasType1 = false;
                boolean hasType2 = false;
                boolean hasType3 = false;
                for (Tuple2<String, Integer> t2 : elements) {
                    if (t2.f1 == 1) {
                        if (!hasType1) {
                            hasType1 = true;
                        }
                    } else if (t2.f1 == 2) {
                        if (!hasType2) {
                            hasType2 = true;
                        }
                    } else if (t2.f1 == 3) {
                        if (!hasType3) {
                            hasType3 = true;
                        }
                    }
                    //
                    if (hasType1 && hasType2 && hasType3) {
                        break;
                    }
                }
                if (hasType1) {
                    out.collect(new Tuple2<>("hasType1",1L));
                    if (hasType2) {
                        out.collect(new Tuple2<>("hasType1_Type2",1L));
                        if (hasType3) {
                            out.collect(new Tuple2<>("hasType1_Type2_Type3",1L));
                        }
                    }
                }

            }

        });

x.keyBy(0).timeWindow(Time.seconds(600)).sum(1).map(new MapFunction<Tuple2<String, Long>, String>(){

    @Override
    public String map(Tuple2<String, Long> value) throws Exception {
        return value.f0 + " = " + value.f1;
    }

}).addSink(new BucketingSink<String>("hdfs://...")).setParallelism(1);


text:
Q: Can IntegerProperty's default value be None in google cloud datastore? I'm using Datastore in google cloud.
When I define a kind, can the IntegerProperty's default value be None? Because I wanna query.add_filter('age', '=', None)
e.g.
class User(ndb.Model):
    age = ndb.IntegerProperty(default=None)

The StringProperty can do that.
class User(ndb.Model):
    name = ndb.StringProperty(default=None)

A: Yes, you can. All classes inheriting from Property, such as IntegerProperty, can use the default property.


text:
Q: Android: Reading data from bluetooth when available I'm developing an app to communicate with an Atmega328p microcontroller via bluetooth. The app will request data whenever it needs, sending a simple "newData" string to de Atmega.
What i need to do, is read this data as soon as it is available. If I read it immediatly after I request it, it isn't yet available and the data is readed in the next request. My question is, is there a way to detect when a new data is available, something like inputstream.available()>0, without using an endless loop?
I've tried with BroadcastReciver but couldn't find a way to do it.
Thanks in advance!


text:
Q: getElemntsByClassName is not working expectedly Dom part-4

var h1 = document.getElementsByClassName("h1");
 h1.getAttribute("class")//shows me error getAttribute is not function

Dom part-4

I don't know why it is happened

A: h1 is not an element. From docs:

Returns an array-like object of all child elements which have all of the given class names...

You have to use h1[0]. Here is the docs for getElementsByClassName

var h1 = document.getElementsByClassName("h1");
alert(h1[0].getAttribute("class"))

Test

A: document.getElementsByClassName always return array of element object on which you have made selection.
For example as you want to select "h1"
document.getElementsByClassName will return array of this element. No matter if its the only one in dom.
Put document.getElementsByClassName("selector")[index] to select exact element from DOM

var h1 = document.getElementsByClassName("h1");
console.log(h1);

console.log(h1[0]);

my name abc

A: getElementsByClassName returns an array-like object, so you need to reference the element you want like it was an array element.
var h1 = document.getElementsByClassName("h1");
h1[0].getAttribute("class")

Example

var h1 = document.getElementsByClassName("h1");
console.log( h1[0].getAttribute("class") )

test


text:
Q: VCenter Upgrade Does not work Task/Details
We need to upgrade our Vcenter enviornment from v4.1.0 Build Number: 799345 to v4.1.0 Update 3 Build Number: 816786
Problem
After backing up the database and the SSL certificates we run the update from the .zip file provided by VMWare located here.  It alerts us that we will be updating and if we wish to continue the update finishes without any errors and all clients are pushed new agents correctly as well.  However, when we check the version information it still shows Build Number: 799345 as though the update was never run.  As far as I can tell it should be Build Number: 816786.
Any ideas why VCenter is not actually updating properly?  There are no errors.


text:
Q: Multiple refs in react I have a Container, that should have references to some of it's children components:
const Container = () => {
  const blocks: HTMLDivElement[] = [];

  return (

      <Navigation currentBlock={currentBlock} blocks={blocks} />

 ref && blocks.push(ref)}>
        // ...

 ref && blocks.push(ref)}>
        // ...

 ref && blocks.push(ref)}>
        // ...

 ref && blocks.push(ref)}>
        // ...

  );
};

But, when I try to render Navigation component, the blocks variable is an empty array.
I tried converting blocks variable to a reference using useRef hook:
const Container = () => {
  const blocks = useRef<HTMLDivElement[]>([]);

  return (

      <Navigation currentBlock={currentBlock} blocks={blocks.current} />

 ref && blocks.current.push(ref)}>
        // ...

 ref && blocks.current.push(ref)}>
        // ...

 ref && blocks.current.push(ref)}>
        // ...

 ref && blocks.current.push(ref)}>
        // ...

  );
};

blocks is still an empty array on render, but after that it becomes a valid array of references that I wanted.
Is there any way to update Navigation component without rerendering Container?
EDIT:
Here's my Navigation component:
const Navigation = ({ currentBlock, blocks }: { currentBlock: number, blocks: MutableRefObject<HTMLDivElement[]>}) => {
  console.log(blocks.current);
  return (

      {blocks.current.map((_, idx) => (
        <NavigationLink key={idx} active={currentBlock === idx} />
      ))}

  );
}

In my console, I have this output:

The Navigation component doesn't render any NavigationLinks, as if the array is empty.

A: To store the refs, you should use the useRef hook. However you must pass on the refs to another component, not by using blocks.current but just blocks. This way it would ensure that the props used by the navigation component can then access the mutated properties since a re-render is not triggered when the refs are assigned
const Container = () => {
  const blocks = useRef<HTMLDivElement[]>([]);

  return (

      <Navigation currentBlock={currentBlock} blocks={blocks} />

 ref && blocks.current.push(ref)}>
        // ...

 ref && blocks.current.push(ref)}>
        // ...

 ref && blocks.current.push(ref)}>
        // ...

 ref && blocks.current.push(ref)}>
        // ...

  );
};

Now inside the Navigation component you can make use of props.blocks.current


text:
Q: Why I use 'console.log(this)' and the this do not bind to console? Now I have some code:
window.testFun = {
   say() {
      console.log(this);
   }
};

window.testFun.say();     //  print say

window.console.log(this); // why not console but window?

I am sorry that my English is not very good, but I am actively learning English now, and I hope to be able to actively discuss the code with everyone

A: The value of this is defined by the function this is used inside.
You are using it in the global scope. You are just passing it to log. It isn't a keyword inside the log function itself (which is built into the browser and you aren't looking at the source code for it).


text:
Q: Method executing several times even though it is called once I am doing a project which includes dynamic controls creation and removal from the WinForm,
So I decided to that part on a small test project.
Test project has two files Form1.cs and NewControls.cs. This program creates additional buttons whenever user clicks an Add button already on the form.And removes the newly created button when it is clicked (self removal button). Also after removal of button other button's Name, Text and their position are changed according to a local variable (controlIndex).
Form1.cs
public partial class Form1 : Form
{
    static List<NewControl> newControlsList = new List<NewControl>();
    public Form1()
    {
        InitializeComponent();
    }

    private void Add_Click(object sender, EventArgs e)
    {
        newControlsList.Add(new NewControl(newControlsList.Count));
    }

    public static void RemoveButton(object sender, EventArgs e)
    {
        NewControl tempNewControl = (NewControl)(sender as Button).Tag;
        tempNewControl.RemoveControl();
        newControlsList.Remove(tempNewControl);
        MessageBox.Show("Removed!");
        foreach (NewControl tempcontrol in newControlsList)
        {
            tempcontrol.controlIndex = newControlsList.IndexOf(tempcontrol);
            tempcontrol.PlaceControl();
        }
    }
}

NewControl.cs
class NewControl
{
    public int controlIndex = 0;
    Button newButton = new Button();

    public NewControl(int index)
    {
        controlIndex = index;
        PlaceControl();
    }

    public void RemoveControl()
    {
        newButton.Dispose();
        Form1.ActiveForm.Controls.Remove(newButton);
    }

    public void PlaceControl()
    {
        newButton.Tag = this;
        newButton.Name = "btn" + controlIndex.ToString("D2");
        newButton.Text = "btn" + controlIndex.ToString("D2");
        newButton.Size = new Size(100, 20);
        newButton.Left = controlIndex * 100;
        Form1.ActiveForm.Controls.Add(newButton);
        newButton.Click += new EventHandler(Form1.RemoveButton);
    }
}

Program works nearly as expected. Problem is the MessageBox which I used in form1.cs in RemoveButton() fires many time (as opposed to just one time), which implies whole method being executed several times. Actually I pasted that MessageBox for debugging (sort of).
Since I cannot debug the application as when "Form1.ActiveForm.Controls.Add(newButton);" statement is executed, debugger Throws NullReferenceException, as there is not an active form while debugging.
I know that's like a bonus question but I thought to just put it there. I am a beginner and can't see the way through both the problems. 1st problem is really important for my original project as it will cause problem when many controls are added.

A: I think it is because you call PlaceControl from Form1.cs AND in the constructor of the NewControl class, Because you say newButton.Click += new EventHandler(Form1.RemoveButton);.
You are adding EventHandlers, so there can be more of them.
So when you call placeControl multiple times, you've got multiple event handlers, i think.

A: Probably the EventHandler hasn't been removed by RemoveButton. (I've been working in java most recently so my terms might be a little off for C#.) Suggestion: set control visibility to true when you want it and false otherwise rather than adding and removing.

A: Everytime a button is removed you go over your existing list of controls, and you call "PlaceControl", which attaches yet another handler.
foreach (NewControl tempcontrol in newControlsList)
{
    tempcontrol.controlIndex = newControlsList.IndexOf(tempcontrol);
    tempcontrol.PlaceControl();
}

Remove the above code block from RemoveButton, and you will see that your dynamically added buttons will each only trigger the event once.

A: In your RemoveButton event you loop on each button and call again PlaceControl.
The only reason is to reposition the remainder controls.
I think it's better a call to a separate method that do only this work.
public void RepositionControl()
{
    newButton.Left = controlIndex * 100;
}

this will prevent to mess with event handlers added more than one time