text:
Q: Error on PowerShell task in Azure DevOps: The term 'powershell.exe' is not recognized as the name I'm following this tutorial to automate the creation of release notes using the wiki in Azure DevOps. Steps are very basic and there are not many variables that I believe would cause the error.

When I create a release it runs and then fails at the PowerShell task. This is what is displayed in the log and with the error:

[error]The term 'powershell.exe' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

I have replaced my agent name with [myLocalAgent] in the log
2020-03-10T08:46:58.0567080Z ##[debug]Evaluating condition for step: 'PowerShell Script'
2020-03-10T08:46:58.0567721Z ##[debug]Evaluating: succeeded()
2020-03-10T08:46:58.0567840Z ##[debug]Evaluating succeeded:
2020-03-10T08:46:58.0568071Z ##[debug]=> True
2020-03-10T08:46:58.0568346Z ##[debug]Result: True
2020-03-10T08:46:58.0568583Z ##[section]Starting: PowerShell Script
2020-03-10T08:46:58.0660872Z ==============================================================================
2020-03-10T08:46:58.0660963Z Task         : PowerShell
2020-03-10T08:46:58.0661006Z Description  : Run a PowerShell script on Linux, macOS, or Windows
2020-03-10T08:46:58.0661050Z Version      : 2.165.0
2020-03-10T08:46:58.0661103Z Author       : Microsoft Corporation
2020-03-10T08:46:58.0661147Z Help         : https://learn.microsoft.com/azure/devops/pipelines/tasks/utility/powershell
2020-03-10T08:46:58.0661190Z ==============================================================================
2020-03-10T08:46:59.2751397Z ##[debug]VstsTaskSdk 0.11.0 commit 7ff27a3e0bdd6f7b06690ae5f5b63cb84d0f23f4
2020-03-10T08:46:59.4510283Z ##[debug]Entering C:\[myLocalAgent]\_work\_tasks\PowerShell_e213ff0f-5d5c-4791-802d-52ea3e7be1f1\2.165.0\powershell.ps1.
2020-03-10T08:46:59.4641263Z ##[debug]Loading resource strings from: C:\[myLocalAgent]\_work\_tasks\PowerShell_e213ff0f-5d5c-4791-802d-52ea3e7be1f1\2.165.0\task.json
2020-03-10T08:46:59.5013258Z ##[debug]Loaded 11 strings.
2020-03-10T08:46:59.5070774Z ##[debug]SYSTEM_CULTURE: 'en-US'
2020-03-10T08:46:59.5667676Z ##[debug]Loading resource strings from: C:\[myLocalAgent]\_work\_tasks\PowerShell_e213ff0f-5d5c-4791-802d-52ea3e7be1f1\2.165.0\Strings\resources.resjson\en-US\resources.resjson
2020-03-10T08:46:59.6018496Z ##[debug]Loaded 11 strings.
2020-03-10T08:46:59.6361663Z ##[debug]INPUT_ERRORACTIONPREFERENCE: 'stop'
2020-03-10T08:46:59.6401971Z ##[debug]INPUT_FAILONSTDERR: 'false'
2020-03-10T08:46:59.6440102Z ##[debug] Converted to bool: False
2020-03-10T08:46:59.6470870Z ##[debug]INPUT_IGNORELASTEXITCODE: 'false'
2020-03-10T08:46:59.6491840Z ##[debug] Converted to bool: False
2020-03-10T08:46:59.6521051Z ##[debug]INPUT_PWSH: 'false'
2020-03-10T08:46:59.6543374Z ##[debug] Converted to bool: False
2020-03-10T08:46:59.6572719Z ##[debug]INPUT_WORKINGDIRECTORY: 'C:\[myLocalAgent]\_work\r7\a'
2020-03-10T08:46:59.6748678Z ##[debug]Asserting container path exists: 'C:\[myLocalAgent]\_work\r7\a'
2020-03-10T08:46:59.6782331Z ##[debug]INPUT_TARGETTYPE: 'inline'
2020-03-10T08:46:59.6826977Z ##[debug]INPUT_SCRIPT: '# Get content of releasenotes
2020-03-10T08:46:59.6841501Z ##[debug]$content = [IO.File]::ReadAllText("C:\[myLocalAgent]\_work\r7\a\releasenotes.md")
2020-03-10T08:46:59.6855896Z ##[debug]# Get content of package.json for getting version value
2020-03-10T08:46:59.6870421Z ##[debug]$contentPackage = [IO.File]::ReadAllText("C:\[myLocalAgent]\_work\r7\a\package.json") | ConvertFrom-Json;
2020-03-10T08:46:59.6884843Z ##[debug]# Concat the URI
2020-03-10T08:46:59.6900257Z ##[debug]$uri = $env:WikiUri +$env:WikiPath + $($contentPackage.version)
2020-03-10T08:46:59.6916667Z ##[debug]# Convert to json for Wiki API
2020-03-10T08:46:59.6932043Z ##[debug]$data = @{content=$content;} | ConvertTo-Json;
2020-03-10T08:46:59.6947112Z ##[debug]# Set Request
2020-03-10T08:46:59.6960317Z ##[debug]$params = @{uri = "$($uri)";
2020-03-10T08:46:59.6973489Z ##[debug]  Method = 'PUT';
2020-03-10T08:46:59.6986730Z ##[debug]  Headers = @{Authorization = "Basic $($env:basicB64Token)" };
2020-03-10T08:46:59.7000064Z ##[debug]  ContentType = "application/json";
2020-03-10T08:46:59.7013085Z ##[debug]  Body = $data;
2020-03-10T08:46:59.7026111Z ##[debug]}
2020-03-10T08:46:59.7039918Z ##[debug]# Call
2020-03-10T08:46:59.7053974Z ##[debug]Invoke-WebRequest @params'
2020-03-10T08:46:59.7136093Z Generating script.
2020-03-10T08:46:59.7346195Z ##[debug]AGENT_VERSION: '2.154.3'
2020-03-10T08:46:59.7464794Z ##[debug]AGENT_TEMPDIRECTORY: 'C:\[myLocalAgent]\_work\_temp'
2020-03-10T08:46:59.7490309Z ##[debug]Asserting container path exists: 'C:\[myLocalAgent]\_work\_temp'
2020-03-10T08:46:59.8394063Z ##[debug]Leaving C:\[myLocalAgent]\_work\_tasks\PowerShell_e213ff0f-5d5c-4791-802d-52ea3e7be1f1\2.165.0\powershell.ps1.
2020-03-10T08:46:59.8447996Z ##[debug]Caught exception from task script.
2020-03-10T08:46:59.8484660Z ##[debug]Error record:
2020-03-10T08:46:59.9086805Z ##[debug]The term 'powershell.exe' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
2020-03-10T08:46:59.9099083Z ##[debug]    + CategoryInfo          : ObjectNotFound: (powershell.exe:String) [], Comm    andNotFoundException
2020-03-10T08:46:59.9111398Z ##[debug]    + FullyQualifiedErrorId : CommandNotFoundException
2020-03-10T08:46:59.9124155Z ##[debug]
2020-03-10T08:46:59.9147270Z ##[debug]Script stack trace:
2020-03-10T08:46:59.9203751Z ##[debug]
2020-03-10T08:46:59.9225885Z ##[debug]Exception:
2020-03-10T08:46:59.9278832Z ##[debug]System.Management.Automation.CommandNotFoundException: The term 'powershell.exe' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
2020-03-10T08:46:59.9656113Z ##[error]The term 'powershell.exe' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
2020-03-10T08:46:59.9666068Z ##[debug]Processed: ##vso[task.logissue type=error]The term 'powershell.exe' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
2020-03-10T08:46:59.9666747Z ##[debug]Processed: ##vso[task.complete result=Failed]

I have searched on the web and there are references to incorrect spelling due to spaces in the file name (no spaces in my file names) or an incorrect path that is referenced (my PowerShell is inline/autogenerated).
Would appreciate any assistance.
Thank you in advance.

A: What OS are you running?
What PowerShell version are you running?
What it's in your environment path?
There are three executables for PowerShell on Windows

*

*PowerShell console = powershell.exe

*PowerShell ide = powershel_ise.exe

*Powershell core = pwsh.exe

