text:
Q: Was this sentence formed grammatically correct? "The charts below show the results of a questionnaire that asked visitors to the Parkway Hotel how they rated the hotel's customer service."
Does this information sentence above look grammatically correct? Doesn't it have to have any conjunction between
these two part?
[The charts below show the results of a questionnaire that asked visitors to the Parkway Hotel]  [how they rated the hotel's customer service]

A: No, you don't need a conjunction or anything else between the two clauses. To so would unnecessarily separate the two objects of to ask. Let's look at two  simpler sentences:

John asked his friends something.
John asked his friends how they rated  the movie.

The verb to ask can take two objects, traditionally called indirect (his friends) and direct (something/how they rated the movie). There's no need to separate them, since the verb governs the syntax of what follows it.
Adding to the length and complexity of the sentence does not change things, as far as that is concerned.
And again, +1 for writing the charts below and not the below charts.
To address your question in the comment, visitors to the Parkway Hotel is one noun phrase, with to the Parkway hotel describing which visitors. It would be like saying

John asked [his friends from Bulgaria]  how they rated  the movie.


text:
Q: Notepad++ strip bbcode color statements Here is what my text file looks like:
    [img]asset:/052cf103006dc0a1aee06067b12b2153-40[/img] Adrik Thorgrim: [color=#000000]done for the night then?[/color]
GM: [color=#000000]Yes[/color]
[img]asset:/052cf103006dc0a1aee06067b12b2153-40[/img] Adrik Thorgrim: [color=#000000]I would prolly plan on altruis notshowing up[/color]
[img]asset:/052cf103006dc0a1aee06067b12b2153-40[/img] Adrik Thorgrim: [color=#000000]i've known both of em for 10 or soyears[/color]
[img]asset:/052cf103006dc0a1aee06067b12b2153-40[/img] Adrik Thorgrim: [color=#000000]tycho is without power tonight[/color]
[img]asset:/052cf103006dc0a1aee06067b12b2153-40[/img] Adrik Thorgrim: [color=#000000]he lives in the middle of farm country[/color]
[img]asset:/052cf103006dc0a1aee06067b12b2153-40[/img] Adrik Thorgrim: [color=#000000]on a dirt road off a dirt road[/color]
[img]asset:/052cf103006dc0a1aee06067b12b2153-40[/img] Adrik Thorgrim: [color=#000000]I went through the massive ice stormback in the 90s that ruined New England's power system, I know allabout it[/color]
[img]asset:/052cf103006dc0a1aee06067b12b2153-40[/img] Adrik Thorgrim: [color=#000000]your at 424.42[/color]
[img]asset:/052cf103006dc0a1aee06067b12b2153-40[/img] Adrik Thorgrim: [color=#000000]I'll send you a statblock for Ciro myenchanter tomorrow[/color]
[img]asset:/052cf103006dc0a1aee06067b12b2153-40[/img] Adrik Thorgrim: [color=#000000]I struggled with Kazac[/color]
[img]asset:/052cf103006dc0a1aee06067b12b2153-40[/img] Adrik Thorgrim: [color=#000000]er not enchanter air wizard...[/color]
[img]asset:/052cf103006dc0a1aee06067b12b2153-40[/img] Adrik Thorgrim: [color=#000000]its fun[/color]
[img]asset:/052cf103006dc0a1aee06067b12b2153-40[/img] Adrik Thorgrim: [color=#000000]I actually been pretty excited forthis AP[/color]
[img]asset:/052cf103006dc0a1aee06067b12b2153-40[/img] Adrik Thorgrim: [color=#000000]I'll do a nice photoshop map of outkingdom when we get there[/color]
[img]asset:/052cf103006dc0a1aee06067b12b2153-40[/img] Adrik Thorgrim: [color=#000000]Im a decent cartographer[/color]
GM: [color=#000000]This AP is really kick ass when yousit down and read it. Although, if you have player's like my RotRLgames on Fridays, this game would suck.[/color]
[img]asset:/052cf103006dc0a1aee06067b12b2153-40[/img] Adrik Thorgrim: [color=#000000]I am the most generalist char statwise here[/color]
GM: [color=#000000]All of the different roles are on thewiki for you guys to decide what you think would best benefit youand the party.[/color]
Valens: [color=#000099]REally? 14, 14, 12, 12, 16, 12[/color]
[img]asset:/052cf103006dc0a1aee06067b12b2153-40[/img] Adrik Thorgrim: [color=#000000]12,16,14,12,14,12[/color]
Valens: [color=#000099]LOL[/color]
[img]asset:/052cf103006dc0a1aee06067b12b2153-40[/img] Adrik Thorgrim: [color=#000000]nope[/color]
[img]asset:/052cf103006dc0a1aee06067b12b2153-40[/img] Adrik Thorgrim: [color=#000000]i'll add it to my watch instantly[/color]
[img]asset:/052cf103006dc0a1aee06067b12b2153-40[/img] Adrik Thorgrim: [color=#000000]ps3[/color]
[img]asset:/052cf103006dc0a1aee06067b12b2153-40[/img] Adrik Thorgrim: [color=#000000]and wii[/color]
[img]asset:/052cf103006dc0a1aee06067b12b2153-40[/img] Adrik Thorgrim: [color=#000000]ps3 just got the search feature[/color]
[img]asset:/052cf103006dc0a1aee06067b12b2153-40[/img] Adrik Thorgrim: [color=#000000]if we have to find some people toreplace im fine with that[/color]
GM: [color=#000000]Plus, NetFlix just signed a deal withShowtime and Epix[/color]
[img]asset:/052cf103006dc0a1aee06067b12b2153-40[/img] Adrik Thorgrim: [color=#000000]yea[/color]
[img]asset:/052cf103006dc0a1aee06067b12b2153-40[/img] Adrik Thorgrim: [color=#000000]paramount and lion's gate moviesstarting sept 1st[/color]
Valens: [color=#000099]Goodnight. Having fun. TOo bad Jaycouldn't join us...[/color]
GM: [color=#000000]Yeah, I will post again on the TangledWeb site and RPTools[/color]
[i][color=#0000ff]mdh is disconnected.[/color][/i]
[img]asset:/052cf103006dc0a1aee06067b12b2153-40[/img] Adrik Thorgrim: [color=#000000]might be worth asking jay again, mighthave cooled down for him its, been about 3-4 weeks[/color]
[img]asset:/052cf103006dc0a1aee06067b12b2153-40[/img] Adrik Thorgrim: [color=#000000]goodnight see you sat[/color]

And the RegEx that I tried using that does not work:
[color\=#000000]([A-Za-z0-9 ,.<>?:";'{}[]-_=+!@#$%^&*()]+)[/color]
What I want to do is strip out the [color=#000000] and [/color] from each line and leave the text and [img][/img] intact.

A: Umm ... how about replacing all [color=#000000] and [/color] with nothing using 'Find & Replace All' (once for each keyword)? No need to mess with regex that way ;)

A: If you literally only want to remove the #000000 colors, then I agree with Lukman: use two instances of Find & Replace All.
I saw instances of other colors in that block, so I assume that you want to replace all colors, not just #000000. If so, then use a regex Find & Replace All with the pattern of \[color=#\d*] instead of the [color=#000000] string.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to determine which program is causing Window to have trouble logging off or shutting down? When logging off Windows 7 SP1 or turning off the computer, how does one quickly diagnose which program is causing the system to issue a warning that a process needs to close?
This post, does a great job providing an answer (albeit not a quick one!) for when the problem is completely unknown.  My case is different in that I am 99% certain it is a single program, but I want to make sure before I mess with things (disabling it is not trivial).
The 'Waiting for a program to close' dialog does not list any programs.
Lengthy bootups are pretty simply to diagnose, but how can one quickly determine which program is having trouble terminating itself during logoff or shutdown?

A: What you can do is when your on your PC do the key combo cntrl+alt+Del and windows will give you a couple options click start task manager then view what's running if there is nothing it most likely means a program is doing g some updating or things like that.


text:
Q: Select by attribute with field equal to element of vector in ArcPy? I am trying to select by an attribute with a condition that field equals to an element of a vector. I use a for loop but could not get the right expression for this condition. Here are my codes.
random37 = [30449, 46617, 17309]
pointlayer = "network_nodeSelected"

for random in random37:

randomname = "n" + str(random)
arcpy.MakeFeatureLayer_management(pointlayer,pointlayer)
arcpy.SelectLayerByAttribute_management(pointlayer,'NEW_SELECTION','"ARC_" = random')
arcpy.CopyFeatures_management(pointlayer, randomname)

print randomname

The error message is presented as follows.
Traceback (most recent call last):
File "", line 6, in
    arcpy.SelectLayerByAttribute_management(pointlayer,'NEW_SELECTION','"ARC_" = point')
File "C:\Program Files (x86)\ArcGIS\Desktop10.6\ArcPy\arcpy\management.py", line 7742, in SelectLayerByAttribute
    raise e
ExecuteError: ERROR 000358: Invalid expression
Failed to execute (SelectLayerByAttribute).
As you can see, my problem is the expression '"ARC_" = random'. But I do not know how to get the right expression.

A: The problem is the sql expression. Here is the solution.
random37 = [30449,46617,17309]
pointlayer = "network_nodeSelected"
layer1 = "wqi_ConProshp"

for point in random37:
    pointname = "n" + str(point)
    fieldname = 'ARC_'
    whereClause = """{0} = {1}""".format(arcpy.AddFieldDelimiters(pointlayer, fieldname),point)
    arcpy.MakeFeatureLayer_management(pointlayer,pointlayer)
    arcpy.SelectLayerByAttribute_management(pointlayer,'NEW_SELECTION',whereClause)
    arcpy.CopyFeatures_management(pointlayer, pointname)
    #select the location and then export it

    print pointname

To be honest, I still can not understand how it works but it indeed solves my problem.


text:
Q: Как использовать process.env в файлах приложения Vue.js? Объясните мне, пожалуйста, как я могу задействовать, например, process.env.NODE_ENV непосредственно в коде Vue.js приложения.
Я уточню что имею ввиду не конфиги Webpack'а, а непосредственно файл main.js из:
module.exports = {
  entry: {
    app: './src/main.js'
  },

Читал https://webpack.js.org/plugins/define-plugin/, но ничего не понял. Очень скудные примеры, которые дальше конфигов Webpack не уходят (хотя у них есть пример SERVICE_URL, что очень странно выглядит). На одном форуме видел фразу, мол, с помощью DefinePlugin можно использовать переменные окружения прямо в коде файлов приложения, но опять же никаких примеров, а у меня ничего не получилось. Переменная process или NODE_ENV в коде приложения недоступна - отображает критическую ошибку: 'process' is not defined.
С помощью process.env я хочу передавать, например, в файл main.js данные для Vue.config. Или тот же SERVICE_URL.
Подскажите, пожалуйста, что я делаю не так?

A: DefinePlugin тут может помочь, в конфиге вебпака:
 plugins: [
        new webpack.DefinePlugin({
            'process.env': {
                'SERVICE_URL': JSON.stringify('http://some_url'),
            }
        })
 ]

И далее используем в коде: process.env.SERVICE_URL


text:
Q: C# - How do I prevent duplicate results in nested loop? This is part of my code, I want to add to finalSorted the two values from arrFinal that share the same url (this is what I get with the Split as line[5] and zLine[5]), and I want them to be one above the other. I try to compare if they are not exactly the same entry by comparing line[1] and zLine[1] that stores a REQUEST or RESPONSE. But this part is problematic too, because it returns the same result, not the one with line[1] different than zLine[1].
The problem is that I want to compare each iteration of the first loop with all other iterations (second for loop) to check if they match and return, one above the other, the two that have the same url but different field for RESPONSE and REQUEST.
List<string> finalSorted = new List<string>();

for (int i = 0;i < arrFinal.Count; i++)
{
    string[] line = arrFinal[i].Split(";");
    for (int z = 0; z < arrFinal.Count; z++)
    {
        string[] zLine = arrFinal[z].Split(";");
        if (line[5] == zLine[5] && line[1] != zLine[1])
        {
            finalSorted.Add(arrFinal[i]);
            finalSorted.Add(arrFinal[z]);
        }
        else
        {
            continue;
        }
    }
}

Any help or advice would be appreciated, I'm open to even change entirely the idea for implementing this solution.
Thank you in advance!
Edit:
This is what I get:
00:00:00.7443;REQUEST;POST;https://ulrName/Prices/;/1_0/962;https://ulrName/Prices/1_0/962
00:00:00.7793;RESPONSE;POST;https://ulrName/Prices/;/1_0/962;https://ulrName/Prices/1_0/962
00:00:00.7793;RESPONSE;POST;https://ulrName/Prices/;/1_0/962;https://ulrName/Prices/1_0/962
00:00:00.7443;REQUEST;POST;https://ulrName/Prices/;/1_0/962;https://ulrName/Prices/1_0/962

This is what I want:
00:00:00.7443;REQUEST;POST;https://ulrName/Prices/;/1_0/962;https://ulrName/Prices/1_0/962
00:00:00.7793;RESPONSE;POST;https://ulrName/Prices/;/1_0/962;https://ulrName/Prices/1_0/962

A: // i assume this format in arrFinal
var arrFinal = new string[] {
    "v0;REQUEST;v2;v3;v4;url",
    "v0;RESPONSE;v2;v3;v4;url",
};

// order by "url" then by "REQUEST or RESPONSE"
var sorted = arrFinal.Distinct().OrderBy(x => {
    // TODO, range check etc...
    var urlPart = x.Split(';')[5];
    return urlPart;
}).ThenBy(x => {
    var requestOrResponse = x.Split(';')[1];
    return requestOrResponse;
}).ToList();


text:
Q: Approximating high-energy Compton scattering cross section I'm trying to obtain the approximation (5.94) on page 164 of Peskin and Schroeder's "Introduction to QFT".
Let an electron with momentum $p = (E,-\omega\hat z)$ scatter off a photon with momentum $k = (\omega, \omega \hat z)$ in the center of mass frame. Then, for $E\gg m$ and $\theta\approx \pi$, the differential cross section is approximately:
$$\begin{aligned}\frac{d\sigma}{d\cos\theta} &\approx \frac 12\cdot\frac 1{2E}\cdot \frac 1{2\omega} \frac {\omega}{(2\pi)4(E + \omega)}\cdot\frac{2 e^4 (E+\omega)}{E+\omega\cos\theta}.\end{aligned}\tag{5.94a}$$
The RHS equals
$$\frac{1}{16(2\pi)E}\cdot\frac{4\pi}{4\pi}\cdot\frac{e^4}{E+\omega\cos\theta}=\frac{4\pi}{8E}\cdot\frac{e^4}{(4\pi)^2}\cdot\frac{1}{E+\omega\cos\theta}=\frac{2\pi\alpha^2}{4E(E+\cos\theta)}.$$
How can this be further approximated to
$$\frac{2\pi\alpha^2}{2m^2+s(1+\cos\theta)},\tag{5.94b}$$
where $s = (k+p)^2$?

A: \begin{equation}
\frac{d\sigma}{d\cos\theta}  = \frac{\alpha^2\pi}{2}  \frac{1}{E(E+\omega\cos\theta)}
\end{equation}
Look at the denominator. Start by writing $E(E+\omega \cos\theta) = E\omega(E/\omega + \cos\theta)$. Next, from $m^2=E^2-\omega^2$ find $E/\omega =\sqrt{1+m^2/\omega^2} \approx 1+m^2/2\omega^2$. Therefore
\begin{align}
E(E+\omega \cos\theta) =& E\omega \left(1+\frac{m^2}{2\omega^2} +\cos\theta\right) = E\omega(1+\cos\theta) +\frac{Em^2}{2\omega}
\end{align}
Now $s=(p+k)^2 = 2p\cdot k = 2 E(E+\omega)$ and in the high energy regime $0\approx m^2 = E^2-\omega^2$ and therefore $E\approx \omega$ and so $s/2= E(E+\omega) = 2E\omega$ and $E/\omega \approx 1$. We therefore find
\begin{align}
E(E+\omega \cos\theta) =& \frac{1}{4} s (1+\cos\theta)+ \frac{1}{2}m^2
\end{align}
which gives the desired result.

A: *

*I want to share a little more, because I also meet puzzles when I approximated it: $E\approx\omega\gg m$, $s=2p\cdot k=2\omega(E+\omega)+m^2$ so that $E\omega \approx \omega^2\approx s/4$, plugging them into the denominator of cross section,
$$E(E+\omega\cos{\theta}) = m^2+\omega^2+E\omega\cos{\theta}\approx m^2+\frac{1}{4}s(1+\cos{\theta})$$
but it's wrong since the formula $\omega^2\approx s/4$ discard the term of $m^2$ order which we need in the final expression.

*let's first find the transformation between $(E,\omega)$ and $(s,m)$
$$
\begin{cases}
s =m^2 + 2\omega(E+\omega)\\
m^2 = E^2 - \omega^2
\end{cases}\Longrightarrow
\begin{cases}
E = \frac{1}{2} \left( \sqrt{s} + \frac{m^2}{\sqrt{s}} \right)\\
\omega = \frac{1}{2} \left( \sqrt{s} - \frac{m^2}{\sqrt{s}} \right)
\end{cases}
$$
then the denominator becomes
$$
\begin{align}
E(E+\omega\cos{\theta})
&= \frac{1}{4}\left(s+2m^2+\frac{m^4}{s}\right)+\frac{1}{4}\left( s-\frac{m^4}{s} \right)\cos{\theta}
\\
&= \frac{1}{2}m^2+\frac{1}{4}s(1+\cos{\theta}) + \mathcal{O}\left(\frac{m^4}{s}\right)
\end{align}
$$
maybe this process would be more clear since we only make approxiamtion in the final step.

*In a word, be careful about the error when we make approximations.


text:
Q: Triple integral for a partial cylinder I encounter this question in my homework and i am stuck with it. The question is as follows:
(a) Find the mass of a solid $U$ with density $\delta(x,y,z)=2020$, where $U$ is bounded by 3 given surface: $x^2+y^2=2020, z=x^2+y^2$ and the xy-plane.
(b) Find the centre of mass of the same solid U described in (a)
I have some rough idea on dealing with part (a).$x^2+y^2=2020$ represents a circular cylinder with radius $\sqrt{2020}$ while $z=x^2+y^2$ represents a elliptic paraboloid inside the circular cylinder and they both should have height of $2020$. Therefore, the volume of this solid should be $\frac{1}{4}$ of the volume of cylinder minus $\frac{1}{4}$ of the volume of the elliptic paraboliod since they are bounded by the xy-plane. Then the mass would be $2020$ times the volume.
However, i have trouble finding the triple integral for the elliptic paraboloid. Also, can i use a single triple integral to find the mass so i could do part (b), or is it not necessary? Really appreciate your guys help.


text:
Q: Centering the first row of a table in CSV reader I am creating tables from a CSV file by using csvsimple package. The contents of the tables are all left aligned, hence I would like to know whether it is possible to center the first row alone (and the remaining rows being aligned to the left) ?
My code is:
\documentclass{beamer}
\usepackage{csvsimple}

\begin{filecontents*}{\jobname.csv}
0.1,0.4,0.7,1.0,1.3
0.201,1.001,1.801,4.601,3.401
0.200,1.000,1.800,2.600,3.400
\end{filecontents*}

\begin{document}

\begin{frame}

\csvreader[autotabular,
%full filter=\ifcsvstrcmp{\csvcoliv}{m}{\csvfilteraccept}{\csvfilterreject}
]{\jobname.csv}{}{\csvlinetotablerow}%

\end{frame}

\end{document}

Csvsimple \csvautotabular and \csvautobooktabular with centered columns' content shows how to switch the default alignment to center for the entire table, but can this be done only for the first row?

A: It is possible with \csviffirstrow, adding \multicolumn{1}{c|}{...} for every element of the first row.
The trick of the fake first column @{}p{0pt}@{} is necessary to avoid a ! Misplaced \omit error.
\documentclass{beamer}
\usepackage{csvsimple}

\begin{filecontents*}{\jobname.csv}
0.1,0.4,0.7,1.0,1.3
0.201,1.001,1.801,4.601,3.401
0.200,1.000,1.800,2.600,3.400
\end{filecontents*}

\begin{document}

\begin{frame}
\begin{tabular}{@{}p{0pt}@{}|*5{l|}}
    \hline
    \csvreader[
        no head,
        late after line=\\\hline,
        ]{\jobname.csv}{}{%
            \csviffirstrow{%
                & \multicolumn{1}{c|}{\csvcoli} & \multicolumn{1}{c|}{\csvcolii} & \multicolumn{1}{c|}{\csvcoliii} & \multicolumn{1}{c|}{\csvcoliv} & \multicolumn{1}{c|}{\csvcolv}
            }{%
                & \csvcoli & \csvcolii & \csvcoliii & \csvcoliv & \csvcolv
            }%
        }
\end{tabular}
\end{frame}
\end{document}


text:
Q: Kill app processes after exit? I have the following code which plays some audio after some time in a service. The issue is, after exiting the app, the media player continues to run; I want to stop the audio from playing after the app has has been exited or closed.

By the way, ten and three were declared at the top:
MediaPlayer ten;
   MediaPlayer three;
Does some piece of code run every time an app is closed? If so, I could call stopService() from that piece of code.
I would really appreciate any feedback (positive or negative)! Thank you so much for all of your help, let me know if you need any more code.
{Rich}

A: onStop you can mute player
and
onResume you can play music player.
OnDestroy you can stop your service
stopService(new Intent(YourService));

For reference mute and unmute player
How to mute MediaPlayer in android

A: Yes, Android have a lifecycle that run the onCreate, onPause, onStop and onDestory. When you exit the app and wish to stop the player, you might want to do something in the onStop.
You can look at the lifecycle at http://developer.android.com/training/basics/activity-lifecycle/stopping.html
Cheers

A: If you have one activity that is always the task root and only the task root, overriding onBackPressed in that activity is probably the best way to tell if the app is "exiting" as far as the user is concerned.  You would not want to kill the process when the activity is merely sent to the background.

A: Thing you needed to check is when app goes in background and when app goes in background stop your service. For that you needed use
ActivityLifecycleCallbacks

You can find more info about from here ActivityLifecycleCallbacks
Also an example which will help you. link


text:
Q: I have no idea why did Boost Asio SSL handshake always fail? I tried use Boost Asio and Openssl to post some json to a SSL server,my case was it sucks when the code execute handshake with the server,the error was
"handshake: certificate verify failed"
 and I have no idea even I have Googled and viewed a branch of relative web pages ,I didn't find the answer yet,the SSL client example seems didn't work for me,what wrong I have done?
my code is
#include "root_certificates.hpp"
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ssl/error.hpp>
#include <boost/asio/ssl/stream.hpp>
#include <cstdlib>
#include <iostream>
#include <string>
#include <time.h>
#include<fstream>
#include <ctime>
#include <istream>

int postsslserver()
{
    try
    {
        auto const host ="mydomain.com";
        auto const port = "https";
        auto const target ="/apps/postpage.html" ;
        retcode = 0;

        char mybuffer[80];

        setlocale(LC_ALL, "");

        pwmd5hashed = "mysecret";

        std::string jsondata ="\"Double\":12.0000001,";

        int version =11;

        // The io_context is required for all I/O
        boost::asio::io_context ioc;

        // The SSL context is required, and holds certificates
        ssl::context ctx{ ssl::context::sslv23_client };

        //20181021
        ctx.set_default_verify_paths();

        // This holds the root certificate used for verification
        //load_root_certificates(ctx);

        // Verify the remote server's certificate
        //ctx.set_verify_mode(ssl::verify_peer);
        ctx.set_verify_mode(ssl::verify_peer);

        // These objects perform our I/O
        tcp::resolver resolver{ ioc };
        ssl::stream<tcp::socket> stream{ ioc, ctx };

        // Set SNI Hostname (many hosts need this to handshake successfully)
        if (!SSL_set_tlsext_host_name(stream.native_handle(), host))
        {
            boost::system::error_code ec{ static_cast<int>(::ERR_get_error()), boost::asio::error::get_ssl_category() };
            throw boost::system::system_error{ ec };
        }

        // Look up the domain name
        auto const results = resolver.resolve(host, port);

        // Make the connection on the IP address we get from a lookup
        boost::asio::connect(stream.next_layer(), results.begin(), results.end());

        // Perform the SSL handshake
        stream.handshake(ssl::stream_base::client);// error always occured this line of code,the error hints was "handshake: certificate verify failed"

        // Set up an HTTP POST request message
        http::request<http::string_body> req{ http::verb::post, target, version };
        req.set(http::field::host, host);
        req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
        req.set(http::field::content_type, "application/json");
        req.set(http::field::body, jsondata);
        //req.keep_alive(req.keep_alive());

        // Send the HTTP request to the remote host
        http::write(stream, req);

        // This buffer is used for reading and must be persisted
        boost::beast::flat_buffer buffer;

        // Declare a container to hold the response
        http::response<http::dynamic_body> res;

        // Receive the HTTP response
        http::read(stream, buffer, res);

        // Write the message to standard out
        std::cout << res << std::endl;

        // Gracefully close the stream
        boost::system::error_code ec;
        stream.shutdown(ec);
        if (ec == boost::asio::error::eof)
        {
            // Rationale:
            // http://stackoverflow.com/questions/25587403/boost-asio-ssl-async-shutdown-always-finishes-with-an-error
            ec.assign(0, ec.category());
        }
        if (ec)
            throw boost::system::system_error{ ec };

        // If we get here then the connection is closed gracefully
    }
    catch (std::exception const& e)
    {
        //std::cerr << "Error: " << e.what() << std::endl;
        write_text_to_log_file(e.what());
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

thanks in advance


text:
Q: Gaussian process regressor - same std-deviation for all the values sklearn 0.23 version Q1) I using Gaussian process regressor on sensor data to estimate human pose. while predicting on the test data I am getting std deviation same for all the values. Is it normal to get standard deviation same as I have used Standscaler() for scaling the data.
Q2) Secondly, I want to improve my score on test data, currently it performs poorly with score 0.27.
whenever I am trying to use mixture of kernel my process gets stuck and never returns. Any suggestion, how to resolve this issue.
Below is the code.
scaler_x = StandardScaler()
scaler_y = StandardScaler()

stance_train = scaler_x.fit_transform(stance_train)
stance_label = scaler_y.fit_transform(stance_label)
stance_test = scaler_x.transform(stance_test)
stance_test_label = scaler_y.transform(stance_test_label)
kernel = RBF(length_scale=3.0, length_scale_bounds=(10,1e-02))
gpr1 = GaussianProcessRegressor(kernel=kernel, random_state=0, n_restarts_optimizer=500, normalize_y=True, alpha=0.01).fit(stance_train,stance_label)

res1 = gpr1.score(stance_test, stance_test_label)
print(res1)

mean, sigma = gpr1.predict(stance_test[:1], return_std=True)
print(sigma)
[0.10220269 0.10220269 0.10220269 0.10220269 0.10220269 0.10220269
0.10220269 0.10220269 0.10220269 0.10220269 0.10220269 0.10220269
0.10220269 0.10220269 0.10220269 0.10220269 0.10220269 0.10220269]
print(mean)
[[-0.32279146 -1.36695596 -0.09067824 -1.46859509 0.71355078 0.76069065
-1.32083008 0.13645212 -0.13363496 -0.12042919 0.65796758 0.04662945
-0.7011215 -1.28839211 -0.17705824 0.37084057 -0.46027648 0.33293756]]


text:
Q: Why I am getting cross origin error in React? I am quite new in React. I have build an event scheduler web app but it's only working in my browser if I try it to different browsers or someone else system it gives me this error:

A cross-origin error was thrown. React doesn't have access to the actual error object in development.

I am trying to figure out but all I can understood it's happening because I am giving default values in state if local storage in undefined. Here is my complete code.
This is the component that is getting the error:
import React from "react";
import { Container, Row, Table } from "react-bootstrap";
import EventModal from "./EventModalButton";

class EventList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      title: "",
      eventtype: "",
      time: ""
    };
  }

  componentDidMount() {
    const defaultData = {
      title: "AI",
      eventtype: "Workshop",
      time: "02:00PM"
    };
    const eventData = JSON.parse(localStorage.getItem("Data") || defaultData);
    this.setState({
      title: eventData.title,
      eventtype: eventData.eventtype,
      time: eventData.time
    });
  }

  render() {
    return (
      <Container fluid="md">

              Title
              Type
              Time
              Date

              {this.state.title}
              {this.state.eventtype}
              {this.state.time}
              Monday, 31/08/2020

        <Container className="row" />
        <Row className="justify-content-center">
          <EventModal />
        </Row>
      </Container>
    );
  }
}
export default EventList;

A: You're trying to parse an object. JSON.parse expects a JSON but you're passing an object.
You could check the sandbox here
 componentDidMount() {
    const defaultData = {
      title: "AI",
      eventtype: "Workshop",
      time: "02:00PM"
    };

    // JSON.parse throws an error when parsing the object.
    const eventData = JSON.parse(localStorage.getItem("Data")) || defaultData;
    this.setState({
      title: eventData.title,
      eventtype: eventData.eventtype,
      time: eventData.time
    });
  }


text:
Q: Cannot set state using usereducer function I have two initial state posts and users. I am able to update the state of posts but not of users. I am using the JWT to send the token from the server-side to the client-side. When I console out the response received after sending the axios post request to /login, I am able to get the token sent from the server. But, when I set the state of users using the reducer function as action.payload and send it to the Login.js I am getting the users value as [].
const initialValue = {
    posts: [],
    users: []
}

const reducer = (state, action) => {
    switch (action.type) {
        case 'LOGIN':
            return {
                ...state,
                users: [action.payload]
            }
        default:
            return state
    }
}

export const Globalcontext = createContext(initialValue)

function App() {

    const [state, dispatch] = useReducer(reducer, initialValue)
    function login(User) {
        axios.post(`http://localhost:4000/blog/login`, User).then(res => {
            dispatch({
                type: 'LOGIN',
                payload: res.data
            })
            console.log(res.data) /* I am getting the desired token value */
        }).catch(err => {
            console.log(err)
        })
    }

After receiving the users state I am trying to set the localStorage item value to that state so that I can authenticate the user.

const Login = () => {
    let history = useHistory();
    const [email, setemail] = useState('');
    const [password, setpassword] = useState('');

    const { login, users } = useContext(Globalcontext);

    const handleSubmit = (e) => {
        e.preventDefault();

        const addedValue = {
            email,
            password,
        };

        localStorage.setItem('usertoken', users);
        console.log(localStorage.getItem('usertoken')); /* Here, I am getting [] as the output. */
        login(addedValue);

        setemail('');
        setpassword('');
        history.push('/blog');
    };
    return (
        <div>
            <form onSubmit={handleSubmit}>
                <input
                    type='email'
                    name='email'
                    value={email}
                    placeholder='E-mail address'
                    onChange={(e) => setemail(e.target.value)}
                />
                <input
                    type='password'
                    name='password'
                    value={password}
                    placeholder='Password'
                    onChange={(e) => setpassword(e.target.value)}
                />
                <button
                    className='btn btn-secondary'
                    style={{ backgroundColor: '#007bff', margin: '5px' }}
                    type='submit'
                    value='submit'
                >
                    Login
                </button>
            </form>
        </div>
    );
};

export default Login;


text:
Q: Netlogo BehaviorSpace mean value after every repetition in BehaviorSpace I have ["concetration" 0 0.2 1] and for each value of concetration I have to make 1000 repetiotions, but I have to bring a mean value of ticks after those repetition, not any other value. Someone knows how to do this? So what I want in result is:
concetration = 0.0 <mean value of ticks after 1000 repetitions>
concetration = 0.2 <mean value of ticks after 1000 repetitions>
concetration = 0.4 <mean value of ticks after 1000 repetitions>

A: ticks is the number of time steps that the simulation ran for. Does it end naturally (like an epidemic runs out) or do you stop it after a certain number of ticks? If you stop it after a fixed number of ticks, then the mean of ticks doesn't make sense.
Assuming that what you are asking is to calculate the average number of ticks that the simulation runs for before ending naturally (1) have BehaviorSpace just record the end of the simulation, not every step (2) look at the BehaviorSpace output and the variable [step] is the last step that the simulation did, which is also ticks if you have the normal setup / go structure.


text:
Q: Difference in IMap and ICache in Hazelcast I am new to Hazelcast. What's the difference between IMap and Icache in hazelcast? It would be great if some one can provide the uses cases when to use IMap and ICache. Currently I am using IMap to save data in hazelcast cluster, just want to know, what will be use cases for using Icache.

A: ICache is the JCache (JSR 107 specification) interface implementation. IMap is more like an extension to java concurrent map. If you do not have any requirement to implement the JCache interface, you can use IMap.


text:
Q: Purpose of checking if the entity state is deleted before deleting     public virtual void Delete(T entity)
    {
        DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
        if (dbEntityEntry.State != EntityState.Deleted)
        {
            dbEntityEntry.State = EntityState.Deleted;
        }
        else
        {
            DbSet.Attach(entity);
            DbSet.Remove(entity);
        }
    }

Of course this method is identical to this:
    public virtual void Delete(T entity)
    {
        DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
        if (dbEntityEntry.State == EntityState.Deleted)
        {
            DbSet.Attach(entity);
            DbSet.Remove(entity);  // Why to remove here??
        }
        else
        {
            // And why to set as Deleted here??
            dbEntityEntry.State = EntityState.Deleted;
        }
    }

I have seen above code in this article. IMHO some parts of this code is redundant. What is the purpose of if statement? And what is the purpose of else statement?
As I have tested, difference between DbSet.Remove(entity); and dbEntityEntry.State = EntityState.Deleted is that, all referenced rows are also deleted in first code, but in second one EF will throw exception about rows which has FK to this row.

A: When you call the DbSet.Remove(entity) in EF 6.X, you are really using the ObjectContext.DeleteObject(entity). This is the code that is called in the InternalSet<TEntity> class:
public virtual void Remove(object entity)
{
    DebugCheck.NotNull(entity);
    if (!(entity is TEntity))
    {
      throw Error.DbSet_BadTypeForAddAttachRemove("Remove", entity.GetType().Name, typeof(TEntity).Name);
    }
    InternalContext.DetectChanges();
    InternalContext.ObjectContext.DeleteObject(entity);
}

If the foreign key on the dependent entity is not nullable, by default, when you configure your relationship, Code First sets cascade delete on the relationship,so, when you call the Remove method, it also deletes all the child objects in the constrained relationship (EF will generate the delete statements for the parent entity and the related entities). If a foreign key on the dependent entity is nullable, Code First does not set cascade delete on the relationship, and when the principal is deleted the foreign key will be set to null.
Now, when you use the second variant changing the state of a parent entity as Deleted (bEntityEntry.State = EntityState.Deleted), EF attaches a whole entity graph to the context with specified state to parent entity and with the children three things can happen depending on the type of relationship you have:

*

*If the relationship is optional, i.e. the foreign key that refers from the child to the parent in the database allows NULL values, this foreign will be set to null and if you call SaveChanges this NULL value for the childEntity will be written to the database (i.e. the relationship between the two is removed). This happens with a SQL UPDATE statement. No DELETE statement occurs.

*If the relationship is required (the FK doesn't allow NULL values) and the relationship is not identifying (which means that the foreign key is not part of the child's (composite) primary key) you have to either add the child to another parent or you have to explicitly delete the child (with DeleteObject then). If you don't do any of these a referential constraint is violated and EF will throw an exception when you call SaveChanges - the infamous "The relationship could not be changed because one or more of the foreign-key properties is non-nullable" exception or similar.

*If the relationship is identifying (it's necessarily required then because any part of the primary key cannot be NULL) EF will mark the childEntity as Deleted as well. If you call SaveChanges a SQL DELETE statement will be sent to the database. If no other referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.
Fo more info, you can check this post and this too.
So, IMHO it's better create a generic Delete method this way:
public virtual void Delete(T entity)
{
   //Attach the entity to your context
   DbSet.Attach(entity);
   // Remove the current entity and the related entities in case of your relationship was configured with cascade delete
   DbSet.Remove(entity);
}

Update
Me neither see the point of the author in use both variants.Usually when you create a Remove generic method  is used one of this two variants, not both at the same time. If you use the DbSet.Remove I don't see the point in check the state, this method will do the job for you. If you use the second variant, I would create a method like this:
public virtual void Delete(T entity)
{
    // An Added entity does not yet exist in the database. If it is then marked as deleted there is
    // nothing to delete because it was not yet inserted, so just make sure it doesn't get inserted.
   dbEntityEntry.State == EntityState.Added
                ? EntityState.Detached
                : EntityState.Deleted);
}


text:
Q: weird usage of unique_ptr I'm seeing some code that uses unique_ptr in some weird ways, i'm not sure if it is even legal, although it seems to compile fine on g++ with -std=c++0x
#include <memory>
#include <boost/unordered_map.hpp>

typedef std::unique_ptr< std::string > str_ptr_t;

typedef boost::unordered_map< int , str_ptr_t > map_t;

str_ptr_t& get_ptr_value(map_t& map, int key)
{
   return map[key];
};

int main()
{
  map_t map;
  str_ptr_t& ref_to_value_of_0 = get_ptr_value(map, 0);
  map[0] = std::move(ref_to_value_of_0);
};

briefly explained, the map value type is a unique_ptr< std::string >. I initialise a reference to the value of key = 0. I then proceed to move the content of that reference to the same instance value, so basically the unique_ptr is being moved onto itself. This seems that to avoid creating many instances of the pointed object, it is attempted to reuse the existing entry instance if one already exists, and then add it again. In reality the assignment is hidden inside a store interface, and the reference is returned from a get interface, but the overall sequence can be summarized in the code i show above
Besides of being a bit weird, is this valid usage of unique_ptr?

A: The move assignment is defined in terms of reset and release, and so it's essentially doing this:
ref_to_value_of_0.reset(ref_to_value_of_0.release())

If you work out how this is evaluated you will find it to be a safe "no-op". It releases the owned pointer, frees a null, then sets its pointer back to original value.
I don't really understand why you are doing that though.


text:
Q: If cohomology theory corresponds to intersection theory, valuation theory corresponds to -? This is a meta question I asked myself. Cohomology theory is dual to an intersection theory. Is there anything valuation theory corresponds to in general?
For instance, McMullen's polytope algebra is dual to the stable intersection of tropical cycles.


text:
Q: Running android got error like this "unresolved supertypes: com.google.android.gms.internal.zzbej" Error message after run android kotlin: Supertypes of the following classes cannot be resolved. Please make sure you have the required dependencies in the classpath: class com.google.firebase.messaging.RemoteMessage, unresolved supertypes: com.google.android.gms.internal.zzbej
I use firebase gradle as below
compile 'com.google.firebase:firebase-messaging:11.6.2'
compile 'com.google.firebase:firebase-database:11.6.2'
compile 'commons-codec:commons-codec:1.9'
compile 'com.google.android.gms:play-services:11.6.2'

Here my gradle
apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

apply plugin: 'kotlin-kapt'

apply plugin: 'realm-android'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "ig.pipayalipayalliance.android"
        minSdkVersion 19
        targetSdkVersion 28
        versionCode 20
        versionName "1.4.9 UAT"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
        vectorDrawables.useSupportLibrary = true
    }

    buildTypes {
        debug {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    dataBinding {
        enabled = true
    }
    configurations {
        all {
            exclude module: 'httpclient'
        }
    }
    lintOptions {
        checkReleaseBuilds false
        abortOnError false
    }
    sourceSets {
        main {
            java.srcDirs = ['src/main/java', 'src/main/aidl']
            jniLibs.srcDirs = ['libs']
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    //noinspection GradleCompatible
    implementation "com.android.support:appcompat-v7:$supportVersion"
    //noinspection GradleCompatible
    implementation "com.android.support:design:$supportVersion"
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    //noinspection GradleCompatible
    implementation 'com.android.support:support-v4:27.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'
    compile('com.squareup.retrofit2:converter-simplexml:2.3.0') {
        exclude group: 'xpp3', module: 'xpp3'
        exclude group: 'stax', module: 'stax-api'
        exclude group: 'stax', module: 'stax'
    }
    compile 'com.squareup.okhttp3:logging-interceptor:3.8.1'
    // Multidex
    compile 'com.android.support:multidex:1.0.2'
    // Rx
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    // Data binding
//    kapt 'com.android.databinding:compiler:3.1.0-alpha05'
    // Anko Commons
    compile "org.jetbrains.anko:anko-commons:$anko_version"
    // Network connection
    compile 'com.github.TuonBondol:NetworkUtil:1.0.2'
    // Keyboard
    compile 'com.github.TuonBondol:KeyboardUtil:1.0.1'
    // Image loading
    compile 'com.github.bumptech.glide:glide:4.4.0'
    kapt 'com.github.bumptech.glide:compiler:4.4.0'
    // Detect keyboard status
    compile 'net.yslibrary.keyboardvisibilityevent:keyboardvisibilityevent:2.1.0'
    //noinspection GradleCompatible
    compile 'com.google.firebase:firebase-messaging:11.6.2'
    compile 'com.google.firebase:firebase-database:11.6.2'
    compile 'commons-codec:commons-codec:1.9'
    compile 'com.google.android.gms:play-services:11.6.2'
    // Generate qr code
    compile 'com.github.SumiMakito:AwesomeQRCode-Kotlin:1.0.5'
    compile files('libs/pushservice20140827.jar')
    //Round image plugin
    implementation 'com.makeramen:roundedimageview:2.2.1'
    implementation 'com.budiyev.android:code-scanner:1.9.2'
    // infinite scroll
    compile 'com.github.tuonbondol:Android-RecyclerView-Infinitescroll:1.0.5'

    //load image
    implementation 'com.squareup.picasso:picasso:2.71828'
}
apply plugin: 'com.google.gms.google-services'

A: Use latest version of those libraries like below and you have replace compile with implementation
implementation 'com.google.firebase:firebase-messaging:20.0.0'
implementation 'com.google.firebase:firebase-database:19.1.0'
implementation "com.google.firebase:firebase-core:17.2.0"
implementation "com.google.android.gms:play-services:12.0.1"

You have to update all firebase libraries with Google Play service. This is old enough.
Besides this you should have used only specific google play service instead of bundled one.

A: It could be a ProGuard issue. I can't post a full solution right now, but you can google how to instruct ProGuard to keep Firebase classes. I'll update later if I can.


text:
Q: SpeechRecognizer on Android 7.0 I've implemented a SpeechRecognizer, and it's working  perfectly on Android 6, but its not working on android 7.0, I don't know why.
If I try to use the recognizer on startActivityforResult(), it work's perfectly, but if I use createListener method, nothing happens, even I tried to output all results.
Here is my code :
class listener implements RecognitionListener
{
    String TAG = "AFFICHAGE";
    public void onReadyForSpeech(Bundle params)
    {
        Toast.makeText(MainActivity.this,"READY TO LISTEN", Toast.LENGTH_LONG).show();
    }
    public void onBeginningOfSpeech()
    {

    }
    public void onRmsChanged(float rmsdB)
    {

    }
    public void onBufferReceived(byte[] buffer)
    {
        Log.d(TAG, "onBufferReceived");
    }
    public void onEndOfSpeech()
    {
        Log.d(TAG, "onEndofSpeech");
    }
    public void onError(int error)
    {
        switch (error){
            case SpeechRecognizer.ERROR_AUDIO:
                Toast.makeText(MainActivity.this, "ERROR AUDIO",Toast.LENGTH_LONG).show();

                break;

            case SpeechRecognizer.ERROR_CLIENT:
                Toast.makeText(MainActivity.this, "ERROR CLIENT",Toast.LENGTH_LONG).show();

                break;

            case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
                Toast.makeText(MainActivity.this, "ERROR PERMISSION",Toast.LENGTH_LONG).show();

                break;

            case SpeechRecognizer.ERROR_NETWORK:
                Toast.makeText(MainActivity.this, "ERROR INTERNET",Toast.LENGTH_LONG).show();

                break;

            case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
                Toast.makeText(MainActivity.this, "ERROR TIMEOUT",Toast.LENGTH_LONG).show();

                break;

            case SpeechRecognizer.ERROR_NO_MATCH:
                Toast.makeText(MainActivity.this, "ERROR NO MATCH",Toast.LENGTH_LONG).show();

                break;

            case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
                Toast.makeText(MainActivity.this, "ERROR BUSY",Toast.LENGTH_LONG).show();

                break;

            case SpeechRecognizer.ERROR_SERVER:
                Toast.makeText(MainActivity.this, "ERROR SERVER",Toast.LENGTH_LONG).show();

                break;

            case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
                Toast.makeText(MainActivity.this, "ERROR TIMEOUT",Toast.LENGTH_LONG).show();

                break;

            default:

                break;
        }
    }
    public void onResults(Bundle results)
    {
        String str = new String();
        Log.d(TAG, "onResults " + results);
        ArrayList data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
        for (int i = 0; i < data.size(); i++)
        {
            Log.d(TAG, "result " + data.get(i));
            str += data.get(i);
        }
        txtSpeechInput.setText("results: "+String.valueOf(data.size()));
    }
    public void onPartialResults(Bundle partialResults)
    {
        Log.d(TAG, "onPartialResults");
    }
    public void onEvent(int eventType, Bundle params)
    {
        Log.d(TAG, "onEvent " + eventType);
    }
}

and here is where I call it :
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    txtSpeechInput = (TextView) findViewById(R.id.txtSpeechInput);
    btn = (Button) findViewById(R.id.button);
    sr = SpeechRecognizer.createSpeechRecognizer(this);
    sr.setRecognitionListener(new listener());
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
            //intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"voice.recognition.test");

            //intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,5);
            sr.startListening(intent);
            Log.i("111111","11111111");
        }
    });
}

Thank for answer.

A: I've found a solution to make it work on initializiting the google librairie like this : SpeechRecognizer.createSpeechRecognizer(getApplication(), ComponentName.unflattenFromString("com.google.android.googlequicksearchbox/com.google.android.voicesearch.serviceapi.GoogleRecognitionService"));
And it's work, so I don't now if it's a good solution or not.


text:
Q: SQL Server listen on a specific port I want to change the PORT to 255:

*

*can i change per db or just for instance?

*is there any issue can come up?

*have to restart the service?

A: You can specify the port SQL Server listens on for each IP address it is listening on, but not per database.  To change an existing installation of SQL Server, run SQL Server Configuration Manager, expand SQL Server Network Configuration, and select Protocols for MSSQLSERVER in the left pane.  Then right-click on TCP/IP in the right pane and select Properties.  On the IP Addresses tab, change the TCP Port for each address as desired.
You will need to restart the service for the change to take effect.
Most SQL Server clients will use port 1433 by default, so if you use a different port, clients will have to be configured to designate the port SQL Server is listening on.
One of the issues that can occur with specifying an alternate port is that another application is already using that port, or RPC may grab that port before SQL Server starts up.  Google "rpc dynamic port range" to research that.  So if you configure SQL Server to use a port that is in the range that RPC uses, SQL Server may start one time, but not the next.  Use the netstat command to see what ports are in use on the server, and review documentation of installed applications to ensure you don't select a port that your applications are using.  Just because you don't see it in use in netstat doesn't mean the application doesn't use it itermittently--not likely, but possible.
Also, firewall rules on client, server, and network devices that allow port 1433 may need to be modified or added to so that the port of your choice will not be blocked.


text:
Q: Binding two dataframes with "Date" column on different RStudio IDEs produces different results I am producing a new dataframe by binding together two dataframes obtained from two different GitHub repositories. Both dataset have a Date column.
When I do this operation on my machine everything is fine, and I can use the functions rbind() or bind_rows() to bind together the dataframes.
Another user tried the same code and the result is different. In particular, the Date column is split. The dates of the first dataframe are under the first column (called Date), while the dates of the second dataframe are placed at the end of the dataframe, in a new column (that I haven't created) called X.U.FEFF.Date.
Below there is the code I used:
library(dplyr)
library(RCurl)

setwd(dir = "YOUR_WORKING_DIRECTORY")

#####===== FIRST DATAFRAME =====#####
cases <- read.csv(text = getURL(url = "https://raw.githubusercontent.com/openZH/covid_19/master/COVID19_Cases_Cantons_CH_total.csv"),
                  header = TRUE,
                  stringsAsFactors = FALSE,
                  na.strings = c("", "NA"),
                  encoding = "UTF-8")

# Removed data for whole Switzerland and Leichtenstein
cases <- subset(x = cases,
                !is.element(el = canton,
                            set = c("CH", "FL")),
                select = c("date",
                           "canton",
                           "tested_pos"))

names(cases)[1] <- "Date"

# Dataset restructured according to the cases dataset format
cases <- reshape(data = cases,
                 idvar = "Date",
                 timevar = "canton",
                 v.names = "tested_pos",
                 direction = "wide",
                 )

names(cases) <- gsub(pattern = "tested_pos.",
                     replacement = "",
                     x = names(cases))

cases[is.na(cases)] <- 0

cases <- cases[order(cases$Date,
                     decreasing = FALSE), ]

#####===== SECOND DATAFRAME =====#####
cases2 <- read.csv(text = getURL(url = "https://raw.githubusercontent.com/daenuprobst/covid19-cases-switzerland/master/covid19_cases_switzerland.csv"),
                   header = TRUE,
                   stringsAsFactors = FALSE,
                   na.strings = c("", "NA"),
                   encoding = "UTF-8")

# Remove total daily cases for Switzerland
cases2 <- subset(x = cases2,
                 select = -c(CH))

# rbind between two cases datasets
cases_tot <- bind_rows(cases[1:7, ],
                       cases2)

write.csv(x = cases_tot,
          file = paste0(getwd(),
                        "/cases_tot.csv"),
          row.names = FALSE,
          quote = FALSE)

For the other user, the function rbind() just fails, while the function bind_rows() produces the output displayed in this image. I don't know how to solve this issue because I can't reproduce it on my machine.
Any idea about what's causing this issue? Thanks a lot.

A: As per comment:
Change read.csv() to read_csv() for more robust csv parsing!


text:
Q: Android Studio throws "No signature of method" error, pointing to build.gradle I got the following error when compiling my code in Android Studio:
A problem occurred evaluating project ':app'.
> No signature of method: build_16swdi705s6eau9c2h85w6rs5.android() is applicable for argument types: (build_16swdi705s6eau9c2h85w6rs5$_run_closure1) values: [build_16swdi705s6eau9c2h85w6rs5$_run_closure1@34d7c56f]
The error points me to this section of the build.gradle:app file (specifically, the line with android {
android { compileSdk version 31
defaultConfig {
    applicationId "com.example.facedetection"
    minSdk 23
    targetSdk 31
    versionCode 1
    versionName "1.0"

    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}

What does this error message mean, and what can I change to fix the issue?

A: Make sure your signing configs are correct, which looks like this-
signingConfigs {
       release {
           keyAlias keystoreProperties['keyAlias']
           keyPassword keystoreProperties['keyPassword']
           storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
           storePassword keystoreProperties['storePassword']
       }
   }
   buildTypes {
       release {
           signingConfig signingConfigs.release
       }
   }

and then set the compileSdkVersion to 30 and targetSdkVersion to 30.


text:
Q: Issue with getting UPN on a federated Azure AD B2C sign-up custom policy flow If I add Azure AD as an IDP to B2C using a built-in sign-up policy and sign-up with an existing Azure AD user (i.e. federation), the "placeholder" on B2C has a source of "Federated Azure Active Directory". The signed-up user has a UPN.
I can't seem to sign-in to B2C using a custom sign-in policy with that user name?
It says "Account does not exist. Please sign-up". I assume you can't mix and match built-in and custom?
I have to sign-up and sign-in using custom policies to get the sign-in to work.
In this case, the source of the "placeholder" is "Other".
The problem is that this signed-up user does not have a UPN.
Is there a way to get a UPN?
Or is this by design?

A: The reason is, the Issuer used in user flow is different to custom policy.
If you return the user via MS Graph (beta version), compare the Identities array of a user signed up via custom policy versus user flow (for AAD). The issuer will be different (login.microsoftonline.com vs sts.windows.net). The combination of Issuer and AAD objectId are used to create and locate the user.
Due to the mismatch, a user signed up via AAD federation with a user flow can't sign in via custom policy, account won't be found.
By analysing the Identities object on the users, you can take the value of the Issuer property on the account created with user flow, and insert it into your AAD Custom Policy Technical Profile for the claim called "IdentityProvider".
Change this
<OutputClaim ClaimTypeReferenceId="identityProvider" PartnerClaimType="iss" />

To
<OutputClaim ClaimTypeReferenceId="identityProvider" DefaultValue="ISSUER FROM USER FLOW USER" />

https://learn.microsoft.com/en-us/azure/active-directory-b2c/identity-provider-azure-ad-single-tenant?pivots=b2c-custom-policy#configure-azure-ad-as-an-identity-provider-1


text:
Q: Sequence of results from MySql Table I have a database for my 6-aside football team going back 10 years which is fairly normalised, so I can pull lots of stats from it for players, eg number of games played, goals scored, average points per game by player etc.
I want to add a new stats page for sequences, eg longest run of consecutive clean sheets for goalies, longest run of consecutive wins for the team, longest run scoring in consecutive games etc.
The important tables are 'fixtures' (containing amongst others fixtureid, scorefor, scoreagainst) and 'played' (containing amongst others playerid, fixtureid, goalsscored). So to see who scored in fixture 128 I would use
SELECT playerid, goalsscored
FROM played p
WHERE p.fixtureid = 128 AND goalsscored > 0

So how would I form a query showing which player scored in most consecutive games, eg Alex (playerid 15) scored in 6 consecutive games (fixtureid 126-132) and Dave (playerid 12) scored in 5 consecutive games (fixtureid 130-135)? Initially we can assume that fixtureid is sequential without breaks and is the order in which games were played.
I have used Sql for quite a while, but stumped by this one and I can't find any similar questions asked before.
In response to a request for more info I have added an EER diagram.

A: Here's how I would do it in code.
Create an List of keyvalue pairs 'CompletedSequences' - key=playerid, value=consecutivagamesscored
Create a similar List of keyvalue pairs 'CurrentSequences'
Select the list of fixtures ordered by date, omitting postponed
For each fixtureid {
   For each kv pair in CurrentSequences {
      If playerid didn't score in this fixture {   /* End of sequence for this kv */
          Add kv pair to CompletedSequences if count > 1   /* Only bother saving those with at least 2 in a sequence */
          Remove kv pair from CurrentSequences
      }
   For each scorer in this fixture {
      If playerid key exists in CurrentSequences increment count /* Add 1 to sequence */
      else create new CurrentSequences kv pair with playerid/1  /* Create new start of sequence for this player */
   }
For each kv pair in CurrenSequences  /* Finish off the ones left unterminated */
   Add kv pair to CompletedSequences if value > 1
Sort CompletedSequencies by value (consecutive games scored)
Make a table of the top 10 sequences with player/count of consecutive games scored.

I can't help feeling that some clever SQL script would do this better and I would prefer not to have to suck the whole resultset into memory to do it in PHP if I can avoid it. I guess I'll have do it that way if there isn't a way in MySQL.


text:
Q: Laravel 8 not finding "tag" from package "\Conner\Tagging\Taggable;" The code works perfectly when I want to create a new tag from scratch, but when $skillsQuery->count() > 0 and enters in the if statement. It prints...

Method Illuminate\Database\Eloquent\Collection::tag does not exist.

How can I update tags using this package?
Controller
<?php

public function storeSkills(Request $request)
{
    $id = auth()->user()->id;
    $skillsQuery = Skill::where('created_by', $id)->get();

    // If skill exists
    if ($skillsQuery->count() > 0) {
        $input = $request->all();
        $tags = explode(", ", $input['name']);
        // $skill = Skill::create($input);
        $skillsQuery->tag($tags);
        $skillsQuery->created_by = $id;

        if ($skillsQuery->save()) {
            return redirect()->route('profile')->with('success', 'Skills updated successfully');
        } else {
            return redirect()->route('profile')->with('error', 'Error updated your Skills!');
        }
    } else {
        $input = $request->all();
        $tags = explode(", ", $input['name']);
        $skill = Skill::create($input);
        $skill->tag($tags);
        $skill->created_by = $id;

        if ($skill->save())
            return redirect()->route('profile')->with('success', 'Skills stored successfully');
        else {
            return redirect()->route('profile')->with('error', 'Error storing your Skills!');
        }
    }
}

A: The result of calling ->get() on a Illuminate\Database\Query is that you will receive an instance of a Illuminate\Database\Collection, which does not contain a ->tag() method. Even if it was a query (by removing ->get()) this still would not work, as you can't call a relationship method off of a collection.
If instead you loop over the skillsQuery then you will receive an instance of a Model object which then allows you to access functions and/or relationships off of it:
$skillsQuery->each(function ($skill) use ($tags) {
  $skill->tag($tags); // or perhaps ->retag($tags); here
});


text:
Q: Does Symfony2 Have Filter Input Built in Classes I'm learning symfony2 and curious about how to filter user input in symfony2. In zend framework 2 they provide standard filter classes to filter input easily such as (Alnum, Digit, Alpha, HtmlEntities) so how about symfony ? I have been searching it but no luck I only found standard validation in symfony2.
Example for filtering inn zf2:
$filter = new \Zend\I18n\Filter\Alnum();
echo $filter->filter("This is (my) content: 123");
// Returns "Thisismycontent123"

If symfony doesn't provide standard filter classes is there any bundle out there to do the same thing?


text:
Q: PHP Timestamp with timezone Why is my timestamp different from the original datetime in my timezone?
ex. I run the code on 4/9/17 at 8:30:51.
The result will be 4/10/17 11:30:51
$now = new DateTime();
now->setTimezone(new DateTimeZone('Asia/Manila'));
echo $now->format("m/d/y G.i:s
");

A: This is simple, the date it's set to universal time zone, in your web server and most of the browsers.
$now = new DateTime();
$now->setTimezone(new DateTimeZone("Asia/Manila"));
echo $now->format("m/d/y G.i:s
");

So you use this code to parametrize your date.
DateTimeZone -> To your timezone, that I predict it to be Asia/Manila
format-> Format date to the desired format.
If it did not work, try this:
On the local server, you can change the configuration in PHP_INI.
In your file Look for:
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
date.timezone = UTC
change for
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
date.timezone = Asia/Manila
If this does not solve your problem. Use this in the beginning of all your PHP files.
date_default_timezone_set("Asia/Manila");
setlocale(LC_ALL, 'your_language');

Exemple:
date_default_timezone_set("America/Sao_Paulo");
setlocale(LC_ALL, 'pt_BR');

If you like, give a score or helpful flag.


text:
Q: I have function but in firebug console it says its not a function where I am calling it? I am using a function in two sites but when I want to implement it to third site it does not work. When I look into firebug console it says its not a function. My function is in a separate file called profilter.js look like this:
jQuery.fn.sfProductFilter = function (options) {
    options = options || {};
    return this.each(function () {
        var pf = new SFProductFilter(this, options)
    })
}

and I am calling it from a page and code is:
$(document).ready(function(){
            console.log($("ul.productSmall"));
            $('ul.productSmall').sfProductFilter(); //says not a function.
});

I have checked through console.log followings
1- jQuery is included already
2- If I console.log from the js file it works but inside any code block it does not
3- ul.productSmall shows right results in console.log
I can provide link of site but just not providing it so moderator wont thinks its a spam.
I have struggled a lot please let me know where I am making mistake?

A: (Copied from comment above.)
You are including jQuery twice, the second load happens far below the inclusion of profilter.js and destroys your custom function.

A: Are you including the jquery ui script?  Looks like .button() is called in
function myChecks(){
    $("#checkboxcontainer input[type='checkbox']").button();
}

I have a hunch this will do the trick.


text:
Q: Better way of comparing two JSON data in Automation Script I am new to JBehave Rest automation script. Below I wrote few lines of code where my requirement is to compare each and every actual JSON field data with the expected data. Here the number of fields in JSON is huge how can i write the script in best way which will handle such scenario.
JSONObject actualjson = new JSONObject(actualJsonresponse);
JSONArray actualjsonData = actualjson.getJSONArray("outputDtlList");
JSONObject expectedjson = new JSONObject(RTRestServicesBean.getConfigurationJsonConfigValue());
JSONArray expectedjsonData = expectedjson.getJSONArray("outputDtlList");

String actual_storagetype = actualjsonData.getJSONObject(0).getString("storageType");
String expected_storagetype = expectedjsonData.getJSONObject(0).getString("storageType");

Assert.assertEquals(actual_storagetype, expected_storagetype);

String actual_locnNbr = actualjsonData.getJSONObject(0).getString("locnNbr");
String expected_locnNbr = expectedjsonData.getJSONObject(0).getString("locnNbr");

Assert.assertEquals(actual_locnNbr, expected_locnNbr);

A: Consider using net.javacrumbs.json-unit:json-unit.
import static net.javacrumbs.jsonunit.JsonAssert.*;

...

assertJsonEquals(expectedjson, actualjsonData);

A: Consider switching to Karate, it handles full JSON payload comparison much better:
* def json = { foo: 'world', hey: 'ho', zee: [1, 2, 3] }
* remove json.hey
* match json == { foo: 'world', zee: [1, 2, 3] }


text:
Q: how to set up cache in a winform c# I couldn't find decent examples of how to accomplish simple caching in winforms c#
this is what i've come up with but I get exceptions.
// this line already gets an exception
   ICacheManager productsCache = CacheFactory.GetCacheManager("MyCacheManager");
the exception is:
Additional information: Could not load file or assembly 'Microsoft.Practices.EnterpriseLibrary.Common, Version=5.0.414.0,
the app.config which I think I am unable to config properly is:
<configuration>
    <configSections>
        <section name="cachingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Caching, Microsoft.Practices.EnterpriseLibrary.Caching, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
    </configSections>
    <cachingConfiguration defaultCacheManager="MyCacheManager">
        <cacheManagers>
            <add name="MyCacheManager" type="Microsoft.Practices.EnterpriseLibrary.Caching, Microsoft.Practices.EnterpriseLibrary.Caching, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                expirationPollFrequencyInSeconds="60" maximumElementsInCacheBeforeScavenging="1000"
                numberToRemoveWhenScavenging="10" backingStoreName="NullBackingStore" />
        </cacheManagers>
        <backingStores>
            <add type="Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.NullBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                name="NullBackingStore" />
        </backingStores>
    </cachingConfiguration>
</configuration>

I used the entlib config to create the app.config
I keep getting exceptions. is there an example I can use? (something more up-to-date than examples from 2007)
10x for your time

A: The Caching assembly depends on Microsoft.Practices.EnterpriseLibrary.Common. Your project needs to reference the Common assembly as well as Microsoft.Practices.EnterpriseLibrary.Caching.  Also, make sure the versions in your bin folder match the version specified in your configuration file.  If the config is generated using a version of the configuration tool that uses a different copy of the assemblies, it can create a version mismatch.
Can also check out the post below for some other ideas:
http://blogs.msdn.com/b/tomholl/archive/2007/04/19/avoiding-configuration-pitfalls-with-incompatible-copies-of-enterprise-library.aspx


text:
Q: Unable to bind ngModel I just started learning Angular and everything is pretty new to me. I have started a course and I got stuck with one part. When I try to do two way property binding, the ngModel is not working as expected.
This is the user.component.ts file:
import { Component, OnInit } from '@angular/core';
import { User } from '../../models/User';
@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css'],
})
export class UsersComponent implements OnInit {
    user: User = {
    firstName: '',
    lastName: '',
    age: 0,
    address: {
      street: '',
      city: '',
      state: ''
    }
  }
  users: User[];
  showExtended: boolean = true;
  loaded: boolean = false;
  enableAdd: boolean = true;
  showUserForm: boolean = false;

  constructor() {
    this.users = this.getUserDefaults();
  }

  ngOnInit(): void {
      this.loaded = true;
  }

  private getUserDefaults() {
    return [
      {
        firstName: 'John',
        lastName: 'Doe',
        age: 65,
        address: {
          street: '50 Main st',
          city: 'Boston',
          state: 'MA',
        },
        isActive: true,
        registered: new Date('01/02/2018 08:30:00'),
        hide: true
      },
      {
        firstName: 'Kevin',
        lastName: 'Johnson',
        age: 34,
        address: {
          street: '20 School st',
          city: 'Lynn',
          state: 'MA',
        },
        isActive: false,
        registered: new Date('03/11/2017 06:20:00'),
        hide: true
      },
      {
        firstName: 'Karen',
        lastName: 'Williams',
        age: 26,
        address: {
          street: '55 Mill st',
          city: 'Miami',
          state: 'FL',
        },
        isActive: true,
        registered: new Date('11/02/2016 10:30:00'),
        hide: true
      },
    ];

  }

  addUser(user: User) {
    this.users.push(user);
  }

  // toggleHide(user: User) {
  //   user.hide = !user.hide;
  // }

  onSubmit(e: any) {
    console.log(123)
    e.preventDefault()
  }

  fireEvent(e: any) {
    console.log(e.type)
    console.log(e.target.value)
  }

}

This is the users.component.html file
<button (click)="showUserForm = !showUserForm" class="btn btn-dark mb-3">Add User</button>

Add User

  <form (submit)="onSubmit($event)">

      First Name
      <input  type="text" class="form-control" name="firstName" [(ngModel)]="user.firstName">

        Last Name
        <input type="text" class="form-control" name="lastName" [(ngModel)]="user.lastName">

        Age
        <input type="number" class="form-control" name="age" [(ngModel)]="user.age">

        Street Address
        <input type="text" class="form-control" name="street" [(ngModel)]="user.address.street">

        City
        <input type="text" class="form-control" name="city" [(ngModel)]="user.address.city">

        State
        <input type="text" class="form-control" name="state" [(ngModel)]="user.address.state">

    <button (click)="addUser({ firstName: 'Mary', lastName: 'Jackson', isActive:true})" [disabled]="!enableAdd" class="btn btn-block mb-3">
      Add New User
    </button>
  </form>

Users

 0">

{{ user.firstName }} {{ user.lastName }} <button (click)="user.hide = !user.hide" class="btn btn-dark btn-sm"></button>

Age: {{ user.age }}

        Address: {{ user.address.street }}, {{ user.address.city }},
        {{ user.address.state }}

Joined: {{ user.registered | date }}

No Users Found

Loading Users...

And this is the interface
export interface User {
    firstName: string,
    lastName: string,
    age?: number,
    address?: {
        street?: string,
        city?: string,
        state?: string
    },
    isActive?: boolean,
    registered?: any,
    hide?: boolean
}

In the html file where I have the inputs the ngModel is not working as expected. I am trying to bind these inputs with
    user: User = {
    firstName: '',
    lastName: '',
    age: 0,
    address: {
      street: '',
      city: '',
      state: ''
    }
  }

ngModel for firstName, lastName and age works just fine. But when I try to bind ngModel with user.address.street or user.address.city or user.address.state, I get the follwoing error:
Error: src/app/components/users/users.component.html:19:89 - error TS2532: Object is possibly 'undefined'.

19         <input type="text" class="form-control" name="street" [(ngModel)]="user.address.street">
                                                                                ~~~~~~

  src/app/components/users/users.component.ts:5:16
    5   templateUrl: './users.component.html',
                     ~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component UsersComponent.

Does anybody know why is this happening and how to fix this problem? Thank you in advance.


text:
Q: How can I consolidate a SQL query as an integer? The following SQL (PHP, MySQL) gives me rows with one id per row and the number of matches for each id, as the COUNT() for each.
SELECT ot.id, COUNT(ot.id)
FROM ot
JOIN tm on tm.mediaid = ot.id
WHERE tm.uploadedToS3 = 1
    AND (
        ot.something IN (1)
        OR ot.somethingelse IN (1)
        OR ot.anotherthing IN (1)
        OR ot.morestuff IN (1)
        OR ot.evenmorestuff IN (1)
    )
GROUP BY ot.id

The result is something like...
ot.id COUNT(ot.id)
40153 4
40305 3
40309 35
40314 29
40315 12
40317 10
40318 16
40319 14
40324 154
40331 113

I would just like to know how many rows this query returns. I don't need any other information, just one integer. For the above, I am looking for the number of rows, i.e. I'd expect to just get the number 10.
How would I get this?
Thanks.

A: Use count(distinct) with no group by:
SELECT COUNT(DISTINCT ot.id)
FROM ot JOIN
     tm
     ON tm.mediaid = ot.id
WHERE tm.uploadedToS3 = 1 AND
      (ot.something IN (1)
        OR ot.somethingelseIN (1)
        OR ot.anotherthing IN (1)
        OR ot.morestuff IN (1)
        OR ot.evenmorestuff IN (1)
      )


text:
Q: ActsAsTaggableOn Tagging with checkboxes I'm playing with ActsAsTaggableOn in a small project to see what are the possibilities of this gem.
So I have Products and products can have tags.
In my Product _form
<%= form_for(@product) do |f| %>

  <%= f.label :title %>

  <%= f.text_field :title %>

Tags

<% tag_cloud(@tags, %w(css1 css2 css3 css4)) do |tag, css_class| %>
    <%= check_box_tag 'product[tag_list][]',tag.name,@product.tag_list.include? (tag),:class => css_class %>
    <%= tag.name %>
<% end %>

<%= f.submit %>

<% end %>

In ProductController I have defined the tag_cloud method
 def tag_cloud
   @tags = Product.tag_counts_on(:tags)
 end

So in my editing product, I can tag the product with the checkboxes, but if a product already has tags those checkboxes aren't selected. I assume that here @product.tag_list.include? (tag) I am missing something or doing something wrong.
Any ideas? Thanks for your help =)
Cheers.

A: Today, after reading more carefully, I found the answer to this one.
This line
<%= check_box_tag 'product[tag_list][]',tag.name,@product.tag_list.include? (tag),:class => css_class %>

should be
<%= check_box_tag 'product[tag_list][]',tag.name,@product.tag_list.include? (tag.name),:class => css_class %>

So instead of the object I want to check if that name exists in the list.
Hope this helps someone.


text:
Q: Ax=0, why A must be singular matrix for having x different from 0? For the given equation $Ax=0$ where $A$ is a square matrix and $x$ is a column vector, why $A$ must be a singular matrix (determinant $0$) in order to have $x$ different from null column vector?.

A: That's simply a matter of linear dependence of the columns of A.
Indeed note that the multiplication $Ax$ correspond to a combination of the columns vectors of A by the coefficient of the vector $x$.
Thus:

*

*if the columns of A are linearly independent (i.e. A not singular) the
only way to have Ax=0 is that $x=0$

*if the columns of A are linearly dependent (i.e. A singular) you
may have $Ax=0$ also for $x\neq0$

A: Because if $A$ is non-singular then its inverse $A^{-1}$ exists, and you have
$$0=A^{-1}0=A^{-1}\left(Ax\right)=\left(A^{-1}A\right)x=Ix=x$$


text:
Q: Using flask returned data in google charts in js I'm trying to use google charts on my website and i'm using flask as backend , but i don't know how to send data from flask to js, got this where i'm gonna get data from later on
@app.route("/")
def home():
    data = {'Language': 'DATABASE','PHP': 5000,'ASP': 600,'ASPX': 1231,'PERL': 500,'JSP': 1000}
    return render_template('index.html', data=data)

but how do i use that 'data=data' here :
function drawChart(stats) {
    var stats = '{{stats}}'
    var data = google.visualization.arrayToDataTable([
        ['Language', 'IN DATABASE'],
        ['PHP', 5000],
        ['ASP', 600],
        ['ASPX', 1231],
        ['PERL', 500],
        ['JSP', 1000]
    ]);

Here i'm just using a predifined var but later on i'm gonna pull data from a sqlite db and use it istead of that data var which is just for testing purposes.
Thanks in advance :D

A: You can include any passed data into the render_template(in your case, data) by enclosing them within {{}}.
Giving an example of chart.js:
<canvas id="myChart" width="100%" height="40%"></canvas>
                                            <script type="text/javascript">
                                            var ctx = document.getElementById("myChart");
                                            var xaxis = ['{{graph_year[0]}}', '{{graph_year[1]}}', '{{graph_year[2]}}', '{{graph_year[3]}}', '{{graph_year[4]}}', '{{graph_year[5]}}']
                                            var yaxis = ['{{graph_returns[0]}}', '{{graph_returns[1]}}', '{{graph_returns[2]}}', '{{graph_returns[3]}}', '{{graph_returns[4]}}', '{{graph_returns[5]}}']
                                            ctx.style.backgroundColor = 'rgba(255,255,255,1)';
                                            var myChart = new Chart(ctx, {
                                                type: 'bar',

Here, graphyear and graphreturns were passed as list type. You can also use the for statement to shorten the code.


text:
Q: Best_in_place gem not saving? (Rails) So, I'm using the best in place gem to allow users to edit their photos caption in place. However, the text that is entered isn't being saved or stored in the database.
Here is a snapshot of the schema relevant to this area:
create_table "photos", force: true do |t|
    t.string   "file"
    t.integer  "attachable_id"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "attachable_type"
    t.string   "title"
    t.text     "description"
    t.boolean  "profile_photo",   default: false
  end

and here's the view code:
<%= best_in_place photo, :description, type: :textarea, nil: 'Enter a Caption' %>

I can enter in the caption but when I refresh, it say's 'Enter a Caption' again and not the text that I've entered originally.
What am I doing wrong?
Thanks!


text:
Q: Send commands to enfora trakers OTA via tcp I work for a company that provide service to track vehicles with gps devices, rigth now I need to find a way to send commands to an enfora devices over the air using the tcp protocol, I have tried many ways with no results unfortunately. I just can send commands via sms.
I would like to send commands to request the current position, to open doors, etc.
This is the code I use to sent AT commands to other brands and it works like a charm!
var toBeSend = Encoding.ASCII.GetBytes(msj);
tcpClient.Client.Send(toBeSend);

What can be the problem, anyone knows?
If anyone have a script no matter if it is in c#, Java, PHP, Python, etc. please share it with me.

A: Using Netty I do this:
channel.write(ChannelBuffers.copiedBuffer(message, StandardCharsets.US_ASCII));

You have to consider that to send an AT command via TCP you have to add a header to the message and also the checksum.


text:
Q: React how to use data.props content to do conditional rendering I have a small question but I can't figure out how to perform it and how to find an other related post. Basically I want to display the instagram part only if there is {d.socials2}, otherwise I want to skip it :

      {props.data
        ? props.data.map((d, i) => (
            <div key={`${d.name}-${i}`} className='col-md-3 col-sm-6 team'>

                {' '}

{d.name}

{d.job}

Twitter:<a href={`https://twitter.com/${d.socials1}`}>{d.socials1}

                  {d.socials2.length > 0 &&

Instagram:<a href={`https://www.instagram.com/${d.socials2}`}>{d.socials2}

                  }

          ))
        : 'loading'}

How can I do that ?

A: You can do it like this:
{
  !!d.socials2 && (

      Instagram:
      <a href={`https://www.instagram.com/${d.socials2}`}>{d.socials2}

  );
}


text:
Q: Unique id of files and monitoring file system changes Do files or folders on S60 have some unique id value that can identify them?
I would like to have an id that can be later used to extract full path of a file or folder. Is this achievable?
If not, what would be the best way to keep track of files of interest?
E.g. if I have a pdf reader, and I want to have a menu option to show all pdf files on the system - how do I prevent my application to search all over the whole system every time I chose this option? Can I search it once and easily monitor changes while my application is active?
Thank you.

A: I can't quite see anything in the Symbian OS C++ API that would do exactly what you want.
Using RFs::NotifyChange() is probably your best bet.

A: Yes, index them at one point and use RFs::NotifyChange(). How would an ID help in identifying new files?

A: Symbian Timebox 10.1 (^3?) introduces a new file notification API, CFsNotify.
If tells you exactly what has changed and to which file/dir/drive.
http://developer.symbian.org/xref/epl/xref/MCL/sf/os/kernelhwsrv/userlibandfileserver/fileserver/inc/f32notification.h#140
It is similar to Microsoft's ReadDirectoryChangesW API.


text:
Q: Android how get device display colors I want to get display colors suppored for current device
here are example

google_pixel:16M colors
  samsung_c3300k_champ:256K colors

note: above value retrieved from device specification sites for example
also, I get that value is base on display bit for eg: device supports 24 bit then 2^24=16,777,216
but how to get current display bit that is not known

A: getPixelFormat() could be used to get the pixel format of the display.
But since API 17, it always returns RGBA_8888.
R - 8 bits
G - 8 bits
B - 8 bits
This comes out to be 24 bits used to represent a single pixel on the display.
Such a display can show 2^24 = 16,777,216 colors.


text:
Q: Set a variable within a Unity class I'm currently following a brackeys tutorial on dialogue, however I want to import multiple names, as well as multiple lines of dialogue along with them, through a text file rather than handwriting them. This differs greatly from the tutorial, so I'm stuck on creating a Dialogue class. Here's what I wrote up:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

 [System.Serializable]
public class Dialogue {
    // text file input
    public TextAsset textFile;
    // list containing each line of the text file
    protected string[] textLines;
    // lists containing names and dialogues (written in the file like so: Bob;I like pancakes)
    protected string[] names;
    protected string[] dialogues;

    // splits up the text file into the list of lines
    textLines = textFile.text.Split('\n');
    // iterates over the course of the list of lines, splitting up the names and dialogue, then sorting each into its respective list
    for (int i = 0; i <= textLines.Length - 1; i++) {
        names.Add(textLines[i].Split(';')[0]);
        dialogue.Add(textLines[i].Split(';')[1]);
    }
}

Unity, however, does not like this, and spits out loads of errors such as:

Assets\scripts\Dialogue.cs(12,15): error CS1519: Invalid token '=' in class, struct, or interface member declaration

and

Assets\scripts\Dialogue.cs(12,36): error CS1519: Invalid token '(' in class, struct, or interface member declaration

among others.
I assume there are limits when working with unity classes such as this one, however I evidently don't know them, and after looking through the internet, I was unable to find them. Any help with this is appreciated!

A: NOTE: I have never used Unity before, so take this with a grain of salt.
You can only assign class fields when you declare them, and you can only place for loops inside functions and properties (get and set are technically functions). Though class fields ARE modified in the application's lifetime, so there is no need to worry.
Also, string[]s do not have the .Add() method in them. Either convert the array into a List<string>, do an expensive operation that pushes new elements into an array or define a fixed size for the array.
You can do this:
/**
 * You can do one of these:
 * protected List<string> names; (we will use this)
 * protected string[] names = new string[SOME_SIZE];
 * protected string[] names; (and push elements)
 */

void AssignTextLines() {
    // splits up the text file into the list of lines
    textLines = textFile.text.Split('\n');

    // iterates over the course of the list of lines, splitting up the names and dialogue, then sorting each into its respective list
    for (int i = 0; i < textLines.Length; /* you don't need -1! */ i++) {
        names.Add(textLines[i].Split(';')[0]); // only for List<T>!!
        dialogues.Add(textLines[i].Split(';')[1]);
    }
}

or this:
protected string[] textLines = textFile.text.Split('\n');

void Something() {
    // then do the thing above
    for (int i = 0; i < textLines.Length; i++) {
        names.Add(textLines[i].Split(';')[0]); // only for List<T>!!
        dialogues.Add(textLines[i].Split(';')[1]);
    }
}

You can also replace the for loop with a foreach loop.
foreach (string txt in textLines) {
    names.Add(txt.Split(';')[0]); // only for List<T>!!
    dialogues.Add(txt.Split(';')[1]);
}

A: The error in your code is that you have written these:
// splits up the text file into the list of lines
textLines = textFile.text.Split('\n');
// iterates over the course of the list of lines, splitting up the names and dialogue, then sorting each into its respective list
for (int i = 0; i <= textLines.Length - 1; i++) {
    names.Add(textLines[i].Split(';')[0]);
    dialogue.Add(textLines[i].Split(';')[1]);
}

Inside the class instead of a method inside the class.

Coming to the actual problem, I think you should use a ScriptableObject in this case. They provide an Awake (Similar to Awake in MonoBehavior) method in which you can write the above code so that it gets executed when the game starts.
[CreateAssetMenu(fileName="Dialogue Asset", menuName="My Game/Dialogue Asset")]
public class Dialogue: ScriptableObject {
    // text file input
    public TextAsset textFile;
    // list containing each line of the text file
    protected string[] textLines;
    // lists containing names and dialogues (written in the file like so: Bob;I like pancakes)
    protected string[] names;
    protected string[] dialogues;

    void Awake() {
        textLines = textFile.text.Split('\n');
        for (int i = 0; i <= textLines.Length - 1; i++) {
            names.Add(textLines[i].Split(';')[0]);
            dialogue.Add(textLines[i].Split(';')[1]);
        }
    }
}

Now you can access the textLines and other things when the game is running. To create a new dialogue asset, you can go to Asset/My Game/Dialogue Asset from the menu bar in Unity and Edit them in the inspector. This is just a brief overview of ScriptableObject class. I suggest you watch Scriptable Objects - Brackey's to get the concept of scriptable objects better.


text:
Q: Let $X$ be a Banach space and $E$ a sublinear subspace . Show there exists a surjective isometry $\phi : E^* \rightarrow \overline{ E}^* $ Let $X$ be a Banach space and $E$ a sublinear  subspace of $X$ . Show there exists a surjective isometry $\phi : E^* \rightarrow \overline{ E}^* $
I think it could be a derived fact of the Godlstine lemma or something related to the weak topology but I am really lost at it . Could you please give some guidelines?

A: Define $$\phi: E ^* \to \overline{E}^*: f \mapsto (\phi_f: \overline{E} \to \Bbb{K}: e \mapsto \lim_n f(e_n))$$ where $e= \lim_n e_n$.
Note first that $\lim_n f(e_n)$ exists because $f$ is continuous. Next, we show that this is well-defined: if $e= \lim_n e_n = \lim_n e_n'$. Then $\lim_n (e_n-e_n') =0$ so $\lim_n (f(e_n)-f(e_n'))=0$. Hence $\lim_n f(e_n) = \lim_n f(e_n')$.
Check that $\phi$ satisfies the required properties.


text:
Q: Defaulting to a value when a object property is undefined I have an object (a return from a graphQl query), that I am iterating over in order to make the data structure simpler before using the data. There are some non-required field in the data model, and I would like to use the data when it's there, and default to undefined when it is not.
This is my current function:
const parseNovice = data => {
  return data.allContentfulNovica.edges.map(edge => {
    return {
      createdAt: edge.node.createdAt,
      id: edge.node.id,
      slika: edge.node.slika.file.url || undefined,
      tekst: edge.node.tekst.tekst || undefined,
      naslov: edge.node.naslov
    };
  });
};

The error I am getting is:

TypeError: Cannot read property 'file' of null

In other words the file for the image is missing, and therefore the file property is not defined. Is there a way for me to default to undefined regardless of which of the properties in the chain is missing?
Should I be using a try/catch for this?

A: Not in a clean native way.  You would need to do undefined checks the whole way down.  You should consider how lodash impliments _.get().  It wraps the logic for doing the undefined checks.  So you may want to consider using that or writing your own utility function if you find yourself doing these deep undefined checks often.
Otherwise you'll have to write something like this:

let edge;

let thing = {
  prop: edge !== undefined && edge.node !== undefined && edge.node.tekst !== undefined && edge.node.tekst.tekst !== undefined ? edge.node.tekst.tekst : undefined,
  prop2: _.get(edge, "node.tekst.tekst")
}

console.log(thing); // undefined

edge = {
  node: {
    tekst: {
      tekst: "foo"
    }
  }
};

thing = {
  prop: edge !== undefined && edge.node !== undefined && edge.node.tekst !== undefined && edge.node.tekst.tekst !== undefined ? edge.node.tekst.tekst : undefined,
  prop2: _.get(edge, "node.tekst.tekst")
}

console.log(thing); // foo
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>


text:
Q: Variables are null even after assigning a value to them (Java) I'm trying to write a method that will add song information (input by the user) to a database. Once the user adds the song details (name, artist, file size, duration), they should be saved in the first empty song slot (4 song slots total) and then taken back to the menu interface.
But when I try to add a second song, the first slot is always empty, as if the details the user inputs aren't saved. I've tried stepping through the debugger and as I enter the name, artist, etc they are all saved in the song1 object. But when I go back to enter a second song, the song1 object has the values:
name = null, artist = null, filesize = 0, duration = 0.
I've been at this for hours now and am really confused, any help would be amazing!
SongDatabase class:
public class SongDatabase {

Scanner console = new Scanner(System.in);

public void addNewSong() {

    Song song1 = new Song();
    Song song2 = new Song();
    Song song3 = new Song();
    Song song4 = new Song();

if (song1.isEmpty()) {
    System.out.println("Name of song:");
    song1.setName(console.next());

    System.out.println("Artist:");
    song1.setArtist(console.next());

    System.out.println("File size (MB):");
    song1.setFileSize(console.nextInt());

    System.out.println("Duration (seconds):");
    song1.setDuration(console.nextInt());
    System.out.println("Song successfully added.");
    System.out.println("");
}

else if (song2.isEmpty()) {
    System.out.println("Name of song:");
    song2.setName(console.next());

    System.out.println("Artist:");
    song2.setArtist(console.next());

    System.out.println("File size (MB):");
    song2.setFileSize(console.nextInt());

    System.out.println("Duration (seconds):");
    song2.setDuration(console.nextInt());
    System.out.println("Song successfully added.");
    System.out.println("");
}

else if (song3.isEmpty()) {
    System.out.println("Name of song:");
    song3.setName(console.next());

    System.out.println("Artist:");
    song3.setArtist(console.next());

    System.out.println("File size (MB):");
    song3.setFileSize(console.nextInt());

    System.out.println("Duration (seconds):");
    song3.setDuration(console.nextInt());
    System.out.println("Song successfully added.");
    System.out.println("");
}

else if (song4.isEmpty()) {
    System.out.println("Name of song:");
    song4.setName(console.next());

    System.out.println("Artist:");
    song4.setArtist(console.next());

    System.out.println("File size (MB):");
    song4.setFileSize(console.nextInt());

    System.out.println("Duration (seconds):");
    song4.setDuration(console.nextInt());
    System.out.println("Song successfully added.");
    System.out.println("");
}

else {
    System.out.println("The database is currently full. Please delete a song before adding a new one.");
}

Song class:
public class Song {

private String name, artist;
private int fileSize, duration;

public Song(String name, String artist, int fileSize, int duration) {
    name = "";
    artist = "";
    fileSize = 0;
    duration = 0;
}

public Song(){}

public boolean isEmpty() {
    if (this.name == null && this.artist == null && this.fileSize == 0 && this.duration == 0 ) return true;
    else return false;
}

public void setName(String inputName) {
    inputName = name;
}

public String getName() {
    return name;
}

public void setArtist(String inputArtist) {
    artist = inputArtist;
}

public String getArtist() {
    return artist;
}

public void setFileSize(int inputFileSize) {
    if (inputFileSize>0){
        fileSize = inputFileSize;
    }
}

public int getFileSize() {
    return fileSize;
}

public void setDuration(int inputDuration) {
    if (inputDuration>0) {
    duration = inputDuration;
    }
}

public int getDuration() {
    return duration;
}
}

A: Upon the entry of addNewSong() method you create four Song objects and store them in local variables. Local variables are lost when you exit the method, so everytime you enter addNewSong() you have four completely new songs. You probably need to store the songs in class fields and initialize them beforehard (similar to your console field). Just move these four lines out of addNewSong() method:
Song song1 = new Song();
Song song2 = new Song();
Song song3 = new Song();
Song song4 = new Song();

Also I would advise you to consider using array or List of songs. Your code will quickly become a mess when you add new functionality or increase number of songs.

A: You are initializing song1..4 every time you invoke the addNewSong() method. You need to externalize the initialization, possibly to a constructor.
By the way I would consider using ArrayList<Song> for a more flexible implementation

A: First of all you need to understand about local variables and scoping. Second if your slots are fixed better use an Array.
Song[] songs = new Songs[4];
for(int i=0;i<songs.length;i++){
   // Get input for song from user and use constructor
   songs[i] = new Song(name,artist,size,duration);
}

When you have constructor why do you need to set attributes individually? You should have used constructor itself.And if the slots are not fixed use an
ArrayList.
List<Song> songsList = new ArrayList<Song>();
// Get songs from user and add them to list.