text:
Q: Absolute integrability and propositional logic for the proof From the following answer of the post Fourier transform of derivate

Because you are assuming that $f'\in L^1(\mathbb{R})$, then the following limits exist
  $$
       \lim_{x\rightarrow\pm\infty}f(x)=\lim_{x\rightarrow\pm\infty}\int_{0}^{x}f'(t)dt+f(0).
$$
  The above limits must be $0$ because $f \in L^1(\mathbb{R})$; otherwise, for example, if $\lim_{x\rightarrow\infty}f(x)=L \ne 0$, then $|f(x)| \ge L/2$ for large enough $x$, which would contradict the absolute integrability of $f$ on $[0,\infty)$. Because these limits must be $0$, then the evaluation terms below vanish:
  \begin{align}
       \int_{-\infty}^{\infty}f'(t)e^{-ist}dt &  = \left.f(t)e^{-ist}\right|_{t=-\infty}^{\infty}-\int_{-\infty}^{\infty}f(t)\frac{d}{dt}e^{-ist}dt \\
  & =is\int_{-\infty}^{\infty}f(t)e^{-ist}dt.
\end{align}

I don't understand the part :

The above limits must be $0$ because $f \in L^1(\mathbb{R})$; otherwise, for example, if $\lim_{x\rightarrow\infty}f(x)=L \ne 0$, then $|f(x)| \ge L/2$ for large enough $x$, which would contradict the absolute integrability of $f$ on $[0,\infty)$

i.e, I don't understand what means "which contradict the absolute integrability of $f$" if one takes a limit different from $0$ ?
Let's take for example the function $f(x)=1/x +1$ : this function tends to $1$ when $x\to\infty$ : should one conclude that $f$ is not absolute integrable ?
I would like to prove with propositional logic that if I assume a limit $L$ different from $0$, then we can deduce a contradiction on absolute integrability.
For this, I would start by the definition of the limit $L\neq 0$ of $f$ when $x\to\infty$:
$\forall \epsilon > 0$,$\exists\,a$ such that $x \geqslant a \Longrightarrow f(x) \geqslant L - \epsilon$
How can I follow the reasoning to prove the contradiction with $\int_{0}^{+\infty}|f(x)|\text{d}x < +\infty$ ?
Regards


text:
Q: Create team from group fails with exception I created teams in Microsoft Teams (from groups as documented here) via the C# graph-api sdk without any problems - everything was working just fine.
But suddenly this is not working anymore. I will always get the following exception at the line return await graphServiceClient.Teams.Request().AddAsync(team);:

Message: Failed to execute Templates backend request
CreateTeamFromGroupWithTemplateRequest. Request Url:
https://teams.microsoft.com/fabric/emea/templates/api/groups/theGroupId/team,
Request Method: PUT,

And further:

Team Visibility can not be specified as it is inherited from the
group.

I know that the visibility property must not be set if creating the team from a group as it states in the Microsoft documentation:

The team that's created will always inherit from the group's display name, visibility, specialization, and members. Therefore, when making this call with the group@odata.bind property, the inclusion of team displayName, visibility, specialization, or members@odata.bind properties will return an error.

But the currently used code below shows that I am not setting any forbidden properties - and this code worked for the last few days, too:
    private async Task<Team> CreateTeamFromGroup(string groupId)
    {
        var graphServiceClient = [...]

        var groupResourceLink = $"https://graph.microsoft.com/v1.0/groups('{groupId}')";
        var team = new Team
        {
            AdditionalData = new Dictionary<string, object>()
            {
                { "template@odata.bind", "https://graph.microsoft.com/beta/teamsTemplates('standard')" },
                { "group@odata.bind", groupResourceLink }
            },
            Channels = new TeamChannelsCollectionPage
            {
                new Channel
                {
                    DisplayName = "WhatEver"
                }
            }
        };

        return await graphServiceClient.Teams.Request().AddAsync(team);
    }

Is anyone else experiencing this problem? Was there an API change? Was the teams backend changed? Anyone any ideas?
P.S.: I am using the latest NuGet-Package for Microsoft Graph - downgrading didn't help.
Update (with a not very satisfying work-around)

*

*The error can be reproduced via the graph api explorer, too.

*The POST command above issues a PUT command, that is described here. With this request, the team can be created.

*

*The documentation and the graph api snippet for C# is out-dated, though. You have to add odatatype = null to the properties when using the sdk

*Unfortunately it is not possible to add channels in the same step. If you specify the property 'channels' it will just be ignored.

Update (Detailed error message)