There is only one executable for PowerShell on OSX/*Nix

*

*Powershell core = pwsh.exe

Anytime you see stuff like, The term 'XXX' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.', it's normally always and install/config issue regardless of whatever command you are trying to use regardless of OS version.

A:
Error on PowerShell task in Azure DevOps: The term 'powershell.exe' is not recognized as the name

Since you are using your private agent, please check following:
First, Check Path variable of System variables, By default, there is %SYSTEMROOT%\System32\WindowsPowerShell\v1.0\ item, if it isn't existing, please add related path that contains PowerShell.exe to the Path variable, then restart your machine.
Second, avoid use "Path" in the Pipeline variable:

Third, try to test it with hosted agent to check if the error comes from the powershell scripts itself.
Hope this help.


text:
Q: Is there a simple source for setting up babel/webpack for IE11? I am looking for help transforming es6 to es5 with babel/webpack and am coming up empty. If there is already an answer for this, please tell me.
package.json:
"dependencies": {
  "@babel/polyfill": "^7.0.0",
  "browserslist": "^4.4.1",
  ...
"devDependencies": {
  "@babel/preset-env": "^7.3.1",
  "eslint": "^5.1.0",
  ...

webpack.config.js:
const path = require('path');

const CleanPlugin = require('clean-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');

module.exports = {
    entry: {
        App: ['@babel/polyfill', './app.js'],
        Library: ['@babel/polyfill', './codegen/library.js'],
        CalculatorPage: ['@babel/polyfill', './calculator-page.js'],
        CalculatorPageExternal: ['@babel/polyfill', './calculator-page-external.js']
    },
    output: {
        path: path.resolve(__dirname, 'static'),
        filename: 'Calc.[name].[chunkhash].js',
        library: [ 'Calc', '[name]' ]
    }

app.js:
require("@babel/polyfill");
...

.babelrc:
{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "browsers": ["IE >= 10"]
        }
      }
    ]
  ]
}

So far, this changes nothing about what is generated when webpack runs.
I understand questions around this have been asked before - but it seems every answer is so specific to that person's use case that I am having a hard time finding a single source of "this is how you transform esNext to es5" with babel and webpack."
What am I missing/what needs to be done to make this actually generate es5 compatible code?

A: rules.loaders is the webpack key you're searching for.
Using babel-loader and @babel/preset-env (preset for polyfill-ing / transforming all yearly EcmaScript specs without a need for micromanaging specific specs e.g ES6) you'll be able to achieve this.

A: You need to configure the preset to browsers you need to target as well.
Use the following:
[
        '@babel/preset-env',
        {
          targets: {
            browsers: ["IE 11"],
          },
        useBuiltIns: 'usage'
        }
]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why do Rust lifetimes matter when I move values into a spawned Tokio task? I'm trying to create a struct that will manage a Tokio task with one tokio::sync::mpsc::Sender that sends input to the task, one tokio::sync::mpsc::Receiver that receives output from the task, and a handle that I can join at the end.
use tokio::sync::mpsc;
use tokio::task::JoinHandle;

// A type that implements BlockFunctionality consumes instances of T and
// produces either Ok(Some(U)) if an output is ready, Ok(None) if an output
// is not ready, or an Err(_) if the operation fails
pub trait BlockFunctionality<T, U> {
    fn apply(&mut self, input: T) -> Result<Option<U>, &'static str>;
}

pub struct Block<T, U> {
    pub tx_input: mpsc::Sender<T>,
    pub rx_output: mpsc::Receiver<U>,
    pub handle: JoinHandle<Result<(), &'static str>>,
}

impl<T: Send, U: Send> Block<T, U> {
    pub fn from<B: BlockFunctionality<T, U> + Send>(b: B) -> Self {
        let (tx_input, mut rx_input) = mpsc::channel(10);
        let (mut tx_output, rx_output) = mpsc::channel(10);

        let handle: JoinHandle<Result<(), &'static str>> = tokio::spawn(async move {
            let mut owned_b = b;

            while let Some(t) = rx_input.recv().await {
                match owned_b.apply(t)? {
                    Some(u) => tx_output
                        .send(u)
                        .await
                        .map_err(|_| "Unable to send output")?,
                    None => (),
                }
            }

            Ok(())
        });

        Block {
            tx_input,
            rx_output,
            handle,
        }
    }
}

When I try to compile this, I get this error for B and a similar one for the other two type parameters:
   |
22 |     pub fn from<B: BlockFunctionality<T, U> + Send>(b:B) -> Self {
   |                 -- help: consider adding an explicit lifetime bound...: `B: 'static +`
...
27 |         let handle:JoinHandle<Result<(), &'static str>> = tokio::spawn(async move {
   |                                                           ^^^^^^^^^^^^ ...so that the type `impl std::future::Future` will meet its required lifetime bounds

I'm having a hard time understanding where the problem is with lifetimes.  The way I understand it, lifetime problems usually come from references that don't live long enough, but I'm moving values, not using references.  I move b, rx_input, and tx_output into the closure and I keep tx_input, rx_output, and handle in the calling scope.  Does anyone know how to satisfy the compiler in this case?

A: Those values may be references or contain references. Reference types are valid types: B could be &'a str. Or B could be SomeType<'a>, a type with a lifetime parameter, that itself contains a &'a str.
To say that B: 'static means that all lifetime parameters of B outlive 'static (ref). For example, types which own their own data and thus have no lifetime parameters (e.g. String) satisfy this bound. But &'static str also satisfies the bound.
Because tokio::spawn creates something whose lifetime is not statically scoped, it requires a 'static argument.
So to satisfy the compiler, add the 'static bounds:
impl<T: 'static + Send, U: 'static + Send> Block<T, U> {
    pub fn from<B: 'static + BlockFunctionality<T, U> + Send>(b:B) -> Self {


text:
Q: select a column and filter values with select2 angularjs i am very new to angularjs. now i have a data table and a filter. in the filter, i have 2 select:column and value. pick a column and filter with the value. my idea is as following:

          <select ng-model="f.column"
                  ui-select2
                  placeholder="Column"
                  class="form-control input-sm"
                  ng-change="filterChange()">
            <option ng-repeat="c in params.columns" value="{{c}}">{{elementMap[c].label}}</option>
          </select>

        <select class="form-control input-sm"
                  ui-select2
                  ng-model="f.value"
                  ng-change="filterChange()">
           <option ng-repeat="row in data.results" value="{{row.(f.column)}}">{{row.(f.column)}}</option>
        </select>

f.column is binded to the column name i pick up.
i need something like {{row.(f.column)}} which angularjs doesn't recognize.
is there any way to work around it?
thanks

A: This directive is now obsolete. A new initiative, more active, and 100% angular is available at https://github.com/angular-ui/ui-select.


text:
Q: ruby URI.escape and URI.encode and URI.parse error ruby version 2.2.2
url = "http://www.rugbyontario.com/AboutUs/NewsStories/LatestNews/tabid/15402/sni[20577]/4831/language/en-US/Default.aspx"
URI.parse(URI.encode(url))

This gives:
*** URI::InvalidURIError Exception: bad URI(is not URI?): http://www.rugbyontario.com/AboutUs/NewsStories/LatestNews/tabid/15402/sni[20577]/4831/language/en-US/Default.aspx

The actual url is working in browser, and I am already trying to escape it, it still gives me an error. Is there a better way to do this?

A: I must admit that I'm not very used to reading RfCs, however, from what I could gleam from RfC3986, [ and ] are indeed illegal in the path component of a URI. So, Ruby is right: the URI is invalid.
The fact that your browser accepts it doesn't mean a thing. Browsers have been known to accept broken input in order to not annoy non-technical users.

A: I am using addressable gem now, this one escapes the urls correctly in this case.


text:
Q: MySQLi result null second time I use it I'm trying to run a second query using the results of my first query to set a flag for all the rows that were just retrieved. The first time I use my result to output JSON it works fine, but the second time I try to call fetch_assoc() from it, the array comes back NULL.
        $result = API::$connection->query($query);

        if (!mysqli_error(API::$connection))
        {
            API::setHeader(200);
            // return json encoded results

                        /// This works just fine, outputs JSON
            echo JSONizer::jsonEncodeSqlResultWithKeys( $result, array (
                                                                'pId',
                                                                'sender',
                                                                'receiver',
                                                                'content',
                                                                'notified',
                                                                'opened',
                                                                'time' ) );

            // initial update query
            $query = 'UPDATE messages
                    SET received=1
                    WHERE ';

            // start by cycling through each pId received and tack each onto query
            $counter = 0;

                            // this never runs because the associated array returns NULL now
            while ($row = mysqli_fetch_assoc($result));
            {
                $pId = $row['pId'];

                // concat query
                $query .= 'pId='.$pId;

                // if there's still more to go, tack on OR
                if ($counter++ != count($result))
                {
                    $query .= ' OR';
                }
                else
                {
                    $query .= ';';
                }

            }

I've tried object and procedural style on calling fetch_assoc, did not make a difference. I tried copying the result into another variable to use, but that was NULL as well. Why would this only work once, but not a second time.


text:
Q: Python argparse: default argument stored as string, not list I cannot figure out this behaviour of argparse from the documentation:
import argparse

parser.add_argument("--host", metavar="", dest="host", nargs=1, default="localhost", help="Name of host for database.  Default is 'localhost'.")
args = parser.parse_args()
print(args)

Here is the output with and without an argument for "--host":
>> python demo.py
Namespace(host='localhost')

>> python demo.py --host host
Namespace(host=['host'])

In particular: why does the argument to "--host" get stored in a list when it is specified but not when the default is used?

A: Remove the "nargs" keyword argument. Once that argument is defined argparse assumes your argument is a list (nargs=1 meaning a list with 1 element)

A: As an alternative and handy module: Docopt can be used for parsing command line arguments. Docopt transform a commandline into a dictionnary by defining values inside doc.

A: The question title and the question body ask two different questions. This is potentially a sign of the confusion I shared with the OP.
The title: why is the default a string not a list?
The body: why is the given value a list not a string?
The selected answer provides the solution to the question in the body. The answer to the question in the title is:
The entry default="localhost" sets default to "localhost", which is a sting. To set it as a list, you could use: default=["localhost"].


text:
Q: Pandas Cleaning up I have an excel file in this format and I am trying to read it in Pandas and clean it up:

I read in the file with read_excel and created a multiindex level starting from row 7([2013,2016,2017...]
    df= pd.read_excel(PATH_CY_TABLE, header= [7,8,9])

This is how it read in:

Ideally, I want to clean up to look something like this:

What steps can I follow to get it this format?
Couple of things I have tried are:
1. remove the level 1 of multi index: where the columns names appears as 'unnamed...'
    df.columns= df.columns.get_level_values(1)

This gives me an error: IndexError: Too many levels: Index has only 1 level, not 2

*Stacking the columns indices:
df.stack()

This gives me an error: TypeError: '>' not supported between instances of 'str' and 'int'

*I tried this:
df.columns=df.columns.get_level_values(0)

And this gave me the first level of MultiIndex as [2013, 2013, 2013, 2016,2016,2016...]. But I want the output df to have two levels of indices here: Level 0 and Level 3.
As a first step I am looking to remove the 'Unnamed...' columns names. I have tried to post the df as an output instead of pictures, but unsure how to do them in the correct way- when I copy paste from jupyter notebook, they paste all messed up. I am quite new to posting questions here..so still working my way around.

A: I wasn't still able find a better way to post my output but I worked around a way to clean up the file to the desired output:
I sliced the MultiLevelIndex level 0 to match year I want(2017)
    df1= df
    df1= df1.iloc[:, df1.columns.get_level_values(0)== 2017]

Out:
                                                     Number      MOE1 (±)  Rate
    Total..........................................…  323156.0    123.0     X
    NaN                                                    NaN      NaN   NaN
    Any health plan……………….……...…                      294613.0    662.0  91.2
    NaN                                                    NaN      NaN   NaN
   .Any private plan2,3………………………                     217007.0   1158.0  67.2


text:
Q: How to assign sample_weights in sklearn.cluster DBSCAN? I'm using DBSCAN to find clusters of pixel values of an RGB image.
db = DBSCAN(eps=0.3, min_samples=10).fit(X)
where, X is an N x 3 matrix. Each row of X contains RGB triplets.
Now, I want to assign weights to pixel values as a function of distance from the center of the image.
And this is the function I'm using:
score =  1 / (1 + math.exp(-a * distance)) # a = 0.001
I compute weight_matrix filled with score as above
Next I did this:
db = DBSCAN(eps=0.3, min_samples=10).fit(X,y=None, sample_weight=weight_matrix)
where, length of the weight_matrix array is equal to the number of rows in X.
But I get the following error:
TypeError: fit() got an unexpected keyword argument 'y'
So I tried doing it like this:
db = DBSCAN(eps=0.3, min_samples=10).fit(X, sample_weight=weight_matrix)
Now I get this error:
TypeError: fit() got an unexpected keyword argument 'sample_weight'
I think I'm passing the arguments incorrectly, but couldn't be sure. My scikit-learn version is 0.14.0.

A: It seems that you are using scikit-learn v <= 0.15, as this is the last version where DBSCAN had fit of form
fit(X)

since 0.16 it is
fit(X, y=None, sample_weight=None)

Simply update your scikit-learn to 0.16 or 0.17.X


text:
Q: How to apply a variable in Azure Pipelines to a node app during build I have created a Framework7.io website that uses the Svelte plugin.
It's using webpack.
I can pass in an environment variable, as part of the npm script - for example:

The variable is then picked up in the webpack.config.js file:

This works locally, just fine.
When using Azure Pipelines, how can I apply a variable in place of hardcoding?
I tried switching out my actual URL with a variable, setup in Azure Pipelines. I.E $(MY-BASE-URL) - though it's not actually being replaced.

How do we apply pipeline variables to the build?

A:
How do we apply pipeline variables to the build?

You could try to use the Replace Tokens task from the Replace Tokens Extension.
Here are the steps:

*

*Set the #{varname}# (e.g. #{MY-BASE-URL}# ) in the package.json file

*Set Pipeline variables and use the Replace Token task.

Result:

Update:
You could use the $variablename(e.g. $MYBASEURL) in package.json.
Then it will directly get the value from pipeline variable.
Note: Based on my test, the - character will truncate variable names. I suggest you could change to use _ (e.g. $MY_BASE_URL)


text:
Q: Creating a Location object in TypeScript I'm having trouble redirecting my app outside of Angular to the logout page.
I'm doing it by using $window.location.href but it's not working on FireFox.
So, There was a suggestion to use $window.location directly but since i'm writing in Typescript i need to create a new Location object rather then just assign my string to it...
I looked into lib.d.ts and i saw that location is declared as:
declare var Location: {
    prototype: Location;
    new(): Location;
}

so i adjust my code to:
var url: string = "http:\\\\host:port/blabla/logout";
var loc: Location = new Location();
loc.href = url;
this.$window.location = loc;

but got this error:
Error: Illegal constructor.

Any Idea how to create the Location object? Is it a good practice to do so?
Any other insights maybe?
Thanks

A: It actually looks like you're not supposed to build new Location objects. So I don't think there's a constructor available anywhere for this. Though you can use anchors to build them for you.
If you're trying to set a new location, you can go with setting window.location.href instead of window.location (These two are equivalent).

A: If you want to assign a String directly and just make TypeScript go along with that, you can do
 window.location = <any>"http://host:port/blabla/logout";


text:
Q: Redirect subdomain of wordpress admin using .htaccess with query strings I have been browsing the internet and haven't been able to find a solution to this, so any help would be much appreciated.
Scenario
I would like to redirect my subdomain file with query strings by appending another query string. For example:
https://sub.domain.com/wp-admin/admin.php?foo=bar&key=value

to
https://sub.domain.com/wp-admin/admin.php?foo=bar&key=value&new=string

Attempts
I need to add this redirect rule in .htaccess. I have tried QSA append but to no avail:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{QUERY_STRING} key=value
    RewriteRule ^admin\.php$ /admin.php?new=string [QSA,L]
</IfModule>

What do you think the solution is?

A: Your existing rule is an internal rewrite. To make this into a redirect, you just need to add the R flag. However, you also appear to be missing the /wp-admin path segment in the URL?
So, try something like:
RewriteCond %{QUERY_STRING} key=value
RewriteCond %{QUERY_STRING} !^new=string
RewriteRule ^wp-admin/admin\.php$ /wp-admin/admin.php?new=string [R,QSA,L]

As in your original code, this just checks for key=value in the query string, not foo=bar&key=value as in the source URL.
UPDATE: The second RewriteCond directive prevents a redirect loop by making sure that new=string is not already present at the start of the query string.
The QSA flag results in the query string on the request being appended to the substitution. So, the resulting URL will become ...?new=string&foo=bar&key=value, not ?foo=bar&key=value&new=string as in your initial requirement - is that a concern?

UPDATE: If you specifically need the new=string URL param appended to the query string then you should remove the QSA flag and use the QUERY_STRING server variable instead. For example:
RewriteCond %{QUERY_STRING} key=value
RewriteCond %{QUERY_STRING} !new=string$
RewriteRule ^wp-admin/admin\.php$ /wp-admin/admin.php?%{QUERY_STRING}&new=string [R,L]


text:
Q: how to catch changes in a member variable? (C#) This seems to be basics of the language, but I do not understand how is this accomplished in .Net. I have a member variable in a class, say a bool _isCommitted. I want something to happen whenever _isCommitted is true. Something like this:
     //Whenever _isCommitted == true()
     {
         Foo()
     }

Basically like an event, but here it is my variable. How to? Many thanks..

A: At the most basic level, you can create an event in your class:
public delegate void MyHandler(bool b);
public event MyHandler CommittedChanged;

Now people can subscribe to your event like so:
public void SomeHandlerMethod(bool b) { ... }

...

someInstance.CommittedChanged += SomeHandlerMethod;
someInstance.CommittedChanged += ASecondHandlerMethod;
someInstance.CommittedChanged += x => { /* inline handler using lambda */ };

A user can unregister his event handler this way:
someInstance.CommittedChanged -= SomeHandlerMethod;

And wherever you decide to change your variable, you will follow it up with:
if (CommittedChanged != null) CommittedChanged(_isCommitted);

This will call everyone who has registered a function with your event.
Having said this, there are plenty of improvements that you can do.  First, make _isCommitted into a property, and do the event callback in its setter.  This way, you won't forget to call the handlers.
public IsCommitted {
   get { return _isCommitted; }
   set {
     _isCommitted = value;
     if (CommittedChanged != null) CommittedChanged(_isCommitted);
   }
}

Read more about events here.
This is enough to get you going.  However, if you delve further into the C# framework, you will find a standardized way of using this event framework inside of the System.ComponentModel namespace.  Sepcifically, the interface INotifyPropertyChanged, which ties neatly into a more generic event system that also plays well with some of Microsoft's own technologies, such as WPF, allowing GUI elements to pick up on changes to your class automatically.  Read more about INotifyPropertyChanged here.

A: This is normally done through properties and a backing private field. You need to ensure you only ever access through the property.
private bool _isCommitted;

public bool IsCommitted
{
  get { return _isCommitted; }
  set
  {
     if(value)
     {
        //do something
     }

     _isCommitted = value;
  }
}

A: You basically need PropertyChangedEvent PropertyChangedEventHandler Delegate

A: I think C# properties is what you need.
private bool _isCommitted;

    public bool IsCommitted
    {
        get { return _isCommitted; }
        set { if(value){/*DO SOMETHING HERE*/}
            _isCommitted = value; }
    }


text:
Q: how to automatically repair table if crashed sometimes if a table is marked as crashed, a simple
REPAIR TABLE `tablename`

works fine to continue.
how do I add an automatic repair in my PHP script?
I get the error:
1194 - Table 'whos_online' is marked as crashed and should be repaired

A: This is very unlikely to make sense.
If you need to repair tables so frequently that you need to automate it, there's something wrong with your setup. You need to fix the root cause in that case.
An automated solution would also be difficult to implement. You'd have to parse the mySQL error message to find out whether the reason your query failed is maybe related to a broken table. There are thousands of different possible reasons why a query could fail.
The usual way is to monitor what is going on on the web site, and having an administrator react to problems. You could, for example, have your web app send you an E-Mail when a query fails.


text:
Q: Unable to obtain Matrix in C Following is the code to obtain matrix like 11  12  13 etc... I am not getting desired results since long. Help me with the solution.
#include<stdio.h>

int main() {
    int i,j;

    for(i=1;i<5;i++){
        for(j=1;j<5;j++){
            printf("%d %d",i,j);
        }
        printf("\n");
    }

    fgetc(stdin);
}

A: Probably because you have a space between the digits:
printf("%d %d",i,j);

Shouldn't it be:
printf("%d%d ",i,j);

for your desired output?

A: Shouldn't printf("%d %d",i,j); actually be printf("%d%d ",i,j);?


text:
Q: How to create List row seperate one another in SwiftUI I'm new in SwiftUI
I'm trying to create my section like this, where each row is separated with another. Kinda like section where the background is not connected one another. take a look at the pict: (picture from dribbble)

but mine ended up like this:
(I created the bg blue so that y'all can see the rows clearly)

here's my code:
import SwiftUI

struct ProductPageView: View {

init() {
        UITableView.appearance().backgroundColor = .clear // Uses UIColor
    }

var body: some View {
    NavigationView {
        ZStack {
            Color.blue.edgesIgnoringSafeArea(.all)
            VStack {
                List {
                    ForEach(arrayProduct, id: \.name) { dataProduct in
                        ProductListCell(item: dataProduct)
                    }
                    .listRowInsets(EdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10))
                }
                .listStyle(InsetGroupedListStyle())
            }
        }
        .navigationTitle("Produk")
    }
}
}

I've used listRowInsets but it's just stretch it.
How do I create that separation between rows?
Any help will be appreciated.
Thank you

A: I did not attempt a pixel perfect reproduction since I don't have the assets, but the following outlines one way you can accomplish this.

Comments are in the code to explain some of the key pieces:
import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView {
            ZStack {
                Color.blue.edgesIgnoringSafeArea(.all)
                VStack {
                    // This handles the display of the
                    // section header
                    HStack {
                        // The text & spacer are grouped
                        // so that you can pad accordingly
                        Text("Stuff")
                        Spacer()
                    }
                    .padding(.bottom, 2)
                    .padding(.leading, 10)
                    // A VStack contains your list of items
                    VStack {
                        ForEach(0...3, id: \.self) { element in
                            // Each grouping (a product for you)
                            // will exist within this top level
                            // HStack
                            HStack {
                                // A new HStack (or another view of
                                // your choice) will contain the views
                                // that compose your product entry
                                HStack {
                                    Text("\(element)")
                                    Spacer()
                                }
                                .padding() // Provides some buffer around the product
                                .background(Color.white)
                                .contentShape(Rectangle()) // For tapping
                                .cornerRadius(5.0)// Rounding!
                            }
                            // Custom padding can tailor your spacing needs
                            .padding([.top, .bottom], 2)
                            .padding([.trailing, .leading], 10)
                        }
                    }
                    Spacer()
                }
            }
            .navigationTitle("Produk")
        }
    }
}


text:
Q: jQuery Click event not getting triggered I am add a table to a plain HTML page after document ready using jQuery
The value that I get is a string of "

Name	Father name.... Delete
 "
jQuery method:
$(function () {
  $.ajax({
    url: "/Account/Report",
  }).done(function (callback) {
    $('#report').html(callback);
  });
});

I am able to bind the string withing a div #report but the following is not working.
$('.deleteEmployee').click(function () {
console.log('Clicked');
});

I thought that DOM might have not been updated but I am able to see the anchor element and table updated.
What am I missing out over here.

A: If you want to attach events to dynamically loaded content you have to attach the event to the document and use a selector like this:
$(document).on("click",".deleteEmployee",function(){
    console.log("Clicked");
});

A: You can bind click method after ajax load is done ...
$(function () {
  $.ajax({
    url: "/Account/Report",
  }).done(function (callback) {
    $('#report').html(callback);

            $('.deleteEmployee').click(function () {
            console.log('Clicked');
            });

  });
});

A: load() which i like most... as above
$('#report').load("/Account/Report",function (callback) {

        $('.deleteEmployee').click(function () {
        console.log('Clicked');
        });
})


text:
Q: Convert.ToString returns `System.Byte[]` and not the actual data as GROUP_CONCAT returns BLOB I have one method which is calling MySQL procedure. Below is part of the procedure:
SELECT AR.alert_id AS AlertId,
        AR.rule_id AS RuleId,
        AR.name AS RuleName,
        AR.rule_type AS RuleType,
        AR.description AS Description,
        (SELECT group_concat(occured_event_id separator ', ')
            FROM alert_rule_event
            WHERE alert_rule_id = AR.id) AS OccuredEventIds,
FROM alert_rule AR

C# code:
alertRuleEntity.AlertId = Convert.ToInt32(dtAlertRuleEntityList.Rows[index]["AlertId"]);
alertRuleEntity.RuleId = Convert.ToInt32(dtAlertRuleEntityList.Rows[index]["RuleId"]);
alertRuleEntity.RuleName = Convert.ToString(dtAlertRuleEntityList.Rows[index]["RuleName"]);
alertRuleEntity.RuleType = Convert.ToString(dtAlertRuleEntityList.Rows[index]["RuleType"]);
alertRuleEntity.Description = Convert.ToString(dtAlertRuleEntityList.Rows[index]["Description"]);
alertRuleEntity.OccuredEventIds = Convert.ToString(dtAlertRuleEntityList.Rows[index]["OccuredEventIds"]);

It is returning values as follows:

It is able to read all column values properly. But In case of column OccuredEventIds it is giving value as System.Byte[] rather than its actual value. What could be the problem?

A: After making following change to my procedure it worked:
(SELECT group_concat(CONVERT(occured_event_id, CHAR(8)) separator ', ')
FROM alert_rule_event
WHERE alert_rule_id = AR.id) AS OccuredEventIds

A: I would try casting your parameters to group_concat to a varchar first as the documentation says that it converts binary parameters to a BLOB.
SELECT AR.alert_id AS AlertId,
        AR.rule_id AS RuleId,
        AR.name AS RuleName,
        AR.rule_type AS RuleType,
        AR.description AS Description,
        (SELECT group_concat(cast(occured_event_id as char(20)) separator ', ')
            FROM alert_rule_event
            WHERE alert_rule_id = AR.id) AS OccuredEventIds,
FROM alert_rule AR

A: Group_Concat Return BLOB type so only you get Bytes as output,
Sol-1 :
Change the value of the group_concat_max_len system variable to 512
and Restart the MySql Service
See here : Why GROUP_CONCAT returns BLOB?
OR
Sol-2 :
SET "respect binary flags=false;" in your Connection string
Hope this helps you....