System.AggregateException: 'One or more errors occurred. (Code:
BadRequest Message: Failed to execute Templates backend request
CreateTeamFromGroupWithTemplateRequest. Request Url:
https://teams.microsoft.com/fabric/emea/templates/api/groups/theGroupId/team,
Request Method: PUT, Response Status Code: BadRequest,
ErrorMessage : {"errors":[{"message":"Team Visibility can not be
specified as it is inherited from the
group."}],"operationId":"639448e414ece64caee8f52839585bf7"} Inner
error:    AdditionalData:     date: 2020-11-24T10:21:22   request-id:
37a28cac-3ac5-4bd2-a061-daf44c442fac  client-request-id:
37a28cac-3ac5-4bd2-a061-daf44c442fac ClientRequestId:
37a28cac-3ac5-4bd2-a061-daf44c442fac )'

A: This was a Microsoft issue/ bug and is currently being fixed as stated here.

A: Just tested this morning and I can say, that the "old way" by using the beta API to create a team with a template works again. Don't know, how many other ways exist to do these things, but here is our current request, that works now (again).
POST https://graph.microsoft.com/beta/teams
{
    "displayName": "My Group Name",
    "description": "Some description",
    "template@odata.bind": "https://graph.microsoft.com/beta/teamsTemplates('educationClass')",
    "owners@odata.bind": [
        "https://graph.microsoft.com/beta/users('<someValidUserId>')"
    ]
}

I think this will be just an intermediate state and when the bugs are fixed, they will publish the new version again and this kind of creation will fail again, but if in this case the v1.0 documented way will work this wouldn't be a big problem. But being informed BEFORE there roll-out starts would be great.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to switch Off/On an LSTM layer? I am looking for a way to access the LSTM layer such that the addition and subtraction of a layer are event-driven. So the Layer can be added or subtracted when there is a function trigger.
For Example (hypothetically):
Add an LSTM layer if a = 2 and remove an LSTM layer if a = 3.
Here a = 2 and a= 3 is supposed to be a python function which returns specific value based on which the LSTM layer should be added or removed. I want to add a switch function to the layer so that it can be switched on or off based on the python function.
Is it possible?
Currently, I need to hard code the layer needed. For eg:
# Initialising the RNN
regressor = Sequential()

# Adding the first LSTM layer and some Dropout regularization
regressor.add(LSTM(units = 60, return_sequences = True, input_shape =
(X_train.shape[1], X_train.shape[2])))
#regressor.add(Dropout(0.1))

# Adding the 2nd LSTM layer and some Dropout regularization
regressor.add(LSTM(units = 60, return_sequences = True))
regressor.add(Dropout(0.1))

My goal is to both add and subtract these layers at runtime.
Any help is appreciated!!

A: I found the answer and posting in case anyone else is looking for the solution.
This can be done by using freeze Keras layer functionality. Basically, you need to pass the boolean trainable argument to the layer constructor to set it as non-trainable.
Eg:
 frozen_layer = Dense(32, trainable=False)

Additionally, in case you want to set the trainable property of a layer to True or False after instantiation. By calling compile() on your model after modifying the trainable property. Eg:
    x = Input(shape=(32,))
    layer = Dense(32)
    layer.trainable = False
    y = layer(x)

    frozen_model = Model(x, y)
    # the weights of layer will not be updated during training for below model
    frozen_model.compile(optimizer='rmsprop', loss='mse')

    layer.trainable = True
    trainable_model = Model(x, y)
    # the weights of the layer will be updated during training
    # (which will also affect the above model since it uses the same layer instance)
    trainable_model.compile(optimizer='rmsprop', loss='mse')

    frozen_model.fit(data, labels)  # this does NOT update the weights of layer
    trainable_model.fit(data, labels)  # this updates the weights of layer

Hope this helps!!


text:
Q: FWrite in new line Trying to make my form inputs to be written in data.txt file.
I want it to write in new line each time someone registers.
Tried to use .PHP-EOL but it doesn't seem to add any new line after each entry!
<?php
 $path = 'data.txt';
 if (isset($_POST['firstname']) && isset($_POST['country']) && isset($_POST['email'])) {
    $fh = fopen($path,"a+");
    $string = $_POST['firstname'].' - '.$_POST['country'].' - '.$_POST['email'] .PHP_EOL;
    fwrite($fh,$string); // Write information to the file
    fclose($fh); // Close the file
 }
?>

A: I got it to work!
Use PHP_EOL at the beginning instead of the end.
Here is the code now:
<?php
 $path = 'data.txt';
 if (isset($_POST['firstname']) && isset($_POST['country']) && isset($_POST['email'])) {
    $fh = fopen($path,"a+");
    $string = PHP_EOL .$_POST['firstname'].' - '.$_POST['country'].' - '.$_POST['email'];
    fwrite($fh,$string); // Write information to the file
    fclose($fh); // Close the file
 }
?>


text:
Q: how to make css for work for different mobile sites I have a desktop site and I've created a css file for the mobile site. It looks good on most mobiles but on an android tablet browser the menu links background color is not showing. How would I debug this? Is there a way I can code css to make changes just for android browsers?
I'm not sure where to start with this.
Thanks
To further explain the question:
I have a mobile css file that works well for iphone and android. Just one part of the site eg http://thepetwiki.com/q2a/ works for iphones but on android tablet the menu dropdown is not working. How do I change the code so works for android tablets as well?
      .navigation {
    max-width: none;
    background: #21a9e9;
    padding: 0;
    list-style: none;
    }

    .navigation li {
      float: left;
    }

  .navigation li a {
    display: block;
    color: #fff;
    padding: 10px;
  }

  .navigation li a:hover {
    background: #0fcaf2;
    text-decoration:none;
  }
  .navheader {
    font-size: 30px;
    padding-top: 0;
    /*font-family: helvetica;*/
  }

  .slide-trigger {
    display: none;
    border: 1px solid #CCCCCC;
    cursor: pointer;
    color: #FFFFFF;
  }

  .slide-trigger span {
    background-image: url("skins/mobile/dropdown-arrows.png");
    background-position: 0 -14px;
    display: block;
    float: right;
    margin-top: 3px;
    height: 14px;
    width: 32px;
  }
  @media only screen and (max-width: 1000px) {
    .slide-trigger { display: block; }
      .no-js .slide-trigger { display: none; }
    .navigation { display: none; }
      .no-js .navigation { display: block; }
    .navigation { margin: 0 15px; }
    .navigation li { float: none; }
    .navigation li a { border-bottom: 1px solid #fff; }
  }
  </style>
<script>
/* MOBILE COLLAPSE MENU */
(function($) {
  $.fn.collapsable = function() {
    // iterate and reformat each matched element
    return this.each(function() {
      // cache this:
      var obj = $(this);
      var tree = obj.next('.navigation');
      obj.click(function(){
        if( obj.is(':visible') ){tree.toggle();}
      });
      $(window).resize(function(){
        if ( $(window).width() <= 1000 ){tree.attr('style','');};
      });
    });
  };
})(jQuery);
var $j = jQuery.noConflict();
$j(document).ready(function(){
    $j('.slide-trigger').collapsable();
});
</script>`

A: here you go
@media (min-width:320px) { /* smartphones, iPhone, portrait 480x320 phones */ }
@media (min-width:481px) { /* portrait e-readers (Nook/Kindle), smaller tablets @ 600 or @ 640 wide. */ }
@media (min-width:641px) { /* portrait tablets, portrait iPad, landscape e-readers, landscape 800x480 or 854x480 phones */ }
@media (min-width:961px) { /* tablet, landscape iPad, lo-res laptops ands desktops */ }
@media (min-width:1025px) { /* big landscape tablets, laptops, and desktops */ }
@media (min-width:1281px) { /* hi-res laptops and desktops */ }

A: You can read more about Media queries and responsive design techniques here


text:
Q: Hfill not working
Hey fellas, look at the picture given above. I want (continued) to be completely left aligned, however, leftalign not working in tabularx (ltablex) env. for me, and hence I am using \hfill. Though hfill works to some extent, but doesn't yield a complete left alignment. Any solutions for modifying hill or any other solution to fix this? Thanks.
\documentclass{article}
\usepackage{ltablex}
\usepackage{threeparttable}
\usepackage{booktabs}

\title{Document}
\begin{document}
\maketitle

\begin{tabularx}{\textwidth}{Xc}
\toprule\toprule
Some random text & 1,75,650\\\midrule
\multicolumn{2}{l}{\textbf{Panel A1: AAA}} \\\midrule
Number of observations ... & 1,75,650\\
Delete: ... & (78,420)\\
Delete: ... & (7,104)\\
Final sample & 90,126\\
Delete: & (2,143)\\
Delete: & (8,345)\\
Final sample & 79,638\\\midrule
\multicolumn{2}{l}{\textbf{Panel A2: AAA}} \\\midrule
Number of observations & 79,638\\
Delete: & (39,540)\\
Delete: & (7,979) \\
Final sample & 32,119 \\\midrule
\multicolumn{2}{l}{\textbf{Panel B1: BBB }} \\\midrule
Number of observations  & 1,75,650\\
Delete: & (78,420)\\
Delete: & (47,136)\\
Delete: & (7,178)\\
Delete: & (32)\\
Delete: & (32)\\
Delete: & (32)\\
Delete: & (32)\\
Delete: & (32)\\
Delete: & (32)\\
Delete: & (32)\\
Delete: & (32)\\
Final sample & 42,884\\\midrule
\multicolumn{2}{l}{\textbf{Panel B2: BBB}} \\\midrule
Number of observations  & 1,75,650\\
Delete: & (78,420)\\
Delete: & (47,136)\\
Delete: & (7,178)\\
Delete: & (32)\\
Delete: & (32)\\
Delete: & (32)\\
Delete: & (32)\\
Delete: & (32)\\
Delete: & (32)\\
Delete: & (32)\\
Delete: & (32)\\
Number of observations  & 1,75,650\\
Delete: & (78,420)\\
Delete: & (47,136)\\
Delete: & (7,178)\\
Delete: & (32)\\
Delete: & (32)\\
Delete: & (32)\\
Delete: & (32)\\
Delete: & (32)\\
Delete: & (32)\\
Delete: & (32)\\
Delete: & (32)\\
Final sample & 42,884\\\midrule\bottomrule
\end{tabularx}

\end{document}

A: Since you speak of tabularx: in tabular environments, there's space before and after a column. You can remove it by inserting @{} in the corresponding place of the column definitions, such as:
\documentclass{article}
\usepackage{tabularx}
\begin{document}
\begin{tabularx}{4cm}{@{}Xr@{}}
\hline
Number & 42\\
\hline
\end{tabularx}
\end{document}

Similar, if you use \multicolumn:
\multicolumn{2}{@{}l}{...}

Your MWE becomes:

And in your case of the "Continued" line, use \multicolumn instead of \hfill:
\bottomrule\multicolumn{2}{@{}r@{}}{\small\textit{(Continued)}}\endfoot


text:
Q: Get value after some specific character in C# So I want to extract the value from a string the value will place at the right after my specific character in this case my specific character is - and will place at the right.
The string will look like this:
TEST-QWE-1
TEST/QWE-22
TEST@QWE-3
TEST-QWE-ASD-4

And from that string I want to extract
1
22
3
4

How I do that in C#? Thanks in advance

A: mystring.Substring(mystring.IndexOf("-") + 1)

Or use LastIndexOf in case there are other dashes before the last part:
mystring.Substring(mystring.LastIndexOf("-") + 1)

Substring: https://learn.microsoft.com/en-us/dotnet/api/system.string.substring?view=netframework-4.7.2
LastIndexOf: https://learn.microsoft.com/en-us/dotnet/api/system.string.lastindexof?view=netframework-4.7.2

A: I would suggest you to learn about Regex for string processing.
In your case a simple Regex pattern like [0-9]+$ would match your numbers.
Since you stated that the number is always to the right of your string you could also use string.Split('-').Last()

A: Use LastIndexOf to get the last occurrence of '-'
var p = str.LastIndexOf('-');
return p >= 0 && (p + 1 < str.Length) ? str.Substring(p + 1) : "";

A: You can use string.LastIndexOf() and string.Substring() to do that. And take care when the special character not occurred in your input.
string[] inputs = new string[]{
    "TEST-QWE-1",
    "TEST/QWE-22",
    "TEST@QWE-3",
    "TEST-QWE-ASD-4",
    "TEST-QWE-ASD-4",
    "TEST",
    "TEST-"
};
foreach(string input in inputs){
    int lastIdx = input.LastIndexOf("-");
    string output = lastIdx > -1 ? input.Substring(lastIdx + 1) : "";
    Console.WriteLine(input + " => " + output);
}
/* console outputs:
TEST-QWE-1 => 1
TEST/QWE-22 => 22
TEST@QWE-3 => 3
TEST-QWE-ASD-4 => 4
TEST-QWE-ASD-4 => 4
TEST =>
TEST- =>
*/

A: I will post another regex to capture what you want: -([^-]+)$
It's different from already posted, since it will capture everything except hyphen (with [^-]+) between hyphen (-) and end of a string ($ means end of a string).
The desired result will be stored in first cupturing group.
Code snippet:
var s = "TEST-QWE-1";
var match = Regex.Match(s, "-([^-]+)$");
if (match.Success)
  Console.WriteLine(match.Groups[1]);

Demo

A: You can use Regex, and this is the string you will need.
[^-]+$
Simply loop over each string you have.
var regex = new Regex(@"([^-]+$)");

regex.Matches(str);

A: You can use a simple Regex like (-\d+$)
You can as well use Split() and get the last element
"TEST-QWE-ASD-4".Split('-').Last();

A: The way to go is use the LastIndexOf method like this :
string input = "TEST-QWE-1";
var lastIndex = input.LastIndexOf("-");
var id = input.Substring(lastIndex + 1); // this is so you don't get the minus as well if you don't want it.

so, first we get the last index of the character we care about.
second, we perform a substring using this index to get the result we want


text:
Q: file_get_contents(URL) returns failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden I am Scrapping a website, Since data is TOO Much big, and I can't keep my Laptop always open, I am using RDP to scrap it.
Now they have blocked up my RDP IP so that I can't access that website, IF i install any VPN, Proxy Software (Since it changes my IP address), I would loose acces to my RDP, than I have to contact RDP PRovider to uninstall it so I am able to access RDP.
Is there any solution to access this website via RDP ? I came to know about Socks5, Website open fines when I use Socks5 with Mozilla it works fine but when I use localhost and run the script, I get file_get_contents(URL) returns failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden. since XAMPP sends HTTP requests via Network IP rather than browser IP.
Anyway to Overcome this problem ?

A: Try using cURL.
<?php

    $curl_handle=curl_init();
    curl_setopt($curl_handle, CURLOPT_URL,'http://###.##.##.##/mp/get?mpsrc=http://mybucket.s3.amazonaws.com/11111.mpg&mpaction=convert format=flv');
    curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
    curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Your application name');
    $query = curl_exec($curl_handle);
    curl_close($curl_handle);

    ?>


text:
Q: ESEUTIL.EXE version 8.3.106.1 I need to get a 32-bit version of the eseutil.exe (version 8.3.106.1) for the purposes of Microsoft DPM 2007 backing up an Exchange 2007 SP3 server.  I can't grab the one off of the Exchange server since it's 64-bit.  I downloaded the SP3 Exchange Management Tools (x86), but the version included is slightly older at 8.3.83.0.  Does anyone know where I can find this version?

A: One ridiculously convoluted option would be to install 32-bit Exchange on a system (the evaluation versions have a 32-bit installer available, even though it's unsupported), and patch it up to current; hopefully that should give you the correct eseutil.exe.

A: According to Microsoft here, ESEUtil should be a part of the Exchange 2007 Management Tools.
Be sure to update them to SP1/2/3 if your Exchange is SP1/2/3 as well.

A: Got it.  I downloaded the x86 version of KB2279665 which was an .msp file.  I then used the utility found here to extract the .cab's from the .msp.  At that point, I used 7-Zip to extract the eseutil.exe file that I needed for DPM.  It's x86 and it's version 8.3.106.1.  Phew!


text:
Q: More efficient/clever way to group/zip a multidimensional array in a particular manner I have a multidimensional array, which I don't know its size, what I do know is that each child will have the same length and same structure.
I need to concat the inner arrays of the first child with the inner arrays of its siblings so all the children same index inner arrays are in one array.
(If someone wants to phrase it a little bit better, or improve the title be my guest)
Example:
let arrays = [

    //1
    [[1, 2], [3, 4], [5, 6]],

    //2
    [[10, 20], [30, 40], [50, 60]],

    //3
    [[100, 200], [300, 400], [500, 600]],

    //N
    [[10000, 20000], [30000, 40000], [50000, 60000]],

];

Expected result:
[
    [1, 2, 10, 20, 100, 200, 10000, 20000],
    [3, 4, 30, 40, 300, 400, 30000, 40000],
    [5, 6, 50, 60, 500, 600, 50000, 60000]
]

Here is what I'm currently doing, which is working, but it's an overkill.
/**
*   Helper function
*   Will return all the values at ${index} of each array in ${arrays}
*   Example: index(1, [[1,2], [3,4]]); //[2, 4]
*/

function index(index, arrays){

    let results = [];

    for(let i = 0, len = arrays.length; i < len; i++)
        results.push(arrays[i][index]);

    return results;
}

let first = arrays.shift();
let output = first.map((item, i) => item.concat( ...index(i, arrays) ))

I'm looking for a more efficient way to do this, since it's running in a node server and also a more clever way (which doesn't have to be more efficient).
Note: I'm using node v7.8.0 so ES6 can be used.
UPDATE:
The spread operator is significantly slower than apply
So my code is much faster this way:
return first.map((item, i) => [].concat.apply(item, index(i, clone) ));

JSPERF:
I tested all the answers in this jsperf and @ibrahimMahrir way is clearly the fastest.

/**
*   Will return all the values at ${index} of each array in ${arrays}
*   Example: index(1, [[1,2], [3,4]]); //[2, 4]
*/

function index(index, arrays){

    let results = [];

    for(let i = 0, len = arrays.length; i < len; i++)
        results.push(arrays[i][index]);

    return results;
}

let arrays = [

 //1
 [[1, 2], [3, 4], [5, 6]],

 //2
 [[10, 20], [30, 40], [50, 60]],

 //3
 [[100, 200], [300, 400], [500, 600]],

 //N
 [[10000, 20000], [30000, 40000], [50000, 60000]],

];

let first = arrays.shift();
let output = first.map((item, i) => item.concat( ...index(i, arrays) ));

console.log(output);

A: This is a typical reducing job with mapping. You may do as follows;

var arrs = [[[1, 2], [3, 4], [5, 6]], [[10, 20], [30, 40], [50, 60]], [[100, 200], [300, 400], [500, 600]], [[10000, 20000], [30000, 40000], [50000, 60000]]],
    res  = arrs.reduce((p,c) => p.map((s,i) => s.concat(c[i])));
console.log(res);

A: Using reduce and its sisters come at a cost in performance. Using basic for loops is not the prettiest you get, but surely is faster.

function group(arrays){

    let results = [],
        len = arrays.length;

    if(!len) return results; // if this line is not necessary then remove it

    let i, j, k,
        innerLen = arrays[0].length;

    for(j = 0; j < innerLen; j++) {
        let arr = [];
        for(i = 0; i < len; i++)
            for(k = 0; k < arrays[i][j].length; k++) // assuming the last level of arrays could be of different lengths
                arr.push(arrays[i][j][k]);
        results.push(arr);
    }

    return results;
}

let arrays = [[[1,2],[3,4],[5,6]],[[10,20],[30,40],[50,60]],[[100,200],[300,400],[500,600]],[[10000,20000],[30000,40000],[50000,60000]]];
console.log(group(arrays));

A: Here is my attempt at a readable approach, based on decomposing the operation using zip and flatten utility methods:

let arrays = [
    //1
    [[1, 2], [3, 4], [5, 6]],
    //2
    [[10, 20], [30, 40], [50, 60]],
    //3
    [[100, 200], [300, 400], [500, 600]],
    //N
    [[10000, 20000], [30000, 40000], [50000, 60000]],
]

// from http://stackoverflow.com/a/10284006/7256039
const zip = a => a[0].map((_,i) => a.map(e => e[i]))

const flatten = a => [].concat(...a)

let result = zip(arrays).map(flatten)

console.log(result)
.as-console-wrapper { min-height: 100%; }

Here is the fastest inline/for-loop version I can come up with while still not sacrificing too much readability:

let arrays = [
    //1
    [[1, 2], [3, 4], [5, 6]],
    //2
    [[10, 20], [30, 40], [50, 60]],
    //3
    [[100, 200], [300, 400], [500, 600]],
    //N
    [[10000, 20000], [30000, 40000], [50000, 60000]],
]

function zipMapFlatten (a) {
  const result = [], rows = a.length, cols = a[0].length
  let i, j, e
  for (j = 0; j < cols; j++) {
    result.push(e = [])
    for (i = 0; i < rows; i++) e.push.apply(e, a[i][j])
  }
  return result
}

let result = zipMapFlatten(arrays)

console.log(result)
.as-console-wrapper { min-height: 100%; }


text:
Q: unreported exception StackEmptyException; must be caught or declared to be thrown I'm not able to figure out why the push() and pop() methods of this code are no longer working (are the exceptions declared properly?).  Thanks in advance for the help.
Here is the code:
/*
* From Schildt's Java: A Beginner's Guide, 6th ed.
* Page 628-629, 637-638
*/

// An exception for stack-full errors
class StackFullException extends Exception {
  int size;

  StackFullException(int s){
    size = s;
  }

  public String toString(){
    return "\nStack is full.  Maximum size is " + size;
  }
}// end StackFullException

// An exception for stack-empty errors
class StackEmptyException extends Exception {
  public String toString(){
    return "\nStack is empty.";
  }
}// end StackEmptyException

// A stack class for characters
class Stack {
  private char stack[]; // this array holds the stack
  private int tos; // top of stack

  // Construct an empty Stack given its size
  Stack(int size){
    stack = new char[size]; // allocate memory for stack
    tos = 0;
  }

  // Construct a Stack from a Stack
  Stack (Stack ob){
    tos = ob.tos;
    stack = new char [ob.stack.length];

    // copy elements
    for (int i=0; i < tos; i++){
      stack[i] = ob.stack[i];
    }
  }

  // Construct a stack with initial values
  Stack(char a[]){
    stack = new char[a.length];

    for (int i = 0; i < a.length; i++){
      try {
        push(a[i]);
      }
      catch(StackFullException exc){
        System.out.println(exc);
      }
    }
  }

  // Push characters onto the stack
  void push(char ch) throws StackFullException{
    if (tos == stack.length){
      throw new StackFullException(stack.length);
    }

    stack[tos] = ch;
    tos++;
  }

  // Pop a character from the stack
  char pop() throws StackEmptyException{
    if (tos == 0){
      throw new StackEmptyException();
    }

    tos--;
    return stack[tos];
  }
} // end Stack

// Demonstrate the Stack Class
public class StackDemo {
  public static void main(String args[]){

      // construct a 10-element empty stack
      Stack stack1 = new Stack(10);

      char name[] = {'B', 'r', 'a', 'd'};

      // construct stack from array
      Stack stack2 = new Stack(name);

      char ch = 0;
      int i;

      // put some characters into stack1
      for (i=0; i < 10; i++){
        stack1.push((char)('1' + i));
      }

      // construct stack from another stack
      Stack stack3 = new Stack(stack1);

      System.out.println();

      // show the stacks
      System.out.printf("Contents of stack1: ");
      for (i=0; i < 10; i++){
        ch = stack1.pop();
        System.out.print(ch);
      }

      System.out.println("\n");

      System.out.printf("Contents of stack2: ");
      for (i=0; i< 4; i++){
        ch = stack2.pop();
        System.out.print(ch);
      }

      System.out.println("\n");

      System.out.printf("Contents of stack3: ");
      for(i=0; i < 10; i++){
        ch = stack3.pop();
        System.out.print(ch);
      }

      System.out.println("\n");
  } // end main
} // end StackDemo

I know I'm a bit of a noob, and I really did try to figure this out on my own, so please be patient with your answers.

A: If a method throws an exception ,the caller of the method should catch the exception or throw it further.
In your case the push and pop function throws  StackFullException and StackEmptyException respectively.So the caller (main method) should catch those exceptions or throw it further.
public static void main(String args[]) throws StackFullException ,StackEmptyException
{
}

or surround the push and pop functions in a try catch block
try
{
ch = stack1.pop();
}
catch(StackEmptyException  e)
{
}


text:
Q: ¿Cómo cargar un select con datos específicos de dos consultas? En un formulario el cual lo estoy haciendo para editar los datos, estoy realizando una consulta y obtengo los datos de un item utilizando un where
$query = "SELECT prod.descripcion_producto, prod.precio, prod.disponible, prod.path_foto, prod.destacado, prod.nuevo, cat.descripcion_categoria, prod.id_categoria, subcat.descripcion_subcategoria, prod.id_subcategoria
                  FROM producto AS prod
                  INNER JOIN categoria AS cat
                    ON prod.id_categoria = cat.id_categoria
                  INNER JOIN subcategoria AS subcat
                    ON prod.id_subcategoria = subcat.id_subcategoria
                  WHERE prod.id_producto = '$id'";

Los datos que utilizo para poner en un select son id_categoria y descripcion_categoria
los cuales son guardados en variables para despues especificarlos en el <option> y en el html tengo lo siguiente:

     Categoría

         <select id="categoria" name="categoria">
             <option value="<?php echo $idCat.','.$nomCat; ?>" ><?php echo $nomCat; ?></option>
         </select>

En otro formulario el cual es de creación lo cargo de la siguiente manera:
<select id="categoria" name="categoria">
    <?php
    $query1 = mysqli_query($con,"SELECT id_categoria, descripcion_categoria FROM categoria WHERE habilitado = '1'");
    while ($cat = mysqli_fetch_array($query1)) {
        //echo $cat;
    ?>
    <option value="<?php echo $cat['id_categoria'].','.$cat['descripcion_categoria'] ?>" ><?php echo $cat['descripcion_categoria'] ?></option>
    <?php
    }
    ?>
</select>

En sí, mi idea como estoy en el formulario en el que edito los valores es la de mostrar los datos que han sido guardados previamente, sin embargo, me gustaría cargar también todos los datos que se obtiene en la tabla categoría.
¿De que manera puedo hacer que se carguen todos los datos pero que primero se muestre los datos que pertenecen al item que ha sido seleccionado?


text:
Q: Posicionamento dos scripts e links css num documento html Sempre coloquei os scripts e os links ao CSS na parte superior do documento no head do documento. Agora percebo que há um outro conceito em que as chamadas aos scripts e CSS, ficam na parte inferior do documento html, nas últimas linhas do body.
Há uma razão para isso? Um colega meu me deu uma explicação há tempos, mas não lembro do todo. É melhor mesmo? Tem vantagens técnicas? Gostaria de saber a respeito.

A: A tag

        <link rel="stylesheet" type="text/css" href="styles.css">

Hello world!

Ainda que esse código possa parecer inócuo, ele apresenta um problema de desempenho grave: há três arquivos JavaScript sendo carregados no head. Uma vez que cada tag script impede que a página continue a ser renderizada até que o código JavaScript carregue e execute totalmente, o desempenho aparente dessa página será penalizado. Tenha em mente que navegadores não começam a renderizar nada na página até que a tag body de abertura seja encontrada. Colocar scripts no topo da página desse modo geralmente leva a uma demora perceptível, muitas vezes na forma de uma página vazia em branco, antes que o usuário possa começar a ler e interagir com o documento.
Exemplo do posicionamento recomendado do script

      <title>Script Example</title>
      <link rel="stylesheet" type="text/css" href="styles.css">

Hello world!

     <-- Exemplo do posicionamento recomendado do script -->

Uma vez que os scripts bloqueiam o download de todos os tipos de recursos da página, é recomendado que todas as tags script sejam posicionadas o mais próximo possível do fim da tag body para que não afetem o download da página.
Para mais informações o sobre posicionamento de js e css. Veja: https://novatec.com.br/livros/javascriptdesemp/capitulo9788575222416.pdf


text:
Q: Need to import a key and value from the file in same directory path/
  file_name.py
  main.py

file_name.py contains below code only
{ 'app_name':'NTorq'}

and nothing else
now how do i access app_name in my main.py file

A: The python file you described only contains data, so there is no need to be a python file.
Coincidentally the JSON file format has a similar syntax for dictionaries and lists as Python. That means that
{"app_name":"ntorq"}

is valid by the rules of both format.
I suggest you rename it to name_file.json just to be clear about the purpose of the file.
After read it with the json module.
import json
name = json.load(open('name_file.json'))['app_name']

A: If file_name.py contains only { 'app_name':'NTorq'}, That's JSON file, not a python file.
And if you want to read the app_name.py and convert it to JSON, you should follow Handras' answer.
Or you can make your data in file_name.py to a variable.
For example,
file_name.py
foo = {'app_name':'NTorq'}

And then import it.
main.py
from file_name import foo
print(foo["app_name"])

output
NTorq


text:
Q: DART: How to setup Gerrit/Jenkins? to setup a gated checkin, we would like to use Gerrit and Jenkins. We have experience about how to do this with JavaScript, but Dart is completely new to us.
So far I haven't seen a dart plugin for Jenkins for central build and triggering the code checks. How do you guys setup the systems to allow both code checks and central build?
Thanks

A: You can use https://drone.io to automatically build dart projects on push to github pretty seamlessly.
I haven't done it with Jenkins yet but I know you can set Jenkins to watch for changes on a git or hg repo then run a script build. A script would just need dart/bin on the path to run pub build
A plugin would just be for the dart build part which is that fairly simple script or a hop task runner script so it's probably just hasn't been a big deal to make a Jenkins plugin.


text:
Q: Unable to deploy node image(NestJS) on AWS Elastic beanstalk I am literally new with AWS as well and Containerization technology. What I am trying to achieve is that deploying a node image to AWS.
AS I am working with NESTJS my main.ts bootstrap method
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.setGlobalPrefix('api/v1');
  await app.listen(5000);
  Logger.log(`Server is running on port ${port}`, "Bootstrap");
}
bootstrap();

I am also using Travis CI to ship my container to AWS
My Docker file
# Download base image
FROM node:alpine as builder

# Define Base Directory
WORKDIR /usr/app/Api

# Copy and restore packages
COPY ./package*.json ./
RUN npm install

# Copy all other directories
COPY ./ ./

# Setup base command
CMD ["npm", "run", "start"]

MY .travis.yml file --> which is the config of Travis CI
sudo: required
services:
    - docker

branches:
    only:
        - master

before_install:
    - docker build -t xx/api .

script:
    - docker run xx/api npm run test

deploy:
    provider: elasticbeanstalk
    region: "us-east-2"
    app: "api"
    env: "api-env"
    bucket_name: "name"
    bucket_path: "api"
    on:
        branch: master
    access_key_id: "$AWS_ACCESS_KEY"
    secret_access_key: "$AWS_SECRET_KEY"

Every time code pushed from Travis CI my Elastic beanstalk start building and failed.
So, I start googling to solve the issue. What I could is that I need to expose port using NGINX. Expost 80 PORT
FROM Nginx
EXPOSE 80
COPY --from=builder /app/build /usr/share/nginx/html

My question is how should I incorporate NGINX to my docker file? AS my application is not something static content. If I move all my build artefacts to /usr/share/nginx/html. This will simply not work as I am not serving static content. So What I need is that I simultaneously run my server to server node app as well as run another container with NGINX which will export 80 port and proxy my requests.
How should I do that? Any help?


text:
Q: Using Docker YML file with context to parent (..) takes too long to build under WSL2 I have this folder structure
folder_ext
folder_docker
       |---> folder_int
folder_1
folder_2
.......

My docker files are all included inside the folder_docker. Inside my docker-compose.yml file, I set the context like this
version: '3'
services:
  nginx:
    container_name: my_nginx
    build:
      context: ..
      dockerfile: ./folder_docker/nginx/Dockerfile

Inside the Dockerfile I copy some files from folder_ext
COPY ./folder_ext /container_folder_ext
but somewhere below I copy also files from folder_docker/nginx/nginx.tmp
COPY ./folder_docker/nginx/nginx.tmpl /etc/nginx/conf.d/nginx.tmpl
I am using also .dockeringore to ignore folders & files that I am not using.
Unfortunately, this takes too long under WSL2 (Ubuntu distro) to begin the building process about ~45 minutes before it starts to process the 1st command inside the Dockerfile. I don't know why, but that's is a huge problem for me since I want to make many builds and I am losing my time with this stall.
If I use an alternative scenario like this below, where context is set inside the folder_ext,
version: '3'
services:
  nginx:
    container_name: my_nginx
    build:
      context: ../folder_ext
      dockerfile: ../folder_docker/nginx/Dockerfile

the build begins almost instantly (~2 seconds) BUT I get an error "docker forbidden path outside the build context" for the 2nd COPY
COPY ../folder_docker/nginx/nginx.tmpl /etc/nginx/conf.d/nginx.tmpl
I don't want to move my folder infrastructure just to make it build faster because it's a git project that follows this folder structure. This seems to be a WSL2/Windows problem since under the production server the building times are acceptable.
Any other solution?

A: It seems that the .dockeringore files inside the subfolders are IGNORED.
The original .dockeringnore file in the parent was like that.
.git
node_modules
build

Inside each parent folder like folder_ext, folder_1, folder_2 etc have also their own .dockerignore files for their subfolders like this
node_modules
build
discard

It seems that docker-compose takes in mind only the 1st .dockeringone file that lives in the parent directory according to context.
I fixed the problem with the following. I used only one .dockeringore file that exists in the parent folder and deleted all subfolder's .dockerignore. Then I changed the exclusions of the one and only parent .dockeringore file like this.
.git
node_modules
build
folder_ext/node_modules
folder_ext/build
folder_1/node_modules
folder_1/build
folder_1/discard
folder_2/node_modules
folder_2/build
folder_2/discard


text:
Q: No provisioning profile option under build settings I am using Xcode 6.3.1 and surprisingly two of the projects i created with it does not have any provisioning profile option under the build settings. All the other projects i created have this option. The deployment target is also ios 8.3

A: Try changing the toggle from "Basic" to "All" in the bar to the left of the search input box.  I'm not sure how you are getting the view that you have, but If you change it to "All", you should see every option and hopefully it will show up.


text:
Q: seaborn violin plot for single column splitting by a categorical column I have a dataframe that looks like this:
    num_column    is_train
    30.75               1
    12.05               1
    ..                 ..
    43.79               0
    15.35               0

I want to see the distribution of num_column using a violin plot and with each side(or split) of the violin showing the data for each of my two categories in is_train column.
From the examples in documentation, here's what I could come up with:
import seaborn as sns
sns.violinplot(x=merged_data.loc[:,'num_column'], hue=merged_data.loc[:,'is_train'], split=True)

From the result of this, I could see that the arguments hue and split had no effect at all. Meaning sides of the violin weren't split and I couldn't see any legend, so I presumed hue argument had no effect.
I am trying to compare distributions of a column from my train and test data.

A: The split= argument is to be used with hue-nesting, which can only be used if you already have an x= argument. Therefore you need to provide columns for both x (should be the same value for both datasets) and hue (coded depending on the dataset):
merged_data['dummy'] = 0
sns.violinplot(data=merged_data, y='num_column', split=True, hue='is_train', x='dummy')

A: You can use the x= parameter to create multiple violins. The hue and split parameters are used when a differentiation via a third column is needed.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

merged_data = pd.DataFrame({'num_column': 20 + np.random.randn(1000).cumsum(),
                            'is_train': np.repeat([0, 1], 500)})
sns.violinplot(data=merged_data, x='is_train', y='num_column')
plt.show()


text:
Q: Invoking java functions from RASCAL can I invoke Java functions from Rascal. I want to write RASCAL analyser, but want access CFG nodes by calling a java function. Is this possible in Rascal. To put it simply, can I wrap the existing java application and invoke it from RASCAL

A: Sure. It works as follows.

*

*Treat your Rascal project in Eclipse as a Java project as well.

*Add source code and libraries and make the stuff compile.

*Learn about the pdb.values API (in particular IValueFactory)

*In Rascal write something like this:

    @javaClass{com.mypackage.MyClass}
    java int myFunction(str arg);

*

*Then in Java:

     package com.mypackage;
     public class MyClass {
        private final IValueFactor vf;
        public MyClass(IValueFactory vf) {
          this.vf = vf;
        }
        IValue myFunction(IString x) {
           return vf.integer(-1);
        }
     }


text:
Q: In Swift is there anyway to know which object was swiped? I want to pass the sender redBox to the function leftSwipeFunc. I don't know how to pass a parameter that's not UISwipeGestureREcognizer. Please help me if you know the answer.
let swipeLeft = UISwipeGestureRecognizer(target: self, action: Selector("leftSwipeFunc:"))
swipeLeft.direction = UISwipeGestureRecognizerDirection.Left
redBox.addGestureRecognizer(swipeLeft)

func leftSwipeFunc(gesture:UISwipeGestureRecognizer){ }

A: Gesture recognizers have a property called view that is the UIView that they are attached to.  So, you can use that inside of leftSwipeFunc to get the view:
func leftSwipeFunc(gesture: UISwipeGestureRecognizer) {
    let swipedView = gesture.view

    // Assuming redBox is a property of your view controller
    if swipedView == redBox {
        println("the redBox was swiped")
    } else {
        println("some other view was swiped")
    }
}

A: You can find the location of the swipe in your view using locationInView.
In your leftSwipeFunc, find the CGPoint of the touch and check if it is in the required view.
let location = gesture.locationInView(self.view)

if CGRectContainsPoint(redBox, location) {
    // redBox was swiped, do something
}


text:
Q: Moving data from a database to Google Big Query I am trying to figure out a way to move data in batches(not streamed in) from on-prem database (Oracle) to Google Bigquery.
I am trying to do this via Google Cloud Composer however I understand that I need to get data into GCS first before I can use composer to move it to BigQuery.
What is the best way to move data from on-prem DB to GCS. or is there a service in Google cloud that allows me to move data directly from the DB to Bigquery?
Can this be better done with Cloud Dataflow instead? Thank you

A: So I think you are mixing a little bit tools/services with the main goal that is the migration. So before anything I'm going to explain some concepts:
1) Cloud Composer is just a GCP product that provide Airflow as Service, and what is Airflow? an orchestration platform where you can programmatically author, schedule and monitor workflows. Therefore, this is useful once you have multiple pipelines, jobs or task to orchestrate. It could be used for the initial migration, but is not necessary a mandatory service to be used.
2) DataFlow is a great product from GCP, that uses Apache Beam as its main pipelining language, so you can deploy batch or stream pipelines. Dataflow is the alternative of classic products/frameworks such as Spark or Hadoop if you want to have a more Cloud Native experience in GCP. The next image it's the recommendation about when to use DataProc (Spark, Hadoop, etc as a service) or Dataflow:

Now that we understand the terms here it comes the answer: It depends. So these services can help you in the process but each infrastructure is quite unique. For instance:

*

*Can we stop services and make the migration? Or should it happen with the database accepting requests?

*How long it should take? max time?

*It's your DB behind firewalls? VPN could affect?

*It is a lift and shift approach? I mean, are you going to copy paste directly or is there going to be data refactoring to use BigQuery in the proper way?

So as you can see it depends a little bit from your needs and current infrastructure. However, I'm going to tell you what we did in our company:
In my case I kind of made both approaches: Lift&Shift and Data Refactoring. The reason fo doing that was to provide the business with something to query, while we were busy refactoring the data architecture. The way that we did the first one was moving just as it is the tables from our MSSQL database to BigQuery. The solution was a set of python scripts to copy the schemas and recreate the tables on the other side (table by table in small batches).
Note: This process could be done using DataFlow for instance, however if your DB is behind Firewalls and it requires VPN access and so on, you will have a bad time trying to make it work.
The suggested way by Google is to make dump of your tables in GCS and then you can reconstruct them using the create table from source option in BigQuery (that it behaves similar as Athena in AWS). However, keep in mind that BigQuery just recognises Avro, parquet, JSON, CSV and ORC formats. Meaning that your DB dump should export in one of these formats. If you use something like JSON or CSV, Google BigQuery is smart enough to auto detect your schema, nevertheless!!! it's not perfect and it will make a lot of assumptions based on the first 100 rows. If you use avro or parquet, the schema will be defined by those files, so you will reduce the risk of false positives.
Note: In the case of Oracle you can "export" to CSV or JSON using something like this https://blogs.oracle.com/opal/fast-generation-of-csv-and-json-from-oracle-database
So in general there are plenty options to tackle this issue and also a lot of things to consider. This is a document from google about migration from TeraData to BigQuery, but in general it works for any other kind of migration:
https://cloud.google.com/solutions/migration/td2bq/td-bq-migration-overview
Good luck!

A: You can schedule your data migrations to GCS outside of Cloud Composer. Then create a DAG with GoogleCloudStorageObjectSensor which pokes GCS in intervals to check if the file arrives. Then you can copy your data to BigQuery with GCSToBigQueryOperator.


text:
Q: Как "заремарить" строки в xml разметке? Можно ли "заремарить" строки в xml разметке?
Если да, то как?

A: Комментарии начинаются с группы символов <!-- и заканчиваются группой символов -->: например, <!--catalog last updated 2000-11-01-->.

A: Быстрые клавиши:
выделить всё, что необходимо закомментить, и нажать shift+ctrl+/


text:
Q: Automatically generating a CRUD webui I'd like to generate a web editor for several tables in an internal database. There is no need for security.
Is there a C# library that can do this? In python I would probably use Django Admin pages or web2py. However I'd really prefer a .NET option in this case

A: you could use scaffolding in ASP.Net MVC to generate the web views and have Entity framework to generate the ORM (data access) layer for you.  I am not sure if there is one library which does that for you. Hope this helps.


text:
Q: Deploy Docker Image With Github Action I have a Github Action which consist to tag, build and deploy a docker image.
When there is a pull request I just do the build job with this file: build.yml
# This is a basic workflow to help you get started with Actions

name: Build

# Controls when the action will run. Triggers the workflow on push or pull request
# events but only for the master branch
on:
  pull_request:
    branches: [ master ]

# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
  docker:
    # The type of runner that the job will run on
    runs-on: ubuntu-latest
    env:
      DOCKERHUB_REPOSITORY: ${{ secrets.DOCKERHUB_REPOSITORY }}

    # Steps represent a sequence of tasks that will be executed as part of the job
    steps:
      # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
      - uses: actions/checkout@v2

      - name: docker build
        run: | # Tag the image with the commit hash
          docker build -t $DOCKERHUB_REPOSITORY .
          docker tag $DOCKERHUB_REPOSITORY:latest $DOCKERHUB_REPOSITORY:$(git log -1 --pretty=%h)

And for the deployment I have to build and deploy with this file: deploy.yml
# This is a basic workflow to help you get started with Actions

name: Deploy

# Controls when the action will run. Triggers the workflow on push or pull request
# events but only for the master branch
on:
  push:
    branches: [ master ]

# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
  docker:
    # The type of runner that the job will run on
    runs-on: ubuntu-latest
    env:
      DOCKERHUB_REPOSITORY: ${{ secrets.DOCKERHUB_REPOSITORY }}

    # Steps represent a sequence of tasks that will be executed as part of the job
    steps:
      # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
      - uses: actions/checkout@v2

      - name: docker login
        env:
          DOCKERHUB_USER: ${{ secrets.DOCKERHUB_USER }}
          DOCKERHUB_ACCESS_TOKEN: ${{ secrets.DOCKERHUB_ACCESS_TOKEN }}
        run: |
          docker login -u $DOCKERHUB_USER -p $DOCKERHUB_ACCESS_TOKEN

      - name: docker build
        run: | # Tag the image with the commit hash
          docker build -t $DOCKERHUB_REPOSITORY .
          docker tag $DOCKERHUB_REPOSITORY:latest $DOCKERHUB_REPOSITORY:$(git log -1 --pretty=%h)

      - name: docker push
        run: |
          docker push $DOCKERHUB_REPOSITORY

For me there is a repetition with the build section but I did not found how can I use a dependency in jobs on different files. It is not working.
How can I tell github action that the deploy section depends on the build ?, with 2 different files.
link: https://docs.github.com/en/free-pro-team@latest/actions/learn-github-actions/managing-complex-workflows#creating-dependent-jobs

A: You can merge them into one CI/CD pipeline. This should be triggered by both pushes and pull_requests in master. This has several advantages;

*

*If the build fails, the pipeline is automatically aborted
(to be absolutely sure, you can add if: ${{ success() }}!

*No duplicate steps, docker build is only defined once.

*Steps can still only be performed on a push or pull_request by using conditions:

if: ${{ github.event_name == 'push' }} // OR
if: ${{ github.event_name == 'pull_request' }}

*

*Fewer pipelines to maintain!


text:
Q: Android studio use camera to make a photo vs load photo from storage I am working on an Android app functionality where I click a button and get the choice to make a photo with the camera or to load a photo from storage.
For making a photo I am using the command
myBitmap = (Bitmap) data.getExtras().get("data");

For loading from storage I am using the comman
myBitmap = BitmapFactory.decodeFile(PATH);

Now I am trying the following: first I choose to make a photo and display it, then I choose from storage but I choose the photo I just made before and display it. In both cases I resize to 200x200 before displaying.
However the results look very different. Probably in one case nearest neighboor downsampling is used and in the other linear downsampling is used. However I don't find proper documentation.
How can I find out what downsampling is used and change it so that in both cases the same is used and the image displays looks the same?
Thank you.
P.S.: in case of decodeFile I found that options can be provided to the command however no idea which kind of options.


text:
Q: Add action to action bar panel I want to add an action to the action bar, but it appears in my action bar as a drop down list.
How can I add button to the action bar?
My code is:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/action_search"
      android:icon="@drawable/ic_action_search"
      android:title="Add"
      showAsAction="ifRoom"/>
</menu>

  @Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    return super.onCreateOptionsMenu(menu);
}

A: If you are using android.app.Activity simply change showAsAction="always" to "android:showAsAction="always".
If you are using android.support.v7.app.Activity change the code as follows:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">

    <item android:id="@+id/action_search"
        android:icon="@drawable/ic_action_search"
        android:title="Add"
        app:showAsAction="ifRoom"/>
</menu>

A: You just simply add the one more item into menu and inflate that menu into your activity ....
        like below you will add your button and access that button into your activity...
    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android" >

        <item
            android:id="@+id/refresh"
            android:icon="@android:drawable/stat_notify_sync"
            showAsAction="ifRoom"/>
        <item
            android:id="@+id/action_bar_button_cancel"
            android:focusableInTouchMode="true"
            android:icon="@android:drawable/ic_menu_close_clear_cancel"
            showAsAction="ifRoom"/>

    </menu>

Inflating the menu like below.....
  @Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    return super.onCreateOptionsMenu(menu);
}

Accessing method in action bar item is....
@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.refresh:
                          //logic
            return true;
                case R.id.action_bar_button_cancel:
                          //logic
                       return true;

        default:
            return super.onOptionsItemSelected(item);
        }
    }

that's if you have any doubt comment


text:
Q: VLC silent install over Powershell I'm trying to install the VLC media player using a PowerShell script.
I opened the VLC wiki and found this (that's the only help I found online):
Start process -FilePath "C: \ Temp \ VLC.exe" -ArgumentList "/ L = 1033 / S"
When I run this command I don't get an error, but I have to accept the Windows admin thing and that's it. VLC cannot be installed.

A: This can be done without powershell.  I'm not sure why people jump so often to start-process.  I guess it won't work if you quote the command.  It can be run directly:
.\vlc-3.0.11-win32.exe /L=1033 /S

Msi version:
install-package vlc-3.0.16-win64.msi

Default preferences file for ignoring update prompts, etc.  copy-item overwrites without a confirmation.
copy-item vlcrc C:\Users\Default\AppData\Roaming\vlc

A: I would suggest to install software using Chocolatey. This is very simple, it's PowerShell based and consists in only 1 command line (but first you need to install Chocolatey):
choco install vlc

And it's very easy to update installed software as well.


text:
Q: td valign="top" not working - CSS overriding somewhere ANSWERED!
I have some css overriding my tables but I don't know how to find it. I simply need images in my table to be at the top of the table. I use the code:

But it does not work and produces this image of the orange bar in the middle. It should be at the top at the same height as "INSPIRE".

Here is the link to my full code: FULL CODE
Can anyone see why my valign="top" is not working? Is there anything to override the css?

A: Your td originally has vertical-align: middle specified inside the CSS. You can override it by using style="vertical-align: top;" inline inside the  tag containing your image. This should work perfectly:

A: This CSS rule is overriding it:
table, th, td {
    vertical-align: middle;
}

Change it to top or add another class to that specific td tag.
Also you could add style tag to that td as follows:
style="vertical-align: top;"


text:
Q: Individual Hub onDisconnect I have 1 SignalR connection and 2 Hubs, ChatHub & OnlineHub.
I have been researching on how to OnConnect & OnDisconnect for each Hub.
Currently when I start a connection to server, both ChatHub and OnlineHub 's will run their OnConnected(). Is there anyway I can separate them?
$.connection.hub.url = chatHubUrl;
var chat = $.connection.ChatHub;
var onlinehub = $.connection.OnlineHub;

$.connection.hub.start({ withCredentials: false }).done(function () {
    onlinehub.server.connectGlobalConnection(userId, token).done(function () {});
});

[HubName("OnlineHub")]
public class OnlineHub : Hub
{
    public override Task OnConnected()
    {
        Groups.Add(Context.ConnectionId, "Online");
        return base.OnConnected();
    }
}

[HubName("ChatHub")]
public class ChatHub : Hub
{
    public override Task OnConnected()
    {
        return base.OnConnected();
    }
}

What I am asking was, can each hub act as a single connection?
Let's say ChatHub from URL-Chat, OnlineHub from URL-Online.
So I can easily detect their OnConnect & OnDisconnect

A: No. See the relevant docs here.
Specifically:

You can define multiple Hub classes in an application. When you do
  that, the connection is shared but groups are separate.


text:
Q: Tooling API - unable to figure out how create method is invoked I am trying to understand tooling API - SOAP and was trying to create a simple Java class which uses tooling wsdl file to create Apex class. I borrowed the snippet from https://developer.salesforce.com/docs/atlas.en-us.api_tooling.meta/api_tooling/intro_soap_overview.htm
but I am unable to figure out which object needs to be invoked to utilize create method to create new classes:
// call create() to add the class
SaveResult[] saveResults = sforce.create(classes);
I tried creating SforceService sforce; but it seems to be not available. I have included wsc-22.jar and created enterprise.jar from enterprise wsdl, toolingApi.jar from tooling wsdl.

A: If you are using Tooling API via SOAP then public SaveResult[] create(SObject[] sObjects) method lives in com.sforce.soap.tooling.ToolingConnection class.
If you do not see it then this may relate to the ancient version of wsc (v22) you used or old version of Tooling WSDL.
NOTE:
not sure if it has been fixed in the current Tooling API (v34), but in the past in order to use com.sforce.soap.tooling.ToolingConnection you had to establish Enterprise (or Partner) SOAP connection first and then use returned session Id and endpoint (adjusted for tooling API) to call Tooling API via ToolingConnection.


text:
Q: Webrtc not connecting on different network even on TURN I am using RTCmulticonnection in one of my project everything works fine except it is not working on different networks. I Have gone through Github issue which state that it needs turn server to run it on different networks. but i already configured turn server according to the documentation.
here is my code
<script src="https://rtcmulticonnection.herokuapp.com/dist/RTCMultiConnection.min.js"></script>
<script src="https://rtcmulticonnection.herokuapp.com/socket.io/socket.io.js"></script>

<script>
var connection = new RTCMultiConnection();

// this line is VERY_important
connection.socketURL = 'https://rtcmulticonnection.herokuapp.com:443/';

// if you want audio+video conferencing
connection.session = {
    audio: true,
    video: true
};

// first step, ignore default STUN+TURN servers
connection.iceServers = [];

// second step, set STUN url
connection.iceServers.push({
    urls: 'stun:mydimain.com:3478'
});

// last step, set TURN url (recommended)
connection.iceServers.push({
    urls: 'turn:mydimain.com:3478',
    credential: 'mypassword',
    username: 'myusername'
});

connection.openOrJoin('this-is-your-room-id');
</script>

upon checking the console in chrome it won't show any error but in Firefox i get the following error...

ICE failed, your TURN server appears to be broken, see about:webrtc for more details.

I have tested my turn server in Trickle ICE. i am getting response and relay which means turn and stun working fine. i also checked connectivity in this snippet which shows

Yep, the TURN server works...

When ever the client initiate the session, I can connect to him and after a few (2-3)minutes it get disconnected. But when I initiate the session it won't get connected with client.
for testing purpose may be you can use this i got this from Github
// second step, set STUN url
    connection.iceServers.push({
        urls: 'stun:numb.viagenie.ca'
    });

    // last step, set TURN url (recommended)
    connection.iceServers.push({
        urls: 'turn:numb.viagenie.ca',
        credential: 'muazkh',
        username: 'webrtc@live.com'
    });

Getting the following error in WEBRTC-internals icecandidateerror
url: turns:mydimain.com:5349?transport=tcp
address: xxx.xxx.xx.x
port: 63612
host_candidate: address: xxx.xxx.xx.x:63612
error_text: Address not associated with the desired network interface.
error_code: 600

now what am i doing wrong? any help would be greatly appreciated.
Thanks


text:
Q: Removing currency character from NumberFormat format() Am trying to remove the currency character after formatting the currency using NumberFormat
import java.text.NumberFormat;

BigDecimal currencyAmount = new BigDecimal(9876543.21)
def currentLocale = Locale.US
def currencyFormatter = NumberFormat.getCurrencyInstance(currentLocale);

println "formatted currency = "+currencyFormatter.format(currencyAmount)

This prints $9,876,543.21 but I dont want $ or any currency character in the formatted currency. Is there anyway to do it?

A: Groovy Solution:
import java.text.NumberFormat

def currencyAmount = 9876543.21 //Default is BigDecimal
def currencyFormatter = NumberFormat.getInstance( Locale.US )

assert currencyFormatter.format( currencyAmount ) == "9,876,543.21"

Don't need getCurrencyInstance() if currency is not requried.


text:
Q: Update rows in DataGridView I am trying to update my DataGridView. I can just only update one row but when i try to update two rows they give me a error:

"Violation of PRIMARY KEY constraint "

string strPRSconn = ConfigurationManager.ConnectionStrings["POSdb"].ConnectionString;
        string date = dt_date.Value.ToString("yyyy-MM-dd");
        var counter = 1;
            SqlConnection sc = new SqlConnection(strPRSconn);
            sc.Open();
            counter++;
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {

            if (!row.IsNewRow)
            {

                    string strQry = "UPDATE CounterChecking "+
                    "SET part_no = @c0,po_no = @po_no,invoice = @invoice,part_name = @c1,"+
                    "date = @date,color = @c2,qty_ordered = @c3,qty_for_delivery = @c4,qty_recieved = @c5,"+
                    "variance = @c6,unit_price = @c7, total = @c8, remarks = @c9 "+
                    "WHERE po_no= '" + cb_po_search.Text + "'";
                    SqlCommand scmd = new SqlCommand(strQry, sc);
                    scmd.Parameters.AddWithValue("@c0", counter);
                    counter++;
                    scmd.Parameters.Add("@po_no", SqlDbType.VarChar).Value = tb_ponumber2.Text;
                    scmd.Parameters.Add("@invoice", SqlDbType.VarChar).Value = tb_invoice2.Text;
                    scmd.Parameters.AddWithValue("@c1", row.Cells[1].Value);
                    scmd.Parameters.Add("@date", SqlDbType.Date).Value = date;
                    scmd.Parameters.AddWithValue("@c2", row.Cells[2].Value);
                    scmd.Parameters.AddWithValue("@c3", row.Cells[3].Value);
                    scmd.Parameters.AddWithValue("@c4", row.Cells[4].Value);
                    scmd.Parameters.AddWithValue("@c5", row.Cells[5].Value);
                    scmd.Parameters.AddWithValue("@c6", row.Cells[6].Value);
                    scmd.Parameters.AddWithValue("@c7", row.Cells[7].Value);
                    scmd.Parameters.AddWithValue("@c8", row.Cells[8].Value);
                    scmd.Parameters.AddWithValue("@c9", row.Cells[9].Value);
                    scmd.ExecuteNonQuery();
                    sc.Close();
                    MessageBox.Show("Successfully Updated!");}
        }
    }


text:
Q: How to write a bash script that creates a new folder version? I guess git is not a deployment tool, however, for the last year I have been using git checkout -f inside post-receive without any issues.
post-receive hook
#!/bin/sh
git --work-tree=/var/www/domain.com --git-dir=/var/repo/site.git checkout -f

Now I want to further things by doing some version control & git tagging.
For example I have an updated version of my project (v0.2) I feel it's better, however there may have been some nice features removed in (v0.1) that I still want to see and compare, also for many other reasons as well.

*

*A. Should I handle this functionality inside the bash script?

*B. What should the code look like?

Below is my interpretation of what the code would like like, my question is how do I actually make the below work optimally?
#!/bin/sh
$version = git tag
if ($version != $previousVersion) {
  mkdir ../../../www/domain.com/$version/
}
git --work-tree=/var/www/domain.com/$version --git-dir=/var/repo/site.git checkout -f

Obviously some flaws above, and plus I don't really know bash scripting, so I am going to read on creating variables and booleans.
With the above my question is what is the best way to write the logic, i.e compare versions (which is not even possible to check above because $previousVersion doesn't exist, I am not exactly sure how to check the last pushed commit's version, or if that is even a thing).
So I would like to learn what operations need to be done in the post-receive so that if there is a new git tag a new folder is created in my --work-tree aka /var/www/domain.com and the checkout pushes the files there.


text:
Q: How to get IIS 7 to route requests for .css files to aspnet_isapi.dll? We currently use DotLess on an ASP.NET web application hosted on IIS 6. In order to get this to work, we needed to tweak our IIS settings so that requests for *.css files would get handled by aspnet_isapi.dll (right click on website in IIS -> properties -> home directory tab -> configuration).
We're now moving this web application over to IIS 7 (classic mode) and can't seem to find a way to set up IIS 7 in this manner. Is there a way to change IIS 7's settings so that requests for *.css files get handled by aspnet_isapi.dll like we were doing in IIS 6?

A: Have you seen this link? Does it help you? http://learn.iis.net/page.aspx/508/wildcard-script-mapping-and-iis-7-integrated-pipeline/
Effectively this: IIS7 -> Web Site -> Handler Mappings -> Add Wildcard Script Match
Wildcard script mapping in IIS 7 classic pipeline mode
With classic pipeline mode the ASP.NET is plugged into the IIS request processing pipeline as an ISAPI extension - exactly the same way as it was in IIS 6. In fact, if you open %WINDIR%\system32\inetsrv\config\applicationHost.config file and locate the  section inside of it you can see how IIS is configured to map ASP.NET specific requests to the aspnet_isapi.dll:
<handlers accessPolicy="Read, Script">
  ...
  <add name="PageHandlerFactory-ISAPI-2.0"
       path="*.aspx" verb="GET,HEAD,POST,DEBUG"
       modules="IsapiModule"
       scriptProcessor="%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll"
       preCondition="classicMode,runtimeVersionv2.0,bitness32" responseBufferLimit="0" />
  ...
</handlers>

Notice the preCondition attribute for the handler mapping. Among other things this attribute is set to classicMode, which ensures that this handler mapping only takes effect when the application pool is configured to run in classic mode.
Now if you want to configure wildcard mapping for the ASP.NET running in classic mode, you can do it by choosing "Handler Mappings" in IIS Manager and then clicking on "Add Wildcard Script Map..." action.

A: define a HttpHandler and wire it into iis via web.config, in this case I've got a class named CssHandler that implements the IHttpHandler interface.
<configuration>
  <system.web>
    <httpHandlers>
      <add verb="GET" path="*.css" validate="false" type="CssHandler" />
    </httpHandlers>
   </system.web>

  <!-- for iis7 integrated pipeline-->
  <system.webServer>
    <handlers>
      <add name="CssHandler" verb="GET" path="*.css" preCondition="integratedMode" type="CssHandler" />
    </handlers>
  </system.webServer>

</configuration>


text:
Q: Remove rows with certain number of '0's from a pandas dataframe I have a sparse dataframe with a lot of '0's. There are totally 3 columns. How can I delete the rows that contain two '0's or more. For example:
df = pd.DataFrame({'a': [0, 1, 2, 3], 'b': [0, 0, 5, 7], 'c': [0, 0, 0, 0]})

df =
     a    b    c
0    0    0    0
1    1    0    0
2    2    5    0
3    3    7    0

The result should be:
df =
         a    b    c
    0    2    5    0
    1    3    7    0


text:
Q: change video source before play using jquery I'd like to be able to change the video source before it starts to play based on a media query using javascript/jquery.  The premise being, if the screen resolution is below a certain value then the device is mobile and lets assume it is on a mobile network so load the lower resolution video.
The following works, but I get a 'glitch' as the original video loads before jQuery does it's thing and changes the video source.
I've looked into using the media query built into the html5 video tag but understand that it has limited support.

the html is as follows

    <video class="video" poster="<?PHP echo $bg_image; ?>" id="bg_video" playsinline autoplay muted loop >
        <source src="https://www.html5rocks.com/en/tutorials/video/basics/devstories.mp4" type="video/mp4">
    </video>

Any ideas how I can do the media query before the video starts to play?
Cheers,
Philip
I've created a codepen that demonstrates the problem
[UPDATE based on VC.One's solution]

    <video class="video" <?PHP echo ($bg_image !="") ? 'poster="' . $bg_image . '"' : ''; ?>" id="bg_video" playsinline autoplay muted loop >
        <source src="images/backgrounds/null.mp4" type="video/mp4">
    </video>

A: It seems a simple If/Else statement works. Let me know how it goes.
(1) HTML : Use a dummy URL like null.mp4 so nothing is loaded by video tag at start.

    <video class="video" poster="<?PHP echo $bg_image; ?>" id="bg_video" playsinline autoplay muted loop >
    <source src="null.mp4" type="video/mp4">
    </video>

(2) JS : Use an If/Else statement in your JavaScript code.
(function($)
{
    $(window).on("load",function(e)
    {
        $('video source').each(function()
        {
            var isMobile = $('#mobile-indicator').is(':visible');

            if (isMobile == true)
            {
                alert("is mobile");
                var videoSmall = "https://www.w3schools.com/html/mov_bbb.mp4";
                $(this).attr('src', videoSmall);
            }
            else
            {
                alert("not mobile");
                var videoLarge = "https://www.html5rocks.com/en/tutorials/video/basics/devstories.mp4";
                $(this).attr('src', videoLarge);
            }

            $("video")[0].load();

        });
    });
})(jQuery);


text:
Q: Question Regarding GCD Proof I have a question about a proof involving greatest common divisors. A function $g(k) = \gcd(13k+2, 5k-1)$ is defined where $k$ is an integer. How do we find all the elements of $\{g(k) : k \in \mathbb{Z}\}$?
So, the first thing I did was simplify using the division algorithm and it turns out $\gcd (13k+2, 5k-1) = \gcd(k+9, -23) = \gcd(k+9, 23)$.
It can be easily seen that $\gcd = 1$ and $23$ since $23$ is prime. So would all the elements in $\{g(k): k \in \mathbb{Z}\}$ be $\{1, 23\}$? I used some numbers to try it out and it seems so.
Also, how do we prove if $b<a$ and that $a$ and $b$ are positive integers, then $\{k \in\mathbb{Z}: g(k)>1\} = \{k \in\mathbb{Z}: a \mid(k+b)\}$? To prove this I know if $g(k)>1$ then it is $23$. However, I'm stuck on $a\mid (k+b)$. I think there are $2$ cases, where $(k+b)$ is either positive or negative.


text:
Q: How to batch process functions with Scala Future's? I have a single function I want to call 100 times but I want to do it in a batched way so that only 2 functions are being run at any one time. This is due to the fact that the function may place a high load on the internet connection, so its better to batch process the functions in groups of 2's.
This is my attempt to do it with Scala Futures but does not seem to work. Is there any standard way using Scala Futures to batch process a list of tasks?
  def futureString(s:String): String = {
    Thread.sleep(2000)// + (Math.random()*1000).toInt)
    println(s"Completed $s")
    "end:" + s
  }

 def processList(list: List[String], blockSize: Int) = {
    var futuresProcessing = Set[Future[String]]()
    async {
      val itemIterator = list.iterator
      while (itemIterator.hasNext) {
        val item = itemIterator.next()
        println("Item is " + item)

        if (futuresProcessing.size >= blockSize) {
          await {
            val completed = Future.firstCompletedOf(futuresProcessing.toSeq)
            println("Size : " + futuresProcessing.size)
            completed
          }
        }

        val f = future { futureString(item) }
        f.onComplete{ case Success(sss) => { futuresProcessing = futuresProcessing - f } }
        futuresProcessing = futuresProcessing + f
      }
    }
  }

  val list: List[String] = (1 to 200).map(n => "" + n).toList
  processList(list, 2)

What I want is that I can batch process any batch size and the futureString may finish at a random amount of time. So lets say the batch size is 10, then at first 10 items start, when one item finishes, then a new item should be added to the batch to process.
I'm starting to think I should use actors.
Update: After a good long sleep and awake I got it working, but I think it would be better done with Actors. Also I think there's some race condition problem with the following code and the use of the futuresProcessing Set.
  import scala.concurrent._
  import scala.concurrent.duration._
  import ExecutionContext.Implicits.global
  import scala.async.Async.{async, await}
  import scala.collection.parallel.mutable
  import scala.util.{Success, Try}
  import scala.concurrent.Await

  def futureString(s:String): Future[String] = {
    future {
    Thread.sleep(2000 + (Math.random()*1000).toInt)
    println(s"Completed $s")
    "end:" + s
    }
  }

  def processList(list: List[String], blockSize: Int) = {
    val futuresProcessing = mutable.ParSet[Future[String]]()
    async {
      val itemIterator = list.iterator
      while (itemIterator.hasNext) {
        val item = itemIterator.next()
        println("Item is " + item)

        if (futuresProcessing.size >= blockSize) {
          await {
            val completed = Future.firstCompletedOf(futuresProcessing.toList)
            println("Size : " + futuresProcessing.size)
            completed
          }
        }

        val f = futureString(item)
        futuresProcessing += f
        f.onComplete{ case Success(sss) => { futuresProcessing -= f } }
      }
    }
  }

val list: List[String] = (1 to 200).map(n => "" + n).toList
processList(list, 4)

A: If you only care about processing batches of 2 in parallel, then there might be an easier solution:
val data = (1 to 20).map(_.toString()).grouped(2).toList

and then:
val result = data.flatMap(pair => pair.par.map(futureString))

Which yields:
// pause
Completed 1
Completed 2
// pause
Completed 4
Completed 3
// pause
Completed 6
Completed 5
// pause
Completed 8
Completed 7
// pause
Completed 9
Completed 10
// pause
// ..etc

result: List[String] = List(end:1, end:2, end:3, end:4, end:5, end:6, end:7, end
:8, end:9, end:10, end:11, end:12, end:13, end:14, end:15, end:16, end:17, end:1
8, end:19, end:20)

If you want to have it done asynchronously (because the version above will block), you can wrap the whole result processing in one Future and await it.

A: For easy peasy, let the pool define the parallelism.
scala> import concurrent._
import concurrent._

scala> implicit val x = ExecutionContext fromExecutorService new java.util.concurrent.ForkJoinPool(2)
x: scala.concurrent.ExecutionContextExecutorService = scala.concurrent.impl.ExecutionContextImpl$$anon$1@6c9b0123

scala> 1 to 20 map (i => Future { println(s"Start $i"); delay; println(s"End $i"); i.toString })
Start 1
Start 2
res1: scala.collection.immutable.IndexedSeq[scala.concurrent.Future[String]] = Vector(scala.concurrent.impl.Promise$DefaultPromise@397314a4, scala.concurrent.impl.Promise$DefaultPromise@32503873, scala.concurrent.impl.Promise$DefaultPromise@30aa1fd3, scala.concurrent.impl.Promise$DefaultPromise@710f6e9a, scala.concurrent.impl.Promise$DefaultPromise@2c267a73, scala.concurrent.impl.Promise$DefaultPromise@12312aaa, scala.concurrent.impl.Promise$DefaultPromise@59e8083a, scala.concurrent.impl.Promise$DefaultPromise@107445f3, scala.concurrent.impl.Promise$DefaultPromise@419c5cf5, scala.concurrent.impl.Promise$DefaultPromise@9afa7a, scala.concurrent.impl.Promise$DefaultPromise@3eb25fe5, scala.concurrent.impl.Promise$DefaultPromise@30b5d38b, scala.concurrent.impl.Promise$DefaultPromise@715363a8...
scala> End 1
Start 3
End 2
Start 4
End 3
Start 5

(etc to 20)
where
scala> val ran = new java.util.Random()
ran: java.util.Random = java.util.Random@2ee5d440

scala> def delay() = Thread sleep (1000L + (ran nextInt 10000))
delay: ()Unit

Edit: configuration of the default ExecutionContext.global pool is documented in the overview. It will use system properties scala.concurrent.context.maxThreads, minThreads and numThreads to constrain available threads.
It's also worth adding that people who want extra control over when async code runs prefer a Task abstraction available in several libraries.
$ scala -Dscala.concurrent.context.maxThreads=2
Welcome to Scala 2.12.0 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_111).
Type in expressions for evaluation. Or try :help.

scala> import concurrent._, ExecutionContext.Implicits.global
import concurrent._
import ExecutionContext.Implicits.global

scala> 1 to 20 map (i => Future { println(s"Start $i"); delay; println(s"End $i"); i.toString })
<console>:16: error: not found: value delay
       1 to 20 map (i => Future { println(s"Start $i"); delay; println(s"End $i"); i.toString })
                                                        ^

scala>  val ran = new java.util.Random()
ran: java.util.Random = java.util.Random@782be4eb

scala> def delay() = Thread sleep (1000L + (ran nextInt 10000))
delay: ()Unit

scala> 1 to 20 map (i => Future { println(s"Start $i"); delay; println(s"End $i"); i.toString })
Start 1
Start 2
res1: scala.collection.immutable.IndexedSeq[scala.concurrent.Future[String]] = Vector(Future(<not completed>), Future(<not completed>), Future(<not completed>), Future(<not completed>), Future(<not completed>), Future(<not completed>), Future(<not completed>), Future(<not completed>), Future(<not completed>), Future(<not completed>), Future(<not completed>), Future(<not completed>), Future(<not completed>), Future(<not completed>), Future(<not completed>), Future(<not completed>), Future(<not completed>), Future(<not completed>), Future(<not completed>), Future(<not completed>))

scala> End 1
Start 3
End 2
Start 4
End 4
Start 5
End 5
Start 6
End 3
Start 7
End 7


text:
Q: Python @properties raising an error I am trying to write a class to pass the following unittest:
import unittest
from property_address import *

class TestAddresses(unittest.TestCase):

    def setUp(self):
        self.home = Address( name='Steve Holden', street_address='1972 Flying Circus', city='Arlington', state='VA', zip_code='12345' )

    def test_name(self):
        self.assertEqual(self.home.name, 'Steve Holden')
        self.assertRaises(AttributeError, setattr, self.home, 'name', 'Daniel Greenfeld')

    def test_state(self):
        self.assertEqual(self.home.state, 'VA')
        self.assertRaises(StateError, setattr, self.home, 'state', 'Not a state')
        self.home.state = 'CO'
        self.assertEqual(self.home.state, 'CO')

The part I am having issues with is the self.assertRaises(StateError, setattr, self.home, 'state', 'Not a state')
I can't seem how to get a StatError to be raised.
The code I am using is:
class Address(object):

    states = ['IA', 'KS', 'UT', 'VA', 'NC', 'NE', 'SD', 'AL', 'ID', 'FM', 'DE', 'AK', 'CT', 'PR', 'NM', 'MS', 'PW', 'CO', 'NJ', 'FL', 'MN',
              'VI', 'NV', 'AZ', 'WI', 'ND', 'PA', 'OK', 'KY', 'RI', 'NH', 'MO', 'ME', 'VT', 'GA', 'GU', 'AS', 'NY', 'CA', 'HI', 'IL', 'TN',
              'MA', 'OH', 'MD', 'MI', 'WY', 'WA', 'OR', 'MH', 'SC', 'IN', 'LA', 'MP', 'DC', 'MT', 'AR', 'WV', 'TX']

    def __init__(self,name, street_address, city, state, zip_code):
        self._name = name
        self._street_address = street_address
        self._city = city
        self._state = state
        self._zip_code = zip_code

    @property
    def name(self):
        return self._name.title()

    @property
    def state(self):
        return self._state

    @state.setter
    def state(self,value):
        if value in self.states:
            self._state = value
        else:
            raise ### This is where I am stuck

do I need to create a new @property for StateError, or should I work it into state def somehow.

A: You need to raise a StateError exception; that is all:
@state.setter
def state(self,value):
    if value not in self.states:
        raise StateError(value)
    self._state = value

This does require you to have defined the exception class first, of course:
class StateError(Exception):
    """Invalid state value used"""

Demo:
>>> class StateError(Exception): pass
...
>>> class Address(object):
...     states = ['IA', 'KS', 'UT', 'VA', 'NC', 'NE', 'SD', 'AL', 'ID', 'FM', 'DE', 'AK', 'CT', 'PR', 'NM', 'MS', 'PW', 'CO', 'NJ', 'FL', 'MN',
...               'VI', 'NV', 'AZ', 'WI', 'ND', 'PA', 'OK', 'KY', 'RI', 'NH', 'MO', 'ME', 'VT', 'GA', 'GU', 'AS', 'NY', 'CA', 'HI', 'IL', 'TN',
...               'MA', 'OH', 'MD', 'MI', 'WY', 'WA', 'OR', 'MH', 'SC', 'IN', 'LA', 'MP', 'DC', 'MT', 'AR', 'WV', 'TX']...     @property
...     def state(self):
...         return self._state
...     @state.setter
...     def state(self,value):
...         if value not in self.states:
...             raise StateError(value)
...         self._state = value
...
>>> a = Address()
>>> a.state = 'VA'
>>> a.state = 'Nonesuch'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 11, in state
__main__.StateError: Nonesuch


text:
Q: symfony: stConfig::set('name', 'value') not working I have the following configuration in defaults.yml:

 poll_votes:
     type:                         string
     value:                        ''
     name:                         'Votes'
          description:                  ''
          editable:                     true
          system:                       false
          nullable:                     false

stConfig::get('poll_votes'); will return the correct value (which can be updated in the backend), but the value is not updated when calling stConfig::set('poll_votes', 'option1: 1 vote');
How can I set this values dynamically? Thank you.

A: stConfig? IIRC wasn't it sfConfig in Symfony 1?
Unless you are asking to change the contents of defaults.yml itself.


text:
Q: Circle around a point on an MKMapView I need to draw a circle with a specified radius around an arbitrary point (not necessarily the user's location) on an MKMapView. I would like the appearance to be similar to the circle that the Maps app uses, to show the accuracy of the user's location.
Is there a recommended way of doing this, or will I need to create a custom overlay?

A: You might want to look at MKCircle and MKCircleView, which are part of the MapKit API and are designed for drawing circles on an MKMapView. I don't think there's an easy way to duplicate the animated "zeroing in" effect like the user location circle does, but you should be able to use these classes to show a fixed degree of accuracy around a given coordinate.

A: You could use MKAnnoations, if you want to tie it to a map location, but you'll still need to provide the view (viewForAnnotation, or something similar -- see docs) to draw the circle.
If you need to know how to draw the circle, that's CGContextStrokeEllipseInRect() for the outline and CGContextFillElipseInRect() for the other part.  If you put all that into a view, you can use UIView animations to make it "throb", like the blue map dot.
If you have more specific questions, you'll have to ask them -- the one was kind of open-ended.


text:
Q: How to run a python flask application on https from EC2 machine on HTTPS I have written a small python application using flask. I have deployed the application on EC2 machine. Currently the application run as http. I want the application on https. How can I do it? instead of doing any modification in code like adding ssl_context?

A: You shouldn't need to be touching ssl_context. What you are trying to do is to just run your web server over HTTPS.
Depending on the web server you have (Nginx, Apache etc.), this is just a case of getting/generating a SSL certificate (you can use CertBot for this - this generates certificates via LetsEncrypt).
Once you have a SSL certificate, you then need to configure your web server to use this SSL certificate (as well as allow HTTPS connections on your firewall settings).
These guides helped me in the past, but you can always look online for a guide that suits the server OS you are using:

*

*https://www.digitalocean.com/community/tutorials/how-to-secure-apache-with-let-s-encrypt-on-ubuntu-20-04

*https://www.nginx.com/blog/using-free-ssltls-certificates-from-lets-encrypt-with-nginx/
Hope this helps!


text:
Q: creating account by data from spreadsheet - google apps I am working on a simple script that creates an account in the control panel of a domain - for example Gmail - and I was looking for a function in the Google apps script that creates an account automatically on inserting data to a spreadsheet
I searched the internet and I did find this though : https://developers.google.com/apps-script/class_usermanager
and the method I am using is : var user = UserManager.createUser("john.smith", "John", "Smith", "password
My question is, how can I insert the parameters from the spreadsheet that I have.
Sorry if this sounds a bit stupid I'm just new to Google apps script.

A: To read from the spreadsheet, you would use the SpreadsheetApp.
An example of reading a set of rows. (Let's say all rows).
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();

.getValues() returns a 2D array. So you would access it by data[rowNum][colNum]. Let's say you want to add every row as a new user, you could do
for (var i in data) {
  UserManager.createUser(data[i][0], data[i][1], data[i][2], data[i][3]);
}

How would you run said script? You could put all of it inside some function (function addAllUsers()) and then run it from the run menu in the Script Editor.


text:
Q: Change behavior of "Add new Android Components" on Android Studio I am having a problem with my build.gradle file every time that I insert a new Fragment from AndroidStudio. When I use the tool that AndroidStudio provides to insert a new component such as fragments or activities, it creates the fragment class .java and the associated  layout, but it also modifies my build.gradle, for example, my dependencies are reordered but the build.gradle file is broken after that because the order is not done properly. I attach an image with the example.
Why is it behavior happening and how could I prevent it?
I am using AndroidStudio v2.1.1 stable channel


text:
Q: How to Convert Class components to functional components in React? import React, { PureComponent, Fragment } from 'react';

class Practice extends PureComponent {

  state = {

    options: [
      {
        name: 'Select…',
        value: null,
      },
      {
        name: 'Rui',
        value: 3000,
      },
      {
        name: 'Catla',
        value: 3000,
      },
      {
        name: 'Carpio',
        value: 3000,
      },
      {
        name: 'Tilapia',
        value: 1750,
      },
      {
        name: 'Mrigel',
        value: 3000,
      },
      {
        name: 'Pabda',
        value: 3500,
      },
      {
        name: 'Koi',
        value: 750,
      },
    ],
    value: '?',
  };

  handleChange = (e) => {

    this.setState({ value: e.target.value });
  };

  render() {
    const { options, value } = this.state;

    return (
      <Fragment>
        <select onChange={this.handleChange} value={value}>
          {options.map(item => (
            <option key={item.value} value={item.value}>
              {item.name}
            </option>
          ))}
        </select>

Oxygen Demand: {value}

      </Fragment>
    );
  }
}

export default Practice;

A: Use useState to handle state of options and value
Use useCallback to handle change events on select field
Return your rendered JSX
import React, { useCallback, useState } from "react";

function Practice() {
  const [options, setOptions] = useState([
    {
      name: "Select…",
      value: null,
    },
    {
      name: "Rui",
      value: 3000,
    },
    {
      name: "Catla",
      value: 3000,
    },
    {
      name: "Carpio",
      value: 3000,
    },
    {
      name: "Tilapia",
      value: 1750,
    },
    {
      name: "Mrigel",
      value: 3000,
    },
    {
      name: "Pabda",
      value: 3500,
    },
    {
      name: "Koi",
      value: 750,
    },
  ]);
  const [value, setValue] = useState("?");

  const handleChange = useCallback((e) => {
    setValue(e.target.value);
  }, []);

  return (
    <>
      <select onChange={handleChange} value={value}>
        {options.map((item) => (
          <option key={item.value} value={item.value}>
            {item.name}
          </option>
        ))}
      </select>

Oxygen Demand: {value}

    </>
  );
}

export default Practice;

A: Convert like this:
import React, { useState, PureComponent, Fragment } from 'react';

let Practice = (praps) =>
let [options,soptions] = useState([
  {
    name: 'Select…',
    value: null,
  },
  {
    name: 'Rui',
    value: 3000,
  },
  {
    name: 'Catla',
    value: 3000,
  },
  {
    name: 'Carpio',
    value: 3000,
  },
  {
    name: 'Tilapia',
    value: 1750,
  },
  {
    name: 'Mrigel',
    value: 3000,
  },
  {
    name: 'Pabda',
    value: 3500,
  },
  {
    name: 'Koi',
    value: 750,
  },
]);
let [value,svalue]=useState('?')

let handleChange = (e) => {

svalue(e.target.value);

};

render() {

return (
  <Fragment>
    <select onChange={this.handleChange} value={value}>
      {options.map(item => (
        <option key={item.value} value={item.value}>
          {item.name}
        </option>
      ))}
    </select>

Oxygen Demand: {value}

  </Fragment>
);

} }

export default Practice;


text:
Q: Why does this "StreamBuilder" use data from a previously closed stream? I have this very simple Flutter app:
import 'package:flutter/material.dart';
import 'dart:async';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Debug",
      initialRoute: "/",
      routes: {
        "/": (context) => MainPage(),
      },
    );
  }
}

With MainPage being:
class MainPage extends StatelessWidget {
  final _rebuilder = StreamController<void>.broadcast();

  @override
  Widget build(BuildContext context) {
    debugPrint("Initializing the app main page");
    var isButtonPressed = StreamController<bool>.broadcast();

    return StreamBuilder<void>(
      stream: _rebuilder.stream,
      builder: (context, snapshot) {
        debugPrint("Rebuilding (stream = ${isButtonPressed.stream.hashCode})");
        return StreamBuilder<bool>(
          stream: isButtonPressed.stream,
          initialData: false,
          builder: (context, snapshot) {
            var pressed = snapshot.data;
            debugPrint("Button state: $pressed (stream = ${isButtonPressed.stream.hashCode})");
            return RaisedButton(
              onPressed: () {
                debugPrint("Closing and rebuilding (stream = ${isButtonPressed.stream.hashCode})");
                isButtonPressed.sink.add(true);
                isButtonPressed.close();
                isButtonPressed = StreamController<bool>.broadcast();
                _rebuilder.sink.add(null);
              },
              child: Text("Pressed: $pressed"),
            );
          },
        );
      },
    );
  }
}

It uses two StreamController: the _rebuilder is used to generate a new button, and the isButtonPressed is used to update the existing button.
As you see, when the button is pressed, I update it through the stream's sink, then close the stream, and finally ask for a new button to be created.
However, it looks like when the button's StreamBuilder is created a second time, it is not initialized using the initialData: false, because pressed == true although stream.hashCode is different.
I/flutter ( 4207): Initializing the app main page
I/flutter ( 4207): Rebuilding (stream = 773570673)
I/flutter ( 4207): Button state: false (stream = 773570673)
I/flutter ( 4207): Closing and rebuilding (stream = 773570673)
I/flutter ( 4207): Rebuilding (stream = 786124862)
I/flutter ( 4207): Button state: true (stream = 786124862)

I don't understand. I expected the new stream to be empty, and hence the button's state to be false. Why isn't it the case?

A: the problem is not in the Streams. Streambuilder itself also widget that uses state methods. So, you should add key property to Streambuilder and that's it. Code below.
class MainPage extends StatelessWidget {
  final _rebuilder = StreamController<void>.broadcast();

  @override
  Widget build(BuildContext context) {
    debugPrint("Initializing the app main page");
    var isButtonPressed = StreamController<bool>.broadcast();

    return StreamBuilder<void>(
      stream: _rebuilder.stream,
      builder: (context, snapshot) {
        debugPrint("Rebuilding (stream = ${isButtonPressed.stream.hashCode})");
        return StreamBuilder<bool>(
          key: UniqueKey(),
          stream: isButtonPressed.stream,
          initialData: false,
          builder: (context, snapshot) {
            var pressed = snapshot.data;
            debugPrint(
                "Button state: $pressed (stream = ${isButtonPressed.stream.hashCode})");
            return RaisedButton(
              onPressed: () {
                debugPrint(
                    "Closing and rebuilding (stream = ${isButtonPressed.stream.hashCode})");
                isButtonPressed.sink.add(true);
                isButtonPressed.close();
                isButtonPressed = StreamController<bool>.broadcast();
                _rebuilder.sink.add(null);
              },
              child: Text("Pressed: $pressed"),
            );
          },
        );
      },
    );
  }
}

(Thanks to @Delgan for finding logical mistakes, the answer have edited.)


text:
Q: How can I finding the Modify/Access/Change time of a file or directory? I am using Debian 7.2 and would like to know the shell command for finding the MAC time of a file or directory.  I tried
man -k "MAC"

and got a lot of hits about macros.  I then tried
man -k "MAC time"

and got nothing.

A: By MAC I assume you're asking about Modify, Access, and Change timestamps. You can get these from the stat command.
Example
$ ls -l LICENSE
-rw-rw-r-- 1 saml saml 810 Jul  5  2012 LICENSE

$ stat LICENSE
  File: `LICENSE'
  Size: 810         Blocks: 8          IO Block: 4096   regular file
Device: fd02h/64770d    Inode: 11409231    Links: 1
Access: (0664/-rw-rw-r--)  Uid: (  500/    saml)   Gid: (  501/    saml)
Access: 2012-07-05 19:05:22.000000000 -0400
Modify: 2012-07-05 19:05:22.000000000 -0400
Change: 2013-10-16 21:17:31.148341667 -0400

Details

*

*Access: 2012-07-05 19:05:22.000000000 -0400 – Last access time of the file.

*Modify: 2012-07-05 19:05:22.000000000 -0400 – Last modification time of the file.

*Change: 2013-10-16 21:17:31.148341667 -0400 – Last change time of the inode data of that file.


text:
Q: Zoom in and out all children of a canvas? I'm having some problems with Canvas event ManipulationDelta, and It seems to be a function for manipulation of the whole canvas itself.
Im looking for a event where I use two fingers to pinch the screen. On pinch it should zoom in or out the children of that canvas element.
Is there a way to do this out of the box with xaml/c# or am I better of with a lib, in that case which?

A: Since you are targeting Windows Phone 7, you can detect gestures via Toolkit.GestureService. Find out more on this article: WP7 GestureService in depth | key concepts and API.
Unfortunately, for Windows Phone 8 you must do the gesture detection yourself, there is no gesture API for it yet.