text:
Q: How to continue using docker container after startup application exit? I want to create docker image that will start nano editor after running and give users possibilities continue work after nano closing.
For that I wrote next Dockerfile
FROM ubuntu:14.04
RUN apt-get update && apt-get install -y nano
RUN mkdir /home/working
ENV EDITOR /bin/nano
WORKDIR /home/working
ENTRYPOINT /bin/nano

After running container (docker run -it --rm test) nano starts, but after exiting off nano, container closes. I want to continue work into ubuntu container after closing nano. What should i change in my Dockerfile?

A: i wouldnt set the ENTRYPOINT to nano. better use /bin/bash.
FROM ubuntu:14.04
RUN apt-get update && apt-get install -y nano
RUN mkdir /home/working
ENV EDITOR /bin/nano
WORKDIR /home/working
ENTRYPOINT /bin/bash

now you can (if the container is running) access the container with
docker exec -it <containername> /bin/bash

and use nano as often as you want. for example to edit multiple files. after you close nano /bin/bash is still running and the container doesnt exits.


text:
Q: LibreOffice: embed script in script URL In LibreOffice, It is possible to run python scripts like this:
sURL = "vnd.sun.star.script:file.function?language=Python&location=document"
oScript = scriptProv.getScript(sURL)
x = oScript.Invoke(args, Array(), Array())

In that example 'file' is a filename, and 'function' is the name of a function in that file.
Is it possible to embed script in that URL? sURL="vnd.." & scriptblock & "?language.."
(It seems like the kind of thing that might be possible with the correct URL, or might not be possible if just not supported).

A: We can use Python's eval() function. Here is an example inspired by JohnSUN's explanation in the discussion. Note: xray() uses XrayTool to show output, but you could replace that line with any output method of your choosing, such as writing to a file.
def runArbitraryCode(*args):
    url = args[0]
    codeString = url.split("&codeToRun=")[1]
    x = eval(codeString)
    xray(x)

Now enter this formula in Calc and Ctrl+click on it.
=HYPERLINK("vnd.sun.star.script:misc_examples.py$runArbitraryCode?language=Python&location=user&codeToRun=5+1")

Result: 6
Obligatory caveat: Running eval() on an unknown string is about the worst idea imaginable in terms of security. So hopefully you're the one controlling the URL and not some black hat hacker!


text:
Q: Haskell foldr with multiplication I'm supposed to write a function that will contain the product of each previous multiplication with that number
Basically this:
> productFromLeftToRight [2,3,4,5]
[120,60,20,5]

I'm supposed to use High Order functions, so folds and such. I'm thinking of using a foldr to traverse through the list with a lambda expression. This is what I'm thinking:
> productFromLeftToRight nums = foldr (\x acc -> [x] * acc ++ acc) [] nums

Since it would unravel like f(2 (f 3 (f 4 (f 5 [])))) I would think I'm right, but I get the whole print error and I don't know how to multiply a number with the first element of acc ( head acc doesn't work)

A: productFromLeftToRight = scanr1 (*)

or
productFromLeftToRight' =
  snd . foldr (\x (acc,lst) -> (x * acc, x * acc : lst)) (1,[])

A: productFromLeftToRight nums =
    init $ foldr (\x lst -> x * head lst : lst) [1] nums

The idea is to use a dummy element 1 to the answer list and remove it in the end.

A: Here's another one that doesn't do any post-processing after the foldr:
productFromLeftToRight = foldr (\n ps -> n * foldr const 1 ps : ps) []

Here, the inner foldr const 1 is acting as a non-partial head function to get the first element of ps:
foldr const 1 (x:xs) = const x (foldr const 1 xs) = x
foldr const 1 []     = 1


text:
Q: What is the use of "and not" in Python? why does the code not work without the "and not found". What is the use of this statement?
def BinarySearch(alist, item):
  first=0
  last=len(alist)-1
  found=False
  while first<=last and not found:
    midpt= (first+last)//2
    if alist[midpt] == item:
      found=True
    else:
      if item < alist[midpt]:
        last=midpt-1
      else:
        first=midpt+1
  return(found)

alist=[1,2,3,4,5]
item=8
print(BinarySearch(alist,item)

)

A: It's not a statement, it's an expression (three expressions*, really).
If you remove the and not found part, the search will not stop when it finds the item, it will keep going until it reaches the end. With the and not found, it stops when it finds the item.
In your case, since you're looking for something in the list that won't be found (8), it doesn't make any difference. But if you look for, say, 3, it will.

* Unnecessary detail:

*

*Accessing a variable is an expression that results in the value the variable contains, so the found in and not found is an expression.

*not v1 (where v1 is the value from #1) is the second expression: It takes the given value and negates it.

*v0 and v2 (where v2 is the value from #2 and v0 is the result of the expression before and not found) is the third expression: Its result is true when both of its operands are true, false otherwise.

A: found is a boolean flag to indicate whether you've found the item you've been looking for. Once you've found it, there's no point to continue looking for it, and you should just return it.
An arguably neater implementation would be to use the early-return paradigm and just return True once the item is found:
def BinarySearch(alist, item):
  first = 0
  last = len(alist) - 1
  while first<=last:
    midpt = (first+last)//2
    if alist[midpt] == item:
      return True

    if item < alist[midpt]:
      last = midpt - 1
    else:
      first = midpt + 1

  return False


text:
Q: Gabriel's horn, calculus Integration Gabriel's horn is formed by revolving the curve $y=1/x$ for $x\in [1,\infty)$ about the $x$-axis.
Find the volume inside Gabriel's horn. I have the answer but I can't seem to get it right. Can someone explain please?

A: What you should do for finding the result is to evaluate the following integral $$\int_1^\infty \pi y^2 dx$$ in which $y=\frac{1}{x}$. You can draw a disc as you see in fig below. We build this disk on $x$- axes, so the volume of it is the volume of colored cylinder. What is that volume? It is $\pi r^2 h$. What is $r$ and what is $h$? indeed, $r$ is $y$ and $h$ is $dx$.

A: $$ x \, y = a^2$$
starting point  $(a,a)$
end point  $(\infty, 0)$
$$ \int_a^\infty { \pi y^2 \, dx} = \pi a^3 $$
which is $ \frac 34 $ th volume of sphere of radius $a.$


text:
Q: "Sort by random" in OSX Finder setting kMDItemFinderComment to a random hash for every file in a folder? Finder allows you to sort files by many different attributes.
In the OSX filesystem, there is an attribute on every file called "comments" (com.apple.metadata:kMDItemFinderComment) which allows you to add any arbitrary string data as metadata for that file.
Finder exposes this "comment" attribute in the GUI and you can "sort" by it. I thought I could abuse this attribute to fill in random data for the each files "comments", and then sort by those random comments.
tldr; I'm trying to create "sort by random" functionality (in Finder) with the help of a BASH script and some python.
this does work to achieve that (sort of):
find $1 -type f -print0 | while IFS= read -r -d $'\0' file; #get a list of files in the dir
  do
  if [[ $file == *.wav ]]
    then
        hash=$(openssl rand -hex 12); #generate a random hash
        osxmetadata --set findercomment "$hash" $file; #set the comment
    fi
done

here i'm using the osxmetadata python utility to do the heavy lifting.
and while it works as intended, but it's really slow:
https://i.stack.imgur.com/d7exk.gif
i'm trying to do this operation on folders with many items, and would frequently be "re-seeding" the files with random comments.
can anyone suggest an optimization i can try to make this faster? i tried using xattrs but that doesn't seem reindex the comments in finder when they update.

A: I'd wrap the then-clause in a (...)& and add a wait after the loop. Then it will do every file in parallel.


text:
Q: The distribution of hitting time of a random walk Suppose we have a random walk $X_n=X_0+\sum_{k=1}^n \xi_k$ where $\xi_k, k=1,2,3,...$ are i.i.d. Bernoulli random variables whose distribution is $P(\xi_k=1)=p$ and $P(\xi_k=-1)=1-p=q$, and $X_0$ is an integer. Let $a<X_0<b$ and $\tau = \inf\{n:X_n \in \{a,b\} \}$, and set the filtration $\mathscr{F}_n = \sigma(\xi_k, k=1,2,3,...)$. I want to compute the distribution of $\tau$.
Let $u(x)=E[z^{\tau}|X_0=x]$, where $|z|<1$. Then we have:
\begin{cases}
u(x)=(pu(x+1)+qu(x-1))z \\
u(a)=u(b)=1
\end{cases}
I generally have two questions:

*

*I know $u(x)=(pu(x+1)+qu(x-1))z$ is right, and generally we should have $E[z^{\tau}|X_k=x]=z^k E[z^{\tau}|X_0=x]=z^k u(x)$. But I need a rigorous "proof" to convince my self. I tried this:
\begin{align}
u(x) &= E[z^{\tau}|X_0=x]\\
&= E[z^{\tau}|X_0=x, X_1= x + 1]P(X_1= x + 1) + E[z^{\tau}|X_0=x, X_1= x - 1]P(X_1= x - 1)\\
&=pE[z^{\tau}|X_0=x, X_1= x + 1] + qE[z^{\tau}|X_0=x, X_1= x - 1]\\
&=pE[z^{\tau}|X_1= x + 1] + qE[z^{\tau}|X_1= x - 1]\\
&=(pE[z^{\tau-1}|X_1= x + 1] + qE[z^{\tau-1}|X_1= x - 1])z\\
&=(pE[z^{\tau}|X_0= x + 1] + qE[z^{\tau}|X_0= x - 1])z\\
&=(pu(x+1)+qu(x-1))z
\end{align}
How to justify $E[z^{\tau}|X_0=x, X_1= x + 1] = E[z^\tau |X_1=x+1]$? I guess it is because $X_n$ is markovian, but just don't know how to justify that equation step by step.
And, for $E[z^{\tau-1}|X_1= x + 1] = E[z^{\tau}|X_0= x + 1]$, I know it is very obvious to explain it in words. Is there any way to prove it rigorously in math?

*How to solve the equation? It seems we have the boundary condition, and we can start from boundary. But I still don't know what is the right direction.
Thank you for any help!


text:
Q: Swift - Inserting image onto PDF no longer working on iOS 13 Currently working on a feature to export a PDF on my loan calculator app. I have a preview screen that'll show the PDF before you save it. The preview screen composes of a webView with html that contain placeholders. I was able to successfully insert an image onto the correct placeholder and have it display onto the PDF. But with iOS 13, the image no longer shows or it displays too small.
LineGraph.html

    Amortization Line Chart

Code that converts the image to Base-64 encoded string and place it in #ImageData#
let isLineGraphSelected = lineGraphDictionary[.isSelectedString] as! Bool
self.lineGraphSnapshot = lineGraphDictionary[.snapshotString] as? UIImage
    if isLineGraphSelected && self.lineGraphSnapshot != nil{
        let data = self.lineGraphSnapshot.pngData()
        if let imageITData = data?.base64EncodedString() {
            LineGraphHTMLContent = LineGraphHTMLContent.replacingOccurrences(of: "#ImageData#", with: imageITData)
                    }
                } else {
                    LineGraphHTMLContent = ""
                }

Let me know if you need more context.
Screenshots:
iOS 12.1

iOS 13.0

Here's my other HTML files for full context
PDFSheet.HTML
<!doctype html>

        <meta charset="utf-8">

        #RESULTS#
        #LINE_GRAPH#

Results.HTML

                            #LOAN_NAME#

                            #DATE_CREATED#

                Loan information

                Loan amount

                #LOAN_AMOUNT#

                Interest rate

                #INTEREST_RATE#

                Number of payments

                #NUM_OF_PAYMENTS#

                Extra payments

                #EXTRA_PAYMENTS#

                Estimated payoff date

                #PAYOFF_DATE#

                Results

                Monthly Payments

                #MONTHLY_PAYMENTS#

                Total interest

                #TOTAL_INTEREST#

                Interest Savings

                #INTEREST_SAVINGS#

                Time saved

                #TIME_SAVED#

                Total loan amount

                #TOTAL_LOAN#

It also can be possible that the function I used to capture the image was affected in iOS 13. I noticed that when I increase the width of the image to a crazy amount in my CSS, the image was very low res. This makes me think that the image being generated is very small in iOS 13. Why? I have no godly idea.
func takeScreenshot() -> UIImage {

        // Begin context
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, UIScreen.main.scale)

        // Draw view in that context
        drawHierarchy(in: self.bounds, afterScreenUpdates: true)

        // And finally, get image
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        if (image != nil)
        {
            return image!
        }
        return UIImage()
    }

New Discovery
I believe the issue is in the takeScreenshot function above. I printed out the image variable and this is what I found.
iOS 12
Optional(<UIImage: 0x6000016fc070> size {575.33333333333337, 350} orientation 0 scale 3.000000)

iOS 13
Optional(<UIImage:0x6000013637b0 anonymous {575.33333333333337, 350}>)

Why did size got replaced with anonymous and why are orientation and scale missing? If I can answer this then I can solve this annoying issue.

Solved
I found the issue. My solution is posted below.

A: To solve this issue you can add/assign height and with using two way, One is, assign height and width in line-graph class OR second assign height and width by percentage(%) or pixel(px) in an inline-style method in
 tag see the following code.

OR

    Amortization Line Chart

A: I solved the problem.
I replaced drawHierarchy with draw.
func takeScreenshot() -> UIImage {

    // Begin context
    print(UIScreen.main.scale)
    print(self.bounds.size)
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, UIScreen.main.scale)

    // Draw view in that context
    draw(self.bounds) //drawHierarchy(in: self.bounds, afterScreenUpdates: true)
    // And finally, get image
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    print(image)
    if (image != nil)
    {
        return image!
    }
    return UIImage()
}

I am not entirely sure why that worked so if anyone could enlighten me that'll be great.


text:
Q: Heroku application App crashed can't get path I am trying for the first time to use Heroku, my app works fine on the local machine, and it builds successfully on Heroku but when I try to open it I get the following errors, full logs at the end
2020-05-02T16:35:34.660563+00:00 heroku[web.1]: State changed from starting to crashed
2020-05-02T16:35:42.610766+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=warm-tundra-79939.herokuapp.com request_id=d3ccbec7-c4a3-4805-8df5-ea8f39b82001 fwd="72.137.75.96" dyno= connect= service= status=503 bytes= protocol=https
2020-05-02T16:35:43.084078+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=warm-tundra-79939.herokuapp.com request_id=09e01082-777c-4b95-a556-c2b85d9fe192 fwd="72.137.75.96" dyno= connect= service= status=503 bytes= protocol=https

here is the index.html

<!DOCTYPE html>

    <meta charset="utf-8" />

    <meta name="viewport" content="width=device-width, initial-scale=1" />

<meta property="og:image" content="http://euro-travel-example.com/thumbnail.jpg">
<meta property="og:url" content="http://euro-travel-example.com/index.htm">

    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

    <title>testapp</title>

2020-05-05T18:49:55.957210+00:00 app[web.1]:
2020-05-05T18:49:57.832175+00:00 app[web.1]: [34mℹ[39m [90m「wds」[39m: Project is running at http://172.16.247.6/
2020-05-05T18:49:57.832502+00:00 app[web.1]: [34mℹ[39m [90m「wds」[39m: webpack output is served from
2020-05-05T18:49:57.832579+00:00 app[web.1]: [34mℹ[39m [90m「wds」[39m: Content not from webpack is served from /app/public
2020-05-05T18:49:57.832647+00:00 app[web.1]: [34mℹ[39m [90m「wds」[39m: 404s will fallback to /
2020-05-05T18:49:57.832827+00:00 app[web.1]: Starting the development server...
2020-05-05T18:49:57.832827+00:00 app[web.1]:
2020-05-05T18:49:57.930367+00:00 heroku[web.1]: State changed from starting to crashed
2020-05-06T00:26:51.023260+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=warm-tundra-79939.herokuapp.com request_id=cc1a766f-6f8e-4c9d-a905-4db2c5a35123 fwd="72.137.75.96" dyno= connect= service= status=503 bytes= protocol=https
2020-05-06T00:26:51.707295+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=warm-tundra-79939.herokuapp.com request_id=71e0907a-cab5-460a-baae-a8f18a4c6e3c fwd="72.137.75.96" dyno= connect= service= status=503 bytes= protocol=https
2020-05-06T00:27:53.993935+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=warm-tundra-79939.herokuapp.com request_id=3f8f5a51-3f4c-4772-bfd2-def72ff6ba3d fwd="72.137.75.96" dyno= connect= service= status=503 bytes= protocol=https
2020-05-06T00:27:54.533509+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=warm-tundra-79939.herokuapp.com request_id=17c0e361-a681-4a1b-8b91-2b11d27b0889 fwd="72.137.75.96" dyno= connect= service= status=503 bytes= protocol=https
2020-05-06T00:28:40.343274+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=warm-tundra-79939.herokuapp.com request_id=67c5ba4b-cc2a-4bf7-a541-bc85fb5368a7 fwd="72.137.75.96" dyno= connect= service= status=503 bytes= protocol=https
2020-05-06T00:28:40.883375+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=warm-tundra-79939.herokuapp.com request_id=e571e97a-b05a-431c-8977-515877b46794 fwd="72.137.75.96" dyno= connect= service= status=503 bytes= protocol=https
2020-05-06T00:29:25.465162+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=warm-tundra-79939.herokuapp.com request_id=76f11081-66aa-497b-8e36-edf91db8e5af fwd="72.137.75.96" dyno= connect= service= status=503 bytes= protocol=https
2020-05-06T00:29:26.011122+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=warm-tundra-79939.herokuapp.com request_id=8c0ae3f4-bd5a-4b4b-b35c-0d23a62eb904 fwd="72.137.75.96" dyno= connect= service= status=503 bytes= protocol=https
2020-05-06T00:29:29.518382+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=warm-tundra-79939.herokuapp.com request_id=bd11cc44-8174-4668-8a39-e9ad79bd13ed fwd="72.137.75.96" dyno= connect= service= status=503 bytes= protocol=https
2020-05-06T00:29:29.978317+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=warm-tundra-79939.herokuapp.com request_id=317f7164-c003-4ea8-bd6d-bda85b7379d3 fwd="72.137.75.96" dyno= connect= service= status=503 bytes= protocol=https
2020-05-06T00:29:54.655340+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=warm-tundra-79939.herokuapp.com request_id=57bd99b4-b000-4553-acaf-8d73266b3cc9 fwd="72.137.75.96" dyno= connect= service= status=503 bytes= protocol=https
2020-05-06T00:29:55.215061+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=warm-tundra-79939.herokuapp.com request_id=a2d42c76-35b8-42fa-885f-de122556b825 fwd="72.137.75.96" dyno= connect= service= status=503 bytes= protocol=https
2020-05-06T00:30:17.301612+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=warm-tundra-79939.herokuapp.com request_id=59438701-a1a8-4ce9-901a-ad7026be07a4 fwd="72.137.75.96" dyno= connect= service= status=503 bytes= protocol=https
2020-05-06T00:30:17.853183+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=warm-tundra-79939.herokuapp.com request_id=712a931c-60ec-41c0-a1f6-02885e046ec1 fwd="72.137.75.96" dyno= connect= service= status=503 bytes= protocol=https
2020-05-06T00:30:53.000000+00:00 app[api]: Build started by user
2020-05-06T00:32:07.210573+00:00 heroku[web.1]: State changed from crashed to starting
2020-05-06T00:32:06.828499+00:00 app[api]: Deploy 4df36638 by user
2020-05-06T00:32:06.828499+00:00 app[api]: Release v12 created by user
2020-05-06T00:32:14.000000+00:00 app[api]: Build succeeded
2020-05-06T00:32:21.473845+00:00 app[web.1]:
2020-05-06T00:32:21.473861+00:00 app[web.1]: > opentable@0.1.0 start /app
2020-05-06T00:32:21.473861+00:00 app[web.1]: > react-scripts start
2020-05-06T00:32:21.473862+00:00 app[web.1]:
2020-05-06T00:32:25.753013+00:00 app[web.1]: [34mℹ[39m [90m「wds」[39m: Project is running at http://172.18.92.170/
2020-05-06T00:32:25.753629+00:00 app[web.1]: [34mℹ[39m [90m「wds」[39m: webpack output is served from
2020-05-06T00:32:25.753777+00:00 app[web.1]: [34mℹ[39m [90m「wds」[39m: Content not from webpack is served from /app/public
2020-05-06T00:32:25.753895+00:00 app[web.1]: [34mℹ[39m [90m「wds」[39m: 404s will fallback to /
2020-05-06T00:32:25.754229+00:00 app[web.1]: Starting the development server...
2020-05-06T00:32:25.754230+00:00 app[web.1]:
2020-05-06T00:32:25.881428+00:00 heroku[web.1]: State changed from starting to crashed
2020-05-06T00:32:25.884338+00:00 heroku[web.1]: State changed from crashed to starting
2020-05-06T00:32:37.154954+00:00 app[web.1]:
2020-05-06T00:32:37.154971+00:00 app[web.1]: > opentable@0.1.0 start /app
2020-05-06T00:32:37.154971+00:00 app[web.1]: > react-scripts start
2020-05-06T00:32:37.154972+00:00 app[web.1]:
2020-05-06T00:32:39.227810+00:00 app[web.1]: [34mℹ[39m [90m「wds」[39m: Project is running at http://172.18.49.162/
2020-05-06T00:32:39.228215+00:00 app[web.1]: [34mℹ[39m [90m「wds」[39m: webpack output is served from
2020-05-06T00:32:39.228315+00:00 app[web.1]: [34mℹ[39m [90m「wds」[39m: Content not from webpack is served from /app/public
2020-05-06T00:32:39.228403+00:00 app[web.1]: [34mℹ[39m [90m「wds」[39m: 404s will fallback to /
2020-05-06T00:32:39.228613+00:00 app[web.1]: Starting the development server...
2020-05-06T00:32:39.228615+00:00 app[web.1]:
2020-05-06T00:32:39.350859+00:00 heroku[web.1]: State changed from starting to crashed
2020-05-06T00:32:40.270514+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=warm-tundra-79939.herokuapp.com request_id=9eb7556b-8477-448a-b054-f21bbcd43734 fwd="72.137.75.96" dyno= connect= service= status=503 bytes= protocol=https
2020-05-06T00:32:41.800494+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=warm-tundra-79939.herokuapp.com request_id=1f677ae6-ba9b-4141-9077-cca446acb53b fwd="72.137.75.96" dyno= connect= service= status=503 bytes= protocol=https
2020-05-06T00:36:38.633976+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=warm-tundra-79939.herokuapp.com request_id=c8267a8d-40a4-4e85-8917-fd2cbcdb5e26 fwd="72.137.75.96" dyno= connect= service= status=503 bytes= protocol=https
2020-05-06T00:36:39.245883+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=warm-tundra-79939.herokuapp.com request_id=f3d5af60-fcf2-4ffa-935e-731525f167a0 fwd="72.137.75.96" dyno= connect= service= status=503 bytes= protocol=https
2020-05-06T00:45:33.000000+00:00 app[api]: Build started by user
2020-05-06T00:46:05.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/333fe337-28b4-4897-aea2-b6e00e21658c/activity/builds/353cebff-768b-4690-b319-cfd691354e65
2020-05-06T00:49:46.000000+00:00 app[api]: Build started by user
2020-05-06T00:51:00.406504+00:00 heroku[web.1]: State changed from crashed to starting
2020-05-06T00:51:00.150835+00:00 app[api]: Deploy e761a226 by user
2020-05-06T00:51:00.150835+00:00 app[api]: Release v13 created by user
2020-05-06T00:51:07.000000+00:00 app[api]: Build succeeded
2020-05-06T00:51:10.690011+00:00 app[web.1]:
2020-05-06T00:51:10.690025+00:00 app[web.1]: > opentable@0.1.0 start /app
2020-05-06T00:51:10.690026+00:00 app[web.1]: > react-scripts start
2020-05-06T00:51:10.690026+00:00 app[web.1]:
2020-05-06T00:51:12.685464+00:00 app[web.1]: [34mℹ[39m [90m「wds」[39m: Project is running at http://172.16.128.62/
2020-05-06T00:51:12.685820+00:00 app[web.1]: [34mℹ[39m [90m「wds」[39m: webpack output is served from
2020-05-06T00:51:12.685898+00:00 app[web.1]: [34mℹ[39m [90m「wds」[39m: Content not from webpack is served from /app/public
2020-05-06T00:51:12.685967+00:00 app[web.1]: [34mℹ[39m [90m「wds」[39m: 404s will fallback to /
2020-05-06T00:51:12.686185+00:00 app[web.1]: Starting the development server...
2020-05-06T00:51:12.686188+00:00 app[web.1]:
2020-05-06T00:51:12.787345+00:00 heroku[web.1]: State changed from starting to crashed
2020-05-06T00:51:12.790433+00:00 heroku[web.1]: State changed from crashed to starting
2020-05-06T00:51:29.195595+00:00 app[web.1]:
2020-05-06T00:51:29.195636+00:00 app[web.1]: > opentable@0.1.0 start /app
2020-05-06T00:51:29.195636+00:00 app[web.1]: > react-scripts start
2020-05-06T00:51:29.195637+00:00 app[web.1]:
2020-05-06T00:51:34.480135+00:00 app[web.1]: [34mℹ[39m [90m「wds」[39m: Project is running at http://172.19.76.182/
2020-05-06T00:51:34.480852+00:00 app[web.1]: [34mℹ[39m [90m「wds」[39m: webpack output is served from
2020-05-06T00:51:34.481791+00:00 app[web.1]: [34mℹ[39m [90m「wds」[39m: Content not from webpack is served from /app/public
2020-05-06T00:51:34.481944+00:00 app[web.1]: [34mℹ[39m [90m「wds」[39m: 404s will fallback to /
2020-05-06T00:51:34.482310+00:00 app[web.1]: Starting the development server...
2020-05-06T00:51:34.482311+00:00 app[web.1]:
2020-05-06T00:51:34.653916+00:00 heroku[web.1]: State changed from starting to crashed
2020-05-06T00:51:49.687511+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=warm-tundra-79939.herokuapp.com request_id=644090fa-2282-43eb-b6a0-3f586a877b2b fwd="72.137.75.96" dyno= connect= service= status=503 bytes= protocol=https
2020-05-06T00:51:50.279212+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=warm-tundra-79939.herokuapp.com request_id=41875779-e718-4c21-9cd0-a27b994ce5ff fwd="72.137.75.96" dyno= connect= service= status=503 bytes= protocol=https
2020-05-06T00:52:45.417633+00:00 heroku[web.1]: State changed from crashed to starting
2020-05-06T00:52:57.867537+00:00 app[web.1]:
2020-05-06T00:52:57.867556+00:00 app[web.1]: > opentable@0.1.0 start /app
2020-05-06T00:52:57.867556+00:00 app[web.1]: > react-scripts start
2020-05-06T00:52:57.867556+00:00 app[web.1]:
2020-05-06T00:52:59.557333+00:00 app[web.1]: [34mℹ[39m [90m「wds」[39m: Project is running at http://172.17.90.18/
2020-05-06T00:52:59.557673+00:00 app[web.1]: [34mℹ[39m [90m「wds」[39m: webpack output is served from
2020-05-06T00:52:59.557747+00:00 app[web.1]: [34mℹ[39m [90m「wds」[39m: Content not from webpack is served from /app/public
2020-05-06T00:52:59.557810+00:00 app[web.1]: [34mℹ[39m [90m「wds」[39m: 404s will fallback to /
2020-05-06T00:52:59.557987+00:00 app[web.1]: Starting the development server...
2020-05-06T00:52:59.557987+00:00 app[web.1]:
2020-05-06T00:52:59.658416+00:00 heroku[web.1]: State changed from starting to crashed
2020-05-06T00:53:42.008093+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=warm-tundra-79939.herokuapp.com request_id=92745996-d95d-4da8-a4f1-686fcb5c63be fwd="72.137.75.96" dyno= connect= service= status=503 bytes= protocol=https
2020-05-06T00:53:42.611511+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=warm-tundra-79939.herokuapp.com request_id=bf1eafd8-3211-4027-91a6-85bb996b9038 fwd="72.137.75.96" dyno= connect= service= status=503 bytes= protocol=https

I used to have favicon but it has been removed and new git has been pushed, but still getting the error

A: I fixed the issue as this was my very first ever app to in nodejs i did not know i need the server.
const express = require('express');
const favicon = require('express-favicon');
const path = require('path');
const port = process.env.PORT || 9999;
const app = express();
app.use(favicon(__dirname + '/build/favicon.ico'));

app.use(express.static(__dirname));
app.use(express.static(path.join(__dirname, 'build')));
app.get('/ping', function (req, res) {
 return res.send('pong');
});
app.get('/*', function (req, res) {
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.listen(port);

A: Create the Procfile file at the root of your project and add this content (web: npm run start:prod) then redeploy your app on heroku
This work only for NodeJS application


text:
Q: How to find a LinkedIn users web link using REGEX C# I'm trying to match LinkedIn URLs from a string. The issue is, my Regex isn't working and won't match with any LinkedIn URLs, any ideas what I'm doing wrong?
Example URLs I'm trying to match:

https://www.linkedin.com/company/tremolo/about/
https://www.linkedin.com/in/adamblakney/

My Regex:
  Regex linkedRegex = new Regex(@"(http(s)?:\/\/([\w]+\.)?linkedin\.com\/in\/[A-z0-9_-]+\/?",
  RegexOptions.IgnoreCase);

All code for clarity:
  string ps = driver.PageSource;
  string words = string.Join(" ", ps);
  Regex linkedRegex = new Regex(@"(http(s)?:\/\/([\w]+\.)?linkedin\.com\/in\/[A-z0-9_-]+\/?",
  RegexOptions.IgnoreCase);

  //find items that matches with our pattern
  MatchCollection linkedMatches = linkedRegex.Matches(words);
  linkedin = linkedMatches[0].ToString();


text:
Q: python, list, array, all rows automatically get updated a = [[0, 0, 0]] * 3
print(a)
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
a[1][0] = 99
print(a)
[[99, 0, 0], [99, 0, 0], [99, 0, 0]]

here when I am trying to update a[1][0] every row automatically get updated how to overcome this


text:
Q: Best way to block or wait for a ValueAnimator to finish? On Android, I have a sequence of graphics and logic calls that need to be executed synchronously. I don't want to use callbacks, and do want to leverage the ValueAnimator class. Below is an example of a step I've managed to make work: blocking the thread while the animation is active by using a Future. I'm positive that there's a better way, is there? And, am I even setting up the animation correctly with the Handler and Looper? It works, but it seems heavy-handed.
        CompletableFuture<Boolean> animFuture = new CompletableFuture<>();
        animFuture.runAsync(() -> {
            new Handler(Looper.getMainLooper()).post(() -> {
                ValueAnimator valAnim = ValueAnimator.ofFloat(0f, 1f);

                // Update listener and stuff removed for clarity

                valAnim.addListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        animFuture.complete(true);
                    }
                });
                valAnim.start();
            });
        });

        animFuture.get();


text:
Q: What is the meaning of "dehyphenate"? I read a sentence in  The hindu which was:
Although this approach has allowed India to eschew involvement in regional
disputes and dehyphenate relations with regional rivals...
What is the meaning of dehyphenate? I couldn't find it in any dictionarie?

A: They are using a big word to suggest improving the communication ie making it (more) direct.
A hyphen is or can be used to join or link certain words when explaining things - so "dehyphenation" is used here to suggest a stronger link or improved level of communication....

A: It is an extended meaning only used in Indian English, with relation to Indian foreign affairs.
At one time India consider relations with "Israel-Palestine"  considering the region as one country. This word has a hyphen "-" and this was called a "hyphenated foreign policy.
A change to consider relations separately with "Israel" and with "Palestine" was called "de-hyphenation". The endorsing an independent policy towards these two rivals is called the de-hyphenation in India's foreign policy.
By extension, the formation of separate relations with two countries or groups engaged in a regional dispute is called "dehyphenation". It is an expression only found in Indian English.


text:
Q: Writing huge excel file(20k records) is taking more then 1 minute java? Hi i am using apache POI and for writing into workbook i am using SXSSFWorkbook since data will be huge,
Eveything looks good, but while converting workbook to inputstream it's taking huge time for exporting reports.
Here is my code
public StreamedContent generateStreamRep(String fileName, Workbook wb) {
    try (ByteArrayOutputStream dsf = new ByteArrayOutputStream();){
        wb.write(dsf);
        file = new DefaultStreamedContent(ByteSource.wrap(dsf.toByteArray()).openStream(), "xlsx", fileName);
   }

I was using IOUtils now switched to
com.google.common.io.ByteSource
Looked into PipedStreams but not getting proper resource.

A: A Minimal Reproducible Example would help to provide a more complete answer.
However the following code uses PipedStreams to accelerate the operations shown in the code of the question. However the benefits you get from this approach cannot be larger than the fastest of the 2 parallel processes. Or, stated differently, the final duration cannot be faster than the slower of the parallel operations.
In a PipedStreams approach you need 2 Streams.
A PipedOutputStream where data will be written and a PipedInputStream were data will be consumed.
To benefit from this approach you need to run these two operations in parallel.
public StreamedContent generateStreamRep(final String fileName, final Workbook wb) {
    try (final PipedOutputStream dsf = new PipedOutputStream ();
         final PipedInputStream sink=new PipedInputStream (dsf);){

        final ExecutorService executorService= Executors.newSingleThreadExecutor();

        //Write to output stream
        executorService.execute(()->wb.write(dsf));

       //read from input stream
       file = new DefaultStreamedContent(sink, "xlsx", fileName);

        executorService.shutdown();

         //wait until task is finished or until a maximum time, which ever comes first. Normally in this case the task is already finished
        executorService.awaitTermination(2,TimeUnit.Minutes);

   }


text:
Q: How can I define the exterior and interior angle of the figure? If i have this figure:

How to describe the angles, depending on the sides?, According to what I know, the angle $ K $, will be: the angle ABC, but with this, a problem arises, how do I describe the angle L? i think that can be CBA

A: If you want to specifically pick out the larger of the two angles, I don't think there is notation for that; you would need to explain in words. By default, $\angle ABC$ and $\angle CBA$ would both refer to the smaller angle.
You could use the convention of oriented angles, where we define $\angle ABC$ to be the angle of the counterclockwise rotation which takes ray $\overrightarrow{BA}$ to ray $\overrightarrow{BC}$. (Here, "counterclockwise" is an arbitrary choice, but mathematicians prefer counterclockwise angles to be positive.) This is well-defined up to adding a multiple of $2\pi$ (or $360^\circ$).
With this convention, $\angle ABC$ and $\angle CBA$ would be the two angles, but which one is which depends not on which angle is larger, but on which direction is the counterclockwise direction. In the diagram in the question, angle $K$ would be $\angle CBA$, since we rotate $\overrightarrow{BC}$ by an angle of $K$ counterclockwise to get $\overrightarrow{BA}$, and angle $L$ would be $\angle ABC$.
Using oriented angles, no matter which angle is which, we always have $\angle ABC = 360^\circ - \angle CBA$ (or just $\angle ABC = -\angle CBA$, since these are the same for oriented angles). Oriented angles also let us write equations like $\angle ABC + \angle CBD = \angle ABD$ without caring about the relative positions of points $A,B,C,D$.


text:
Q: get data from table and from relative foreign tables in SQL Hi have a text search input that looks for matching records in the DB and gets all the data from a table:
let's say like this:
$q = Input::get('items');

        $q = "\"" . "($q)" . "\"";

        $items = DB::table('my_items')->whereRaw(

            'MATCH(item_name) AGAINST(? IN BOOLEAN MODE)',

            array($q)

        )->get();

So I get all the items in the DB from my textsearch, then I send the result as json to some script that updates my page with the items:
return Response()->json($items);

The relations are:
My_item:
public function brand(){

        return $this->hasOne('App\Brand', 'id', 'brand_id');
    }

Brand:
public function My_item(){

        return $this->belongsToMany('App\My_item');

    }

Now the problem here is that in 'my_items' table I have some data as IDs that reference foreign tables.
For example I will have a 'brand_id' that for example references a 'brands' table where I can have information regarding the brand.
So for example I could have brand_id = 3 that means 'Microsoft' in my brands table (id = 3, name = microsoft).
Now what I need to do is not only passing the brand_id to my view but also the actual information (name), in this case Microsoft so that I can  put that info in the item description.
But, how can I get that information before sending with that query? Is there some sort of flag I can use in the query like $items = DB::table bla bla with foreign?

A: First of all, you can simplify your search query to something like this:
My_item::where('item_name', 'LIKE', "%$q%")->get();

Now, assign relations the relation to your other tables in your Models. Then you can get all information using the following syntax:
My_item::with('brand')->where('item_name', 'LIKE', "%$q%")->get();

Read more about relations here: https://laravel.com/docs/5.1/eloquent-relationships

A: this way works, DB:: method is dropped for:
$items = My_item::with('brand')->where('item_name', 'LIKE', "%$q%")->get();

this one doesn't:
DB::table('my_items')::with('brand')->where('item_name', 'LIKE', "%$q%")->get();


text:
Q: Converting 66 rows of list into dataframe python I want two columns in dataframe. names and labels.

len(names),len(labels)

I have list of names and labels (8 values in each label) which are total 66. when i tried converting only labels, 1 row of label was picked and 8 values in that row (of label) was printed separately.

for x in range(len(labels)):
  lst = (labels[x])
df = pd.DataFrame(labels[x])

df.columns =['labels']
df

the output it gave:

    x1
0   49
1   130
2   81
3   129
4   48
5   148
6   77
7   148

I want these 8 values of label in 1 row (separate columns for each row is accepted)
but for some mistake its not giving me other 65 rows only 1.
I also wants names to be printed along with labels.

A: The 'label' is list of list, so you can directly use
pd.DataFrame(label)
pd.DataFrame(data=label,columns=name)
here,
df = pd.DataFrame([labels[x]])
Adding list results in a row!!


text:
Q: SQLAlchemy / pyODBC not releasing database connection I'm using SQLAlchemy (Core only, not ORM) to create a connection to a SQL Server 2008 SP3.
When looking at the process' network connections, I noticed that the TCP/IP connection to the SQL Server (port 1433) remains open (ESTABLISHED).
Sample code:
from urllib.parse import quote_plus
from sqlalchemy.pool import NullPool
import sqlalchemy as sa

# parameters are read from a config file
db_params = quote_plus(';'.join(['{}={}'.format(key, val) for key, val in db_config.items()]))
# Hostname based connection
engine = sa.create_engine('mssql:///?odbc_connect={}'.format(db_params),
                          poolclass=NullPool)

conn = engine.connect()
conn.close()

engine.dispose()
engine = None

I added the NullPool and the engine.dispose() afterwards, thinking they might solve the lingering connection, but alas.
I'm using as hostname based connection as specified here.
Versions:

*

*Python 3.5.0 (x32 on Win7)

*SQLAlchemy 1.0.10

*pyODBC 3.0.10

Edit: I've rewritten my code to solely use pyODBC instead of SQLAlchemy + pyODBC, and the issue remains. So as far as I can see, the issue is caused by pyODBC keeping the connection open.

A: When only pyODBC, the issue is because of connection pooling as discussed here.
As described in the docs:

pooling
A Boolean indicating whether connection pooling is enabled.
This is a global (HENV) setting, so it can only be modified before the
first connection is made. The default is True, which enables ODBC
connection pooling.

Thus:
import pyodbc

pyodbc.pooling = False
conn = pyodbc.connect(db_connection_string)
conn.close()

It seems that when using SQLAlchemy and disabling the SA pooling by using the NullPool, this isn't passed down to pyODBC.


text:
Q: Adaptive Cards and Microsoft Bot Framework: will only permit 'openUrl' action? EDIT 2: The following schema (provided by a colleague) works.  I removed the quotation marks from the schema in the examples from Microsoft, but that still didn't work.  I'm not sure what the issue is.  I leave the question open in case someone else wants to provide an answer, but I've got it working.
const card = {
        contentType: 'application/vnd.microsoft.card.adaptive',
        content: {
            $schema: 'http://adaptivecards.io/schemas/adaptive-card.json',
            type: 'AdaptiveCard',
            version: '1.0',

            {
            type: 'Input.Text',
            placeholder: 'Name',
            style: 'text',
            maxLength: 50,
            id: 'defaultInput'
            },
            actions: [
                {
                    type: 'Action.Submit',
                    title: 'Siguiente',
                    data: {} // will be populated with form input values
                }
            ]
        }
    };

I'm trying to make a form in my MS Bot using Adaptive Cards.  I took the sample form from the MS site (https://blog.botframework.com/2019/07/02/using-adaptive-cards-with-the-microsoft-bot-framework/) but get the following error

The error seems to be thinking that my action type is Action.openUrl but I don't see that in my code, which is below.  Any help much appreciated.  Using Microsoft Bot Framework 3, Node 12.13.0.
  function askPolicyNumber(session) {
        const card = {
            '$schema': 'https://adaptivecards.io/schemas/adaptive-card.json',
            'type': 'AdaptiveCard',
            'version': '1.1',
            'body': [
                {
                    'type': 'Input.Text',
                    'id': 'id_text'
                },
                {
                    'type': 'Input.Number',
                    'id': 'id_number'
                }
            ],
            'actions': [
                {
                    'type': 'Action.messageBack',
                    'title': 'Submit',
                    'data': {
                        'prop1': true,
                        'prop2': []
                    }
                }
            ]
        };
        const msg = new builder.Message(session).attachments([card]);
        return session.send(msg);
    }

EDIT:
It seems that no matter what I set the action to it keeps thinking it's an openUrl action.  In fact, if I set it to openUrl and give it a url property, it works fine.
I looked at this page -- https://learn.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-actions#adaptive-cards-actions -- and followed the instructions there for 'Adaptive Cards with messageBack action', but it didn't change anything
"actions": [
        {
            "type": "Action.Submit",
            "title": "Click me for messageBack",
            "data": {
                "msteams": {
                    "type": "messageBack",
                    "displayText": "I clicked this button",
                    "text": "text to bots",
                    "value": "{\"bfKey\": \"bfVal\", \"conflictKey\": \"from value\"}"
                }
            }
        }
    ]
}

A: There are a lot of problems with what you're doing. It is recommended that everyone use Bot Builder v4 instead of v3. The main problem that your colleague solved was that you were trying to use an Adaptive Card object as though it was an Attachment object.
The blog post you linked to explains that Adaptive Cards must follow the Adaptive Cards schema. There is no Action.messageBack in the Adaptive Cards schema. Please continue referring to the documentation for more information.


text:
Q: Email subject encoding I'm trying to configure my e-mail template (Applications->Development->Email Templates) in Kentico and faced with encoding issue with e-mail subject field.
For example, if the e-mail template subject field contains the following text with the macro:
Přijatá objednávka číslo {%HTMLEncode(Order.OrderInvoiceNumber) #%}

I receive it as
P?ijat? objedn?vka ??slo 3019

As you can see, the subject doesn't encoded, however, I see it in Kentico back-end without a question marks.
I have no idea, how to fix it. Pease help.

A: Try to put your string into resources and get via macro, so your subect will look like: {$ReceivedOrderNumber$}{%HTMLEncode(Order.OrderInvoiceNumber)#%}


text:
Q: Interchange supremum and expectation Let $B_n:=\{f\in L^\infty_+\mid f\le n \}$, where we consider $L^\infty$ with the weak$^*$ topology. I have the following sets
$$D(z):=\{h\in L^0_+(\mathcal{F}_T)\mid h\le Z_T \mbox{ for a }Z\in Z(z)\}$$
where $Z(z)$ is the set of positive (RCLL) supermartingales on $[0,T]$ with $E[Z_0]\le z$. Moreover $U$ is a function from $\mathbb{R}_+\to\mathbb{R}$, strictly increasing, strictly concave and $C^1$. For a $h\in D(z)$ I want to prove
$$\sup_{f\in B_n} E[U(f)-hf]=E[\sup_{f\in B_n}\{U(f)-fh\}]$$
One direction is clear: $E[U(f)-hf]\le E[\sup_{f\in B_n}\{U(f)-fh\}]$, hence
$$\sup_{f\in B_n} E[U(f)-hf]\le E[\sup_{f\in B_n}\{U(f)-fh\}]$$
the inequality $"\ge "$ is bothering me. How can I tackle this problem? I know that the equality is true. Thanks for your help

A: Fix $U:\mathbb R^+\to \mathbb R$ as above.
For every $y\in\mathbb R$ the function $g_y: [0,n]\to \mathbb R$ defined by
$$ g_y(x) = U(x) -xy $$ is continuous in the compact interval [0,n].
Therefore $g_y$ is bounded and attains its bounds and we may set
$$G(y) =  \sup_{x\in[0,n]}  g_y(x)$$
and define a function $F:\mathbb R\to [0,n]$ such that
$$g_y(F(y)) =G(y).$$
That is $F(y)$ is the maximizer of $g_y$.
Therefore we have
$$E(\sup_{f\in B_n} U(f) - fh) \leq E(\sup_{x\in[0,n]} U(x) - xh) = E(G(h)).$$
It's easy to see from your conditions on $U$ that $F$ is continuous.
Thus the composition $X(\omega) = F(h(\omega))$ is measurable and we have $X\in B_n$.
So $$\sup_{f\in B_n}E( U(f) - fh) \geq E( U(X) - Xh) = E(g_h(X)) = E(G(h)).$$
Hence $$\sup_{f\in B_n}E( U(f) - fh) \geq E(\sup_{f\in B_n} U(f) - fh).$$


text: Q: deploying a styles library for plugin developers I have an application that my customers can write plugins (that have WPF UIs) for. Now I would like to expose a set of styles as a library that they can use and that will help them with the development of the UIs sO they don't have to reivent the weel. How would I idealy expose those styles without actually having to deploy a lot of xaml files? How is something like this usually done in WPF so it does not break tooling support (blend, vs). How do I expose it and how does the cusomer reference those styles?


text:
Q: Release management api & pagination using vss-web-extensions-sdk I'm writing azure devops extension and want to fetch a list of releases.
I'm using RestClient from "ReleaseManagement/Core/RestClient" that has getReleases() method.
It has continuationToken as a paremeter but i did not find any example how to get that token from response headers.
Question: how to get continuation token for next 50 releases after fetching the first batch?

A: The continuationToken is in the response header after the first call to the API:
x-ms-continuationtoken: xxxx

You can use the rest api to retrieve the header information. Here is an example for your reference:
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace GetReleases
{
    class Program
    {
        public static void Main()
        {
            Task t = GetReleases();
            Task.WaitAll(new Task[] { t });
        }
        private static async Task GetReleases()
        {
            try
            {
                var username = "xxxxx";
                var password = "******";

                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Add(
                        new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                        Convert.ToBase64String(
                            System.Text.ASCIIEncoding.ASCII.GetBytes(
                                string.Format("{0}:{1}", username, password))));

                    using (HttpResponseMessage response = client.GetAsync(
                                "https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/releases?api-version=4.1-preview.6").Result)
                    {
                        response.EnsureSuccessStatusCode();
                        string responseBody = await response.Content.ReadAsStringAsync();
                        Console.WriteLine(responseBody);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }
}

A: SDK don't have api to get result with continuation token. You need to call release List api and parse response header to get continuation token.


text:
Q: Separating of tests build form application build in CI/CD without rebuilding I have a project with files:
main.cpp - application
sum.h
sum.cpp
tester.cpp - tester application

I build it with CMake, CMakeLists.txt:
cmake_minimum_required(VERSION 3.10)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

set (ProjectName hello)
project(hello VERSION 1.0)
set(SOURCES sum.h sum.cpp main.cpp)
add_executable(${ProjectName} ${SOURCES})

enable_testing()
add_executable(tester sum.h sum.cpp tester.cpp)
add_test(Tester tester)

Then I set up a CI/CD on gitlab:
image: gcc

build:
  stage: build
  before_script:
   - apt update && apt -y install make cmake libcrypto++-dev
  script:
    - cd SimpleCiCdForCpp
    - mkdir build
    - cd build
    - cmake ..
    - make
    - ls
  artifacts:
    paths:
      - SimpleCiCdForCpp/build/hello
      - SimpleCiCdForCpp/build/tester

test:
  stage: test
  before_script:
   - apt update && apt -y install make cmake libcrypto++-dev
  script:
    - ls
    - cd SimpleCiCdForCpp
    - cd build
    - cmake ..
    - make
    - ctest

Everything works - I have 2 applications: the main one and the tester and the tests pass.
The problem is that I have to build everything on Build stage and on Testing stage, otherwise I end up with empty testing config for ctest
Is there any good practice to separate testing projects from main applications?

A: Your CMAkeLists.txt may look like this:
cmake_minimum_required(VERSION 3.10)
project(hello VERSION 1.0)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
include(CTest) # Sets BUILD_TESTING=0 by default

# Do not build twice.
add_library(sum sum.cpp sum.h)

# There is already PROJECT_NAME CMake variable.
add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries(${PROJECT_NAME} PRIVATE sum)

# Do not use if not needed!
if(BUILD_TESTING)
  add_executable(tester tester.cpp)
  target_link_libraries(tester PRIVATE sum)
  # Use same name for test and executable.
  add_test(COMMAND tester NAME tester)
endif()

Then:
build:
    - cmake -S. -Bbuild -DBUILD_TESTING=0
    - cmake --build build
  artifacts:
    paths:
      # Cache the... cache, so that you don't rebuild!
      - SimpleCiCdForCpp/build

test:
    - cmake -S. -Bbuild -DBUILD_TESTING=1
    - cmake --build build
    # Newest syntax.
    - ctest --test-dir build


text:
Q: SQL Determining the length of a unique visit from access log I have a table that has access log records and I want to know the average time of a visit. I'm using sqlite with JDBC to populate the table. The table could be potentially a few 100 million rows large. I don't have much SQL experience.
The table is similar to this:
ID   Name      Time(s)
1    Apricot   100
2    Apricot   101
3    Banana    102
4    Banana    102
5    Banana    105
6    Apricot   106
7    Apricot   300
8    Cake      300
9    Banana    310
10   Banana    320

I want to see the duration of each visit. One visit is when an entry appears and continues to appear (with the same name) until some time has passed (say 100 seconds). After that, the session ends - if the same name appears again then it is a new session.
Ultimately I want to graph the number of visits and their durations.
I'm not sure what kind of output would be the easiest, but here is a possible output that would be useful:
Name       Time
Banana     3     (row5 - row3)
Apricot    6     (row6 - row1)
Apricot    0     (row7 - last visit is >100s and no more subsequent visits)
Cake       0     (row8 - last visit is >100s and no more subsequent visits)
Banana     10    (row10 - row9)

(Additionally, show the ID - this could be the ID of the start of a visit or the end)
How can this be done using SQL?
This page: Determining the length of a user's visit based on SQL timestamps
has a similar question to mine but I don't really understand the answer, nor does it work for me (my DB browser freezes).


text:
Q: Where to combine database data with file system data in .NET I am creating a .NET Core Web API application where people can find building plans for houses.
The application has a database table which contains information like address, zip, city and an ID.
The PDFs are stored on the File System and are grouped in folders with the same ID as in the Database.
This is my current Controller code:
[HttpGet]
public async Task<ActionResult<List<BuildingplanDto>>> Get(
    [FromQuery] string street,
    [FromQuery] string city,
    [FromQuery] string housenumber)
{
    //Retrieve building plan info from database
    List<Buildingplan> buildingplans = await _BuildingplanService.FindAsync(street, city, housenumber);

    List<BuildingplanDto> buildingplanDtos = new List<BuildingplanDto>();
    BuildingplanDto buildingplanDto;
    foreach (Buildingplan buildingplan in buildingplans)
    {
        //Map database entity to Dto
        buildingplanDto = _mapper.Map<Buildingplan, BuildingplanDto>(buildingplan);
        //Add folders from the filesystem to the Dto
        buildingplanDto.Folders = _documentService.GetFolders(buildingplan.DossierId);
        buildingplanDtos.Add(buildingplanDto);
    }

    return Ok(buildingplanDtos);
}

However this code doesn't feel right; There is too much logic in the Controller which I want to put somewhere else. I don't know where to put it though.
Could anyone give me a direction where to put this logic? I am also open for other tips.

A: You need to layer your application, where each layer has a specific purpose.  The most basic layering is UI-Logic-Data, but there are other more advanced architectures as well - e.g. https://morphological.wordpress.com/2011/08/29/5-layer-architecture/ (a blog post of mine).
Think of the API controller as the UI - it should only be responsible for handling the API request and providing back a response; the "heavy lifting" of pulling together the data that goes into the response would be done elsewhere.
For example, a basic 3-layer model could look like this:

*

*API layer - is responsible for handling external API requests.

*Logic layer - is responsible for making decisions such as orchestrating various calls, enforcing business rules and so on.

*Data / Service layer - is responsible for fetching data, e.g. from a database, file system or external API.


text:
Q: Use a PC PSU for powering a Raspberry Pi cluster and number of 5V+ cables I need to power a cluster of 8 Raspberry Pis 4 and I have a 480W PC PSU with a maximum load of 28A on 5V+. My question is really simple and dumb (sorry for that) but I did not found a precise answer, but when I attach them to the 24pin motherboard connector should I use all the five 5V+ cables and 5 ground respectively? PSU cables are 20awg, and I estimated 3A for the Raspberry Pis so a total of 24A.

A: Yes, you should use all the 5V conductors and at least as many GND to reduce voltage drop over the cable; using extra grounds would only help.   With 5 supply and 5 return wires, each conductor will be carrying almost 5A.  Even this starts to push the limit of what you would want going over 20AWG.


text:
Q: Change of variable in double integrals $\iint_S f(x,y) \,dx \,dy$, where $S=\{(x,y)|x^2\leq y,-1 \leq x\leq 1\}$. Problem

Express the double integral $\iint_S  f(x,y) \,dx \,dy$ as an iterated integral in polar coordinates, where $S=\{(x,y)|x^2\leq y,-1 \leq x\leq 1\}$.

Doubt
I have difficulty finding range of $r$ and $\theta$.
$r^2 \cos^2(\theta) \leq r \sin(\theta) \leq 1$
$-1 \leq r \sin(\theta) \leq 1$

A: One may divide the area to three parts:
\begin{cases}
0\leq\theta\leq\dfrac{\pi}{4};\ 0\leq r\leq\sin\theta\sec^2\theta,\\
\dfrac{\pi}{4}\leq\theta\leq\dfrac{3\pi}{4};\ 0\leq r\leq\sec\theta,\\
\dfrac{3\pi}{4}\leq\theta\leq\pi;\ 0\leq r\leq\sin\theta\sec^2\theta.
\end{cases}
then
\begin{align}
\int_{-1}^{1}\int_{x^2}^{1} f(x,y)\ dy\ dx
&=
\int_{0}^{\pi/4}\int_{0}^{\sin\theta\sec^2\theta} f(r\cos\theta, r\sin\theta)\ r\ dr\ d\theta \\
&+
\int_{\pi/4}^{3\pi/4}\int_{0}^{\sec\theta} f(r\cos\theta, r\sin\theta)\ r\ dr\ d\theta \\
&+
\int_{3\pi/4}^{\pi}\int_{0}^{\sin\theta\sec^2\theta} f(r\cos\theta, r\sin\theta)\ r\ dr\ d\theta
\end{align}


text:
Q: My for loop is not iterating correctly in array rotation problem in Python I'm trying to write a solution to Codility problem 2.1 in Python. The taks is to write a function to rotate a given array one space to the right k number of times. For example, if you were to rotate [0, 1, 2, 3, 4] twice it would first become [4, 0, 1, 2, 3] and then [3, 4, 0, 1, 2].
I'm doing this by writing two for loops, the inner for loop to rotate the array and the outer for loop to repeat the rotation k times. I haven't moved on to write the outer loop yet but I think it should be straightforward. However, I'm struggling to write the inner loop to rotate the array.
When I test [0, 1, 2, 3, 4] it returns [4, 1, 2, 3, 3] instead of [4, 0, 1, 2, 3], so it only returns the first and last elements correctly. The loop doesn't seem to cycle through the second, third and fourth elements at all (I have tested this by asking the loop to print(i) when it cycles through the loop).
Can anyone see why my for loop isn't working? The code is below
def Solution(A):
    N = len(A)
    A_minus_one_original = A[-1]
    for i in (-1, -N):
        if i != -N:
            A[i] = A[int(i) - 1]
            print(i)
        elif i == -N:
            A[i] = A_minus_one_original
            print(i)
    print(A)

A: for i in range(-1, -N, -1)

Use this for loop, because yours only touch the -1 and -N positions
BTW, python supports array slicing, which is very useful for rotate the array k steps (k < len(a)).
# left
new_a = a[k:] + a[:k]
# right
la = len(a)
new_a = a[la-k:] + a[:la-k]

A: Don't forget to name your variables to make your code readable. I solved the problem in that way.
def solution(list_to_rotate,rotation_time):
    last_index_list_to_rotate = -1
    rotation_time = rotation_time - 1
    for i in range(last_index_list_to_rotate, rotation_time):
        if i != rotation_time:
            val = list_to_rotate[last_index_list_to_rotate]
            del list_to_rotate[last_index_list_to_rotate]
            list_to_rotate.insert(0,val)
            print(i)
    print(list_to_rotate)

#rotate twice the list
solution([0,1,2,3,4],2)