text:
Q: ExpressJS Different Domain Name - CORS I am having a challange currently setting the domain for a cookie I am sending with the response from my expressjs implementation but currently it is only setting the IP address of where my expressjs server is at(the end point).
Here is my initial CORS configuration;
router.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:3000");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,
Content-Type, Accept, pwd, email");
next();
});

Here is my res.cookie line inside my authentication part;
 res.cookie('token', token, {domain: "localhost", expires: new
 Date(Date.now() + 600000*100000), httpOnly: true});

When I log in using chrome, very oddly I get the cookie but under the IP address of my expressjs endpoint, lets say "http://88.13.91.0" so when I refresh I lose it. I also dont see in the response for the expressjs api the "set-cookie" header in the response, but I do get the cookie. I have cleared the cookie to make sure its coming after attempting to log in so I know its not stale. I also have in my fetch call "credentials" set to "include" as documented but no luck.
My question is, am I not able to set the domain if its not the same as the endpoint? My thought is that maybe this is a security issue and as a result blocked because no one should be able to set a cookie for a domain that isn't theres, or maybe I am wrong.

A: Try CORS like this and
import * as cors from "cors";

// or
const cors = require ('cors');
    app.get("/", function (req, res) {
      res.setHeader("Content-Type", "application/x-www-form-urlencoded");
      res.setHeader("Access-Control-Allow-Origin", "*");
      res.setHeader(
        "Access-Control-Allow-Headers",
        "Origin, X-Requested-With, Content-Type, Accept"
      );

      res.setHeader("Access-Control-Allow-Credentials", true);

add this above all your middleware
app.use(cors());


text:
Q: Как реализовать ввод в EditText через Button, а не клавиатуру? Допустим в активити будет одна кнопка и неопределенное количество edittext. Когда мы нажимаем на edittext, клавиатура не появляется, но если мы нажмем на кнопку, то в edittext введется то, что мы определим в программе Java.
Как такое сделать?

A: Как вариант можно сделать глобальную переменную которая будет соответствовать текущему выбранному полю для ввода:
private EditText currentView;

у данного типа виджетов есть слушатель фокуса:
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        if (hasFocus) {
            ...
        } else {
            ...
        }
    }
});

вы можете сделать его общим для всех ваших виджетов поля ввода:
 private View.OnFocusChangeListener listener = (view, hasFocus) -> {
        if (hasFocus) {
            ...
        } else {
            ...
        }
    };

дальше в слушателе когда у вас есть фокус вы присваиваете currentView значение view:
if (hasFocus) {
currentView = (EditText) view;
} else {
...
}
и добавляете слушатель к каждому EditText которых у вас большое кол-во:
myEtxt1.setOnFocusChangeListener(listener);

ну и наконец у кнопки вы можете добавить ее включение/отключение:
myBtn.setEnabled(currentView != null);

и в слушателе нажатий устанавливаете текст в поле для ввода которое вы выбрали.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Hamiltonian eigenvalues in a transformed reference frame Under a time-dependent unitary transformation $V(t)$ of the state vectors $|{\psi}\rangle$
\begin{equation}
|\psi'(t)\rangle = V(t) |\psi(t)\rangle
\end{equation}
The Hamiltonian $H(t)$ has to transform as
\begin{equation}
 H' = V H V^{\dagger} - i \hbar V \dot{V}^{\dagger}
\end{equation}
to preserve the form of the Schrödinger equation. $H'$ is Hermitian, and as such can be diagonalized.
If the original Hamiltonian has instantaneous eigenvectors $\{|n(t)\rangle\}_n$ of eigenvalues $E_n(t)$ such that
\begin{equation}
H(t)|n(t)\rangle = E_n(t) |n(t)\rangle,
\end{equation}
can one also find eigenvector and eigenvalues of the transformed Hamiltonian $H'$ starting from those of $H$?
I know that, in particular cases, it is possible to do that. I am wondering if there is a scheme to do it in the general case.

A: If you know the time dependent eigenvectors and eigenvalues of your original Hamiltonian, at any given time you could try using ordinary perturbation theory on the Hamiltonian
$$V^\dagger H' V=  H  + i \hbar  {V}^{\dagger}\dot{V}$$
treating the first part as your free theory and the second part as a perturbation.
In general, since $V$ and $\dot{V}$ are arbitrary, I don't think you can do any better than this. If it's a finite Hilbert space with $N$ vectors your perturbation is an arbitrary generator of $U(N)$ which means it's an arbitrary Hermitian matrix, so the form of the perturbation is completely general.


text:
Q: Why can't I see "Login" button on User record I am trying to login to Salesforce as another user but I cannot see the "login" button usually found on the User record.
I am a System Administrator and have both the "Manage Users" and "Modify All Data" attribute setup on my profile.
The "Login Access Policies" only lists Salesforce.com Support
Am I missing something?

A: Enable Administrators Can Log in as Any User on "Login Access Policies"


text:
Q: Alexa (ASK) : How to play multiple audio from different URL? I'm a beginner at ASK development and currently stuck on playing audio from multiple different URLs using .addAudioPlayerPlayDirective from handlerInput.responseBuilder. So if I add multiple addAudioPlayerPlayDirective to the responseBuilder it returns error instead. For example :
handlerInput.responseBuilder
    .speak(speakOutput)
    .addAudioPlayerPlayDirective('REPLACE_ALL', podcastBeginning.url, podcastBeginning.token, 0, null, podcastBeginning.metadata)
    .addAudioPlayerPlayDirective('REPLACE_ALL', podcastBeginning.url, podcastBeginning.token, 0, null, podcastBeginning.metadata);

Also, I added the method of the issue below.
const LatestHeadlinesIntentHandler = {
    canHandle(handlerInput) {
        return handlerInput.requestEnvelope.request.type === 'LaunchRequest' ||
          handlerInput.requestEnvelope.request.type === 'IntentRequest' &&
            (
              handlerInput.requestEnvelope.request.intent.name === 'LatestHeadlinesIntent' ||
              handlerInput.requestEnvelope.request.intent.name === 'AMAZON.ResumeIntent' ||
              handlerInput.requestEnvelope.request.intent.name === 'AMAZON.LoopOnIntent' ||
              handlerInput.requestEnvelope.request.intent.name === 'AMAZON.NextIntent' ||
              handlerInput.requestEnvelope.request.intent.name === 'AMAZON.PreviousIntent' ||
              handlerInput.requestEnvelope.request.intent.name === 'AMAZON.RepeatIntent' ||
              handlerInput.requestEnvelope.request.intent.name === 'AMAZON.ShuffleOnIntent' ||
              handlerInput.requestEnvelope.request.intent.name === 'AMAZON.StartOverIntent'
          );
    },
    async handle(handlerInput) {
        const response = await httpGet();
        let responseBuilder = handlerInput.responseBuilder;
        let speakOutput;
        let podcastBeginning = audio[0];
        let podcastNext = audio[1];
        let podcastEnd = audio[2];
        let audioCount = 0;
        let podcast = {
            "token": response.audios[audioCount].intId,
            "url": response.audios[audioCount].url,
            "metadata" : {
              "title": response.audios[audioCount].title,
            }
          }

        if (sucessfulGet === true){
            speakOutput = 'Alright, reading you the latest headlines!';
            handlerInput.responseBuilder
                .speak(speakOutput)
                .addAudioPlayerPlayDirective('REPLACE_ALL', podcastBeginning.url, podcastBeginning.token, 0, null, podcastBeginning.metadata)

        }else {
            speakOutput = "No stories found. Response Code: " + responseCode;
        }

        return handlerInput.responseBuilder
            .getResponse();
    }
};

Any help would be appreciated. Thanks.

A: The AudioPlayer interface can help you achieve this functionality.  It provides directives and requests (i.e next, previous, pause) for streaming audio and monitoring playback progression. For more information :
https://developer.amazon.com/en-US/docs/alexa/custom-skills/audioplayer-interface-reference.html
Also there is a an Alexa skill sample (https://github.com/alexa-samples/skill-sample-nodejs-multistream-audio-player/blob/main/lambda/index.js) which handles multiple audio files.  The audio data is contained in an array found in /lambda/constants and imported into /lambda/index.js, which contains the logic to handle requests to manage the audio (play, pause, play next, etc) from your skill.
Please also note that each audio item URL must meet the following requirements listed here: https://developer.amazon.com/en-US/docs/alexa/custom-skills/audioplayer-interface-reference.html#audio-stream-requirements


text:
Q: Unable to use "chr" in python I have had errors previously in my code that I have sorted now, but now that I run my code a new error appears

string = (chr(addition))
  TypeError: an integer is required (got type str)

I do not know why this is appearing, and would appreciate it if anyone had a solution or an idea of how to fix this code.
The line that it has a problem with is string = (chr(addition))
The full code is posted below.
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFHIJKLMNOPQRSTUVWXYZ0123456789"
choice = input("Would you like to encrypt or decrypt? [e/d]: ")
string = ''
key1 = ''
message1 = ''
if choice == "e":
    message = input("Please insert the message you would like to use: ")
    keyword = input("Please insert the keyword you would like to use: ")
    for A in message:
        if message in alphabet:
            message1 = (ord(message)) - 96
        for A in keyword:
            if keyword in alphabet:
                key1 = (ord(keyword)) - 96
    addition = key1 + message1
    string = (chr(addition))
    print (string)

A: You initialize key1 and message1 to a string.
key1 = ''
message1 = ''

If these values are not overwritten, addition = key1 + message1 will be a string too, so chr(addition) gets a string as parameter, as the error message states. You can easily find these bugs by debugging
A hot fix could be initializing them to zero, for example:
key1 = 0
message1 = 0

A: Would this be more like what you are looking for?
Each time it encrypts a letter it cycles through one letter of the the keyword. Once it has exhausted all keyword letters it goes back to the beginning (last if statement). I did not add any values in the message1 nor to key1 values because you should be the one to decide what fits your encrypting criteria. Since Python 3 encodes to Unicode instead of ASCII you can pass the chr() function values above 255. However it is good to notice that you cannot go bellow 0, as it would have happened in your previous code when you were subtracting 96 twice (from the keyword letter and from the message letter). Going bellow 0 will make the interpreter spit out a ValueError which states exactally that.
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFHIJKLMNOPQRSTUVWXYZ0123456789"
choice = input("Would you like to encrypt or decrypt? [e/d]: ")

if choice == "e":

        message = input("Please insert the message you would like to use: ")
        keyword = input("Please insert the keyword you would like to use: ")
        ik = len(keyword)
        i = 0
        string = ''

        for A in message:

            message1 = (ord(A))
            key1 = (ord(keyword[i]))

            addition = message1 + key1
            string += (chr(addition))

            if i >= ik:
                i = 0
            else:
                i += 1

        print (string)

If you would like to decrypt your message all you have to do then is subtract the key value:
elif choice == "d":

        message = input("Please insert the message you would like to use: ")
        keyword = input("Please insert the keyword you would like to use: ")

        ik = len(keyword)
        i = 0
        string = ''

        for A in message:

            message1 = (ord(A))
            key1 = (ord(keyword[i]))

            addition = message1 - key1
            string += (chr(addition))

            if i >= ik:
                i = 0
            else:
                i += 1

        print (string)


text:
Q: Intutionistic Robinson Arithmetic By Friedman translation $HA$ and $PA$ prove the same $\Pi_2$ formulas.
Is it true for Intutionistic Robinson arithmetic(Robinson axioms with intutionistic logic) and classic Robinson arithmetic?
Axioms of $Q$ are:

*

*$\neg(Sx=0)$

*$Sx=Sy\rightarrow x=y$

*$y=0 \lor \exists x(Sx=y)$

*$x+0=x$

*$x+Sy=S(x+y)$

*$x\cdot 0=0$

*$x\cdot Sy=(x\cdot y)+x$

*$\neg(x<0)$

*$0=x\lor 0<x$

*$x<y \leftrightarrow (Sx<y \lor Sx=y)$

*$x<Sy \leftrightarrow (x<y\lor x=y)$

Q1. Is it true that for every $\Pi_2$ formula $\phi$, $Q\vdash_c \phi$ iff $Q\vdash_i \phi$?

Let $$Q^e=Q\cup \{x=y \lor\neg(x=y),\neg(x=y)\leftrightarrow (x<y \lor y<x) \}$$
What happens to Q1 if we replace $Q$ by $Q^e$?

Q2. Is it true that for every $\Pi_2$ formula $\phi$, $Q^e\vdash_c \phi$ iff $Q^e\vdash_i \phi$?

I think the second question can be proved by strong completeness of Beth model for intutionistic logic, but I'm not sure.
Thanks.
Edit:
Definition. The set $\Delta^+_0$ formula is the smallest set such that:

*

*$s=t\in \Delta^+_0$ for every term $s$ and $t$,

*$s<t\in \Delta^+_0$ for every term $s$ and $t$,

*if $\phi,\psi\in \Delta^+_0$, then $\phi\circ \psi\in\Delta^+_0$ where $\circ\in \{\lor,\land \}$,

*if $\phi\in \Delta^+_0$, then $\exists x(x<s \land \phi(x))\in \Delta^+_0$ where $s$ is a term.

*if $\phi\in \Delta^+_0$, then $\forall x(x<s \rightarrow \phi(x))\in \Delta^+_0$ where $s$ is a term.

By $\Pi_2$ formula $\phi$ I mean $\phi=\forall{\bf x}\exists{\bf y}\psi({\bf x},{\bf y})$ where $\psi\in \Delta^+_0$.

A: Both are false. Consider the following Kripke model $M\vDash Q^e$ (in fact, it satisfies the intuitionistic version of $\mathrm{PA}^-$): it consists of two worlds $u,v$ such that $u$ sees $v$; the first-order structure at $v$ is the semiring $M_v$ of polynomials $f\in\mathbb Z[x]$ with positive leading coefficient (and $0$), the structure at $u$ is the substructure $M_u\subseteq M_v$ consisting of polynomials whose linear coefficient is even. Putting
$$\phi(x)=\exists y<x\,(y+y=x),$$
we see that
$$M,u\nvDash\phi(a)\lor\neg\phi(a)$$
for the element $a:=2x\in M_u$, witnessing that intuitionistic $Q^e$ does not prove the $\Pi_2$ sentence
$$\forall x\,(\phi(x)\lor\neg\phi(x))$$
provable in any classical theory. Under the restrictive definition of $\Pi_2$ as given in the question, one can take the equivalent sentence
$$\forall x\,(\exists y<x\,(y+y=x)\lor\forall y<x\,(y+y<x\lor y+y>x))$$
instead.
More generally, if the classical extension of an intuitionistic theory $T\supseteq Q^e$ is $\Pi_2$-conservative over $T$, then $T$ must prove
$$\tag{$*$}\forall x\,(\phi(x)\lor\neg\phi(x))$$
for every $\Delta_0$ formula $\phi$ (exercise: the restrictions in the question are ultimately of no consequence). A higher-level argument that this shouldn't hold for $T=Q^e$ is that $Q^e$ is included in Cook and Urquhart's theory IPV (which, confusingly, is the intuitionistic version of $S^1_2$ rather than PV), thus by the witnessing theorem for IPV, it cannot prove $(*)$ unless $\phi(x)$  defines a poly-time predicate (and the theory proves this). Since $\Delta_0$ formulas define arbitrary predicates in the linear-time hierarchy, this cannot happen for all $\Delta_0$ formulas unless P = NP. The argument relativizes to subtheories of intuitionistic versions of $S^i_2$ for any $i$, using non-collapse of PH as an assumption in place of P $\ne$ NP.


text:
Q: Topology induced by lexicographical order is not discret
Let $\{0,1\}\times\mathbb{N}$ be equipped with the lexicographical order. Let $\tau_{LO}$ be the topology regarding the lexicographical order on $\{0,1\}\times\mathbb{N}$. Show that $\tau_{LO}$ is not discret.

To show that $\tau_{LO}$ is not discret it is enough to give $U\in\mathcal{P}(\{0,1\}\times\mathbb{N})$ with $U\notin\tau_{LO}$.
The lexicographical order $<$ is defined as follows:
$u=(u_1,u_2)<(v_1,v_2)=v\iff\begin{cases}u_1<v_1~\text{or}\\u_1=v_1~\text{and} ~u_2<v_2\end{cases}$
A base of the order topology is given by:
$\mathcal{O}=\{(u,v)|u,v\in X, u<v\}\cup\{(-\infty, u), (u,\infty)|u\in X\}\cup\{X\}$.
So there is a set, which can not be written as union of sets in $\mathcal{O}$.
Such a set is $\{(1,0)\}\in\mathcal{P}(\{0,1\}\times\mathbb{N})$.
So an interval $(u,v)$ with $u,v\in\{0,1\}\times\mathbb{N}$ which contains the tupel $(1,0)$ [not the interval] always has other elements and is never a singleton.
Suppose there are such $u,v$. Then $u<(1,0)<v$.
Hence $u_1<1$ or $u_1=1$ and $u_2<0$. Obviously the seconds case does not hold. So $u_1=0$.
The successor of $(1,0)$ is obviously $v=(1,1)$.
So we have $(0,u_2)<(1,0)<(1,1)$ and how ever you choose $u_2$ there will always be infinite many other tupel 'between' $(0,u_2)$ and $(1,0)$.
In other words: A set containing $(1,0)$ can never be open, because $(1,0)$ has no unique predecessor.
And of course this shows explicit that $\{(1,0)\}$ is not open. So $\tau_{LO}$ is not the discret topology.
Is this correct?
Thanks in advance.


text:
Q: How to prevent validation for an event handler of a user control? I have a user control with a delete button. When a button is clicked, an event fires which deletes a record from the database. Now, the control is placed in Default.aspx. The whole body markup of Default.aspx (including the user control with its button itself) resides in <form runat="server"> as required by ASP.NET. Everything works so far.
However, the problem is when I put some validation controls inside Default.aspx (meaning inside <form runat="server"> because otherwise the page will report server errors). When validation controls are added, the delete button in the user control stops working. Clicking on this button no longer triggers the event as before.
Now, I disabled event validation in Default.aspx using EnableEventValidation="false" directive. I am also including UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None; in the code behind file. However, none of this helps.
How do I fix this problem and make the button clickable?
Update:
I know for sure that the validation controls are causing the problem, because I only need to add EnableClientScript="False" to each of them, and the button becomes clickable. But I don't want to rewrite validation on the client side manually!

A: It turns out the PostBack cannot occur if the form is not IsValid regardless of what element causes it. As long as that element (button) is inside the form with runat="server"that is invalid, the posback will not happen.
A very simple workaround is to just make the Button in my user control bypass validation: CausesValidation="False" (thanks to this question).
Another solution and maybe a more efficient one, is to use ValidationGroup. This way, all TextBoxes together with the Submit Button will belong to one group, and those controls that do not belong to that group will NOT be validated. In fact, they might have their own ValidationGroup; this will avoid interference between different controls within one Web Form.


text:
Q: Is it possible to have a sound play before/during the splash screen? My app takes a few seconds to load and I have a splash screen.  Once  "viewDidLoad" I have a little sound play.  I feel that the sound would be in better use if it started playing when the splash screen popped up.  Is it possible to have a sound start before/during the splash screen?
Here is my code: (under viewDidLoad)
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: @"intorSound" ofType: @"aif"];
        NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
        player = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: nil];
        [player setVolume: soundVolumeValue];    // available range is 0.0 through 1.0
        [player play];

        [fileURL release];

Thank you for your time!

A: A little trick is to use the same splash screen as your Default.png, making a seamless transition into code you control.  When applicationDidLaunch gets called, start your sound playback, and display the splash screen.  If you want, you can put a little progress indicator up onto the splash screen as well.  In viewDidLoad, when you are done with all initialization, do a 2-5 second or so fade of the splashscreen.  You can throw in code to dismiss the splash screen with a tap, thus giving people some time to read the splash screen or tap it to dismiss it.  This all makes the amount of time that the Default.png is displayed with no sound seem insignificant.

A: You can display your own splash screen and load your app in the background.  This way, as soon as applicationDidLauch is done, you can display your own splash screen and sound, then load the rest while the user sees this.

A: I like the technique of leaving the splash screen up a little longer to play the sound, but beware you are messing with HIG guidelines which state "Avoid displaying an About window, a splash screen, or providing any other type of startup experience that prevents people from using your application immediately." (p. 45)
They also talk more about the startup image on p. 123 and stress it's NOT supposed to build your brand. However you see this all the time, and it is sometimes called the "most-often broken rule" - but beware there is a line you are dancing next to it.


text:
Q: need to create algorithm to sort and output a result You are given 7 numbers in the form of A, B, C, A+B, B+C, C+A, and A+B+C. You have to make a program in C++ that will be able to figure out the values of A, B, and C given those 7 numbers. Please help fast! I have already created an array to find the max and min of those seven numbers and now I'm stuck.
Here's what I have so far:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main()
{
     int arr[10], n=7, i, max, min;
     for (i = 0; i < n; i++)
          cin >> arr[i];
     max = arr[0];
     for (i = 0; i < n; i++)
     {
          if (max < arr[i])
               max = arr[i];
     }
     min = arr[0];
     for (i = 0; i < n; i++)
     {
          if (min > arr[i])
               min = arr[i];
     }
}

Sample input: 2 2 11 4 9 7 9
Output for that input: 2 2 7

A: Solution:
Answering to your question "need to create algorithm to sort and output a result", you can use a std::array and the std::sort function from the algorithm library.
However, even if you sort them the three lowest numbers are not guaranteed to be A, B and C as the array could be ordered as A, B, A+B, C, A+C, B+C and A+B+C. You will have to check whether the 3 number in the array is A+B.
Additional information:

*

*using namespace std; is considered a bad practice (More info here).

Full code:
#include <iostream>
#include <array>
#include <algorithm>

int main(){
    constexpr unsigned int n = 7;
    std::array<unsigned int, n> arr;
    for (unsigned int i = 0; i < n; i++)
        std::cin >> arr[i];
    std::sort(arr.begin(),arr.end());
    if(arr[2] == arr[0] + arr[1])
        std::cout << arr[0] << " " << arr[1] << " " << arr[3] << "\n";
    else
        std::cout << arr[0] << " " << arr[1] << " " << arr[2] << "\n";
}


text:
Q: Read a file in C++ from a specific Line and then store it in Vectors/Array I am new to C++ programming and I did my homework for reading a file. I am learning C++ from this cpp-tutorial: Basic-file-io site.
I have a file whose content looks like:
Input: /path/to/the/file/
Information :xxx
Type of File: Txt file
Extra Information Value = 4
Development = 55
NId      CommId
1        0
3        0
8        7
.   .
And so on...

This file has about 10000 Nodes and their corresponding CommID. The Node and CommId are seperated by TAb space in this file. I am reading this file as Input by using the following code:
ifstream commFile("CommTest.txt");
if (!commFile)
       {
         // Print an error and exit
    cerr << "Uh oh, CommunityTest File could not be opened for reading!" << endl;
                 exit(1);
             }
while(commFile)
{
    // read communityFile from the 6th Line
    string strLine;

    getline(commFile, strLine);
    cout << strLine << endl;

}

I have two questions:

*

*I want to start reading from Line 7 i.e 1 0 and so on.

*How can I start reading it from the line 7?

I checked lot of questions and came across that it is not possible to jump to line number if the lines of the txt files are of different length.
I wonder how to use seekg in which I need to count the bits before I can reach Line 7.
Please let me know, how to do it?

I want to get the Nodes and CommId in two seperate Integers. As soon as I have Node in an Integer, I want to search the Neighbour Nodes of this Node from a Graph file(This file is also provided as input and it has edges information). After getting the Neighbours of this Node, I want to store the collected Neighbours and their CommId (commId of every Node is available from the above file). I want to store them as pair in an Array/Vector.
For example:

After reading 1   0 from this file. I will take the Node 1 and will
  find the Neighbours of Node 1 from a Graph File. For every Neighbours
  of Node 1, I want to save the information as a pair. For example, if
  Node 1 has two Neighbours Node. i.e Node 63 and Node 55. If Node 63
  belong to commId 100 and Node 55 belongs to CommId 101, the pair
  should be:
[(63,100),(55,101)..] and so on.

The learning link, STackOverflow forum suggested me to use Vectors,Map, STructs for Graphs. I haven't used Vector/Maps,Structs anytime before in my life. I am aware of Array as I used it before.
Please suggest what would be the best way.
Thanks in advance. Every help would be greatly appreciated.

A: you can read text file from 7 no line by this:
for (int lineno = 0; getline (myfile,line) && lineno < 7; lineno++)
  if (lineno > 6)
      cout << line << endl;

after getting NId and CommId from #7 line, you can take it in stringstream. You can learn it from stringstream
std::stringstream ss;
ss << line;
int nId,CId;
ss >> nId >> CId;

Then can take 2D array and I think you must handle 2D array which if
array[row][column]

Every row define as NId and corresponding in a row you and store commId as a column value.
according to your Example: [(63,100),(55,101)..] and so on.
Here NId 63, 55 .....
So you can..
array[63][0] = 100
array[55][0] = 101
so on....

You can do it by a count and handle column value like 0,1,2.....

A:   int main(int argc, char **argv) {
    vector<int> nodes;
    map<int, vector<int> > m;
    ifstream commFile("file.txt");
    string strLine, node_string;
    int node;
    if (!commFile.is_open()) {
        cerr << "Uh oh, CommunityTest File could not be opened for reading!" << endl;
        return -1;
    }
    // Ignore the first lines of your file, deal with the empty lines
    for(int i = 0; i < 12 && std::getline(commFile,strLine); i++) {
        cout << "Line to ignore = " << strLine << endl;
    }

    while(getline(commFile,strLine)) {
        istringstream split(strLine);
        // split the string with your nodes
        while(getline(split, node_string, ' ')) {
            std::istringstream buffer(node_string);
            buffer >> node;
            // push it into a temporary vector
            nodes.push_back(node);
        }
        if(nodes.size() >= 2) {
            // add into your map
            m[nodes[0]].push_back(nodes[1]);
        }
    }
    return 0;
}


text:
Q: When and where to use switch statement instead of nested if-else statement? I have a question regarding structures in C++, I wrote the below code and I want to assign each student to a different course, I've been trying to make different assignments but couldn't figure out the correct way to do it.
This is my code:
#include <iostream>

using namespace std;

struct Course {
    string CourseCode;
    string CourseName;
    string LecturerName;
    int CourseNumber;
};

struct Student {
    string StudentID;
    string StudentName;
    string Nickname;
    Course info;
};

void menu(void) {
    cout << "=================================" << endl;
    cout << "              MENU              " << endl;
    cout << "=================================" << endl;
    cout << "     1- Add new course" << endl;
    cout << "     2- Display course offered" << endl;
    cout << "     3- Add new students" << endl;
    cout << "     4- Display student list" << endl;
    cout << "     5- Modify student name" << endl;
    cout << "     6- Display student's name after modification" << endl;
    cout << "     7- Exit Program" << endl;
    cout << "=================================" << endl << endl;
}

int main()
{
    Student* ptr[5];
    Student details[5];

    for (int i = 0; i < 2; i++) {
        ptr[i] = &details[i];
    }

    int m, option, stuNo, courNo, n;

    menu();
    cout << "Choose an option from the menu: ";
    cin >> option;

    while (option != 7)
    {
        if (option == 1) {
            cout << "\nHow many courses do you want to enter? [Maximum 2]: ";
            cin >> courNo;
            for (m = 0; m < courNo; m++) {
                cout << "\nEnter course " << m + 1 << " details: " << endl;
                cout << "Course Code: ";
                cin >> ptr[m]->info.CourseCode;
                cout << "Course Name: ";
                cin >> ptr[m]->info.CourseName;
                cout << "Lecturer Name: ";
                cin >> ptr[m]->info.LecturerName;
            }
        }

        else if (option == 2) {
            cout << "\nThe courses details you entered are:" << endl;
            for (m = 0; m < courNo; m++) {
                cout << "\nCourse " << m + 1 << ": " << endl;
                cout << "Course Code: " << ptr[m]->info.CourseCode << endl;
                cout << "Course Name: " << ptr[m]->info.CourseName << endl;
                cout << "Lecturer Name: " << ptr[m]->info.LecturerName << endl;
            }
        }

        else if (option == 3) {
            cout << "\nHow many students do you want to enter? [Maximum 5]: ";
            cin >> stuNo;

            for (m = 0, n=0; m < stuNo; m++, n++) {
                cout << "\nEnter student " << m + 1 << " details: " << endl;
                cout << "ID: ";
                cin >> ptr[m]->StudentID;
                cout << "Name: ";
                cin >> ptr[m]->StudentName;
                cout << "Nickname: ";
                cin >> ptr[m]->Nickname;
                cout << "Course number from the list: ";
                cin >> n; // This gives same output for both students
            }
        }

        else if (option == 4) {
            cout << "\nThe students details you entered are:" << endl;
            for (m = 0; m < stuNo; m++) {
                cout << "\nStudent " << m + 1 << ": " << endl;
                cout << "ID: " << ptr[m]->StudentID << endl;
                cout << "Name: " << ptr[m]->StudentName << endl;
                cout << "Nickname: " << ptr[m]->Nickname << endl;
                cout << "Course " << ptr[n-1]->info.CourseName<< endl;
            }
        }

        else if (option == 5) {
                cout << "\nEnter the student number that has been saved in option 1,2: ";
                cin >> n;
                cout << "\nEnter the new name: ";
                cin >> ptr[n-1]->StudentName;
        }

        else if (option == 6) {
            cout << "\nStudent "<< n <<" new name: ";
            cout << ptr[n - 1]->StudentName;
            cout << endl;
        }

        else
            cout << "Invalid number! Please re-enter a choice from the menu." << endl;

        cout << "=====================================================" << endl;
        cout << "\nChoose an option from the menu: ";
        cin >> option;
    }

    if (option == 7)
        cout << "End of program!" << endl;

}

I know the output of the courses assigned to the students will be the same based on my code since I have only n, how to change it to make it different for each student
This is the output:
=================================
              MENU
=================================
     1- Add new course
     2- Display course offered
     3- Add new students
     4- Display student list
     5- Modify student name
     6- Display student's name after modification
     7- Exit Program
=================================

Choose an option from the menu: 1

How many courses do you want to enter? [Maximum 2]: 2

Enter course 1 details:
Course Code: 111
Course Name: co1
Lecturer Name: lect1

Enter course 2 details:
Course Code: 222
Course Name: co2
Lecturer Name: lect2
=====================================================

Choose an option from the menu: 3

How many students do you want to enter? [Maximum 5]: 2

Enter student 1 details:
ID: 1111
Name: student1
Nickname: stud1
Course number from the list: 2

Enter student 2 details:
ID: 2222
Name: student2
Nickname: stud2
Course number from the list: 1
=====================================================

Choose an option from the menu: 4

The students details you entered are:

Student 1:
ID: 1111
Name: student1
Nickname: stud1
Course co2

Student 2:
ID: 2222
Name: student2
Nickname: stud2
Course co2
=====================================================

Choose an option from the menu: 7
End of program!

A: The problem is that you are storing the list of available Courses and Students in the same list.  You should have a separate list for Courses and Students, and then have the two lists cross-reference each other as needed.
For instance, change the Course info; member of Student to std::string CourseCode; instead, and then you can lookup the CourseCode in the Courses list when needed.
Try something more like this:
#include <iostream>
#include <string>
#include <limits>
using namespace std;

struct Course {
    string CourseCode;
    string CourseName;
    string LecturerName;
    int CourseNumber; // <-- what is this for???
};

struct Student {
    string StudentID;
    string StudentName;
    string Nickname;
    string CourseCode;
};

void menu() {
    cout << "=================================" << endl;
    cout << "              MENU              " << endl;
    cout << "=================================" << endl;
    cout << "     1- Add new course" << endl;
    cout << "     2- Display course offered" << endl;
    cout << "     3- Add new students" << endl;
    cout << "     4- Display student list" << endl;
    cout << "     5- Modify student name" << endl;
    cout << "     6- Display student's name after modification" << endl;
    cout << "     7- Exit Program" << endl;
    cout << "=================================" << endl << endl;
}

string getCourseName(const string &CourseCode, const Course *courses, int courNo) {
    for(int m = 0; m < courNo; ++m) {
        if (courses[m].CourseCode == CourseCode)
            return courses[m].CourseName;
    }
    return "";
}

int main()
{
    Student students[5];
    Course courses[2];

    int n, m, option, stuNo = 0, courNo = 0, modNo = 0;

    menu();

    do
    {
        cout << "Choose an option from the menu: ";
        cin >> option;

        switch (option) {
            case 1:
                if (courNo >= 2) {
                    cout << "\nCourse list is full";
                    break;
                }

                cout << "\nHow many courses do you want to enter? [Maximum " << 2 - courNo << "]: ";
                cin >> n;

                for (m = 0; m < n; ++m) {
                    cout << "\nEnter course " << m + 1 << " details: " << endl;
                    cout << "Course Code: ";
                    cin >> courses[courNo].CourseCode;
                    cout << "Course Name: ";
                    cin >> courses[courNo].CourseName;
                    cout << "Lecturer Name: ";
                    cin >> courses[courNo].LecturerName;
                    ++courNo;
                }

                break;

            case 2:
                cout << "\nThe courses details you entered are:" << endl;
                for (m = 0; m < courNo; ++m) {
                    cout << "\nCourse " << m + 1 << ": " << endl;
                    cout << "Course Code: " << courses[m].CourseCode << endl;
                    cout << "Course Name: " << courses[m].CourseName << endl;
                    cout << "Lecturer Name: " << courses[m].LecturerName << endl;
                }
                break;

            case 3:
                if (stuNo >= 5) {
                    cout << "\nStudent list is full";
                    break;
                }

                cout << "\nHow many students do you want to enter? [Maximum " << 5 - stuNo << "]: ";
                cin >> n;

                for (m = 0; m < n; ++m) {
                    cout << "\nEnter student " << m + 1 << " details: " << endl;
                    cout << "ID: ";
                    cin >> students[stuNo].StudentID;
                    cout << "Name: ";
                    cin >> students[stuNo].StudentName;
                    cout << "Nickname: ";
                    cin >> students[stuNo].Nickname;
                    cout << "Course number from the list: ";
                    cin >> students[stuNo].CourseCode;
                    ++stuNo;
                }

                break;

            case 4:
                cout << "\nThe students details you entered are:" << endl;
                for (m = 0; m < stuNo; ++m) {
                    cout << "\nStudent " << m + 1 << ": " << endl;
                    cout << "ID: " << students[m].StudentID << endl;
                    cout << "Name: " << students[m].StudentName << endl;
                    cout << "Nickname: " << students[m].Nickname << endl;
                    cout << "Course: " << students[m].CourseCode << " " <<  getCourseName(students[m].CourseCode, courses, courNo) << endl;
                }
                break;

            case 5:
                cout << "\nEnter the student number that has been saved in option 1,2: ";
                cin >> n;

                if (n < 1 || n > stuNo) {
                    cout << "\nInvalid student number";
                    break;
                }

                cout << "\nEnter the new name: ";
                cin >> students[n-1].StudentName;

                modNo = n;
                break;

            case 6:
                if (modNo < 1 || modNo > stuNo) {
                     cout << "\nNo student modified";
                     break;
                }

                cout << "\nStudent " << modNo << " new name: ";
                cout << students[modNo-1].StudentName << endl;
                modNo = 0;

                break;

            case 7:
                break;

            default:
                cout << "Invalid number! Please re-enter a choice from the menu." << endl;
                break;
        }

        cout << "=====================================================" << endl;
    }
    while (option != 7);

    cout << "End of program!" << endl;
}


text:
Q: Fail to randomize java string array I want to randomize or shuffle the order of the string array using the code below
public static void main(String[] args) {
        String str[]= {"Vxds", "Cvda", "Xcgi", "Atdr", "Mbeds", "0bda"};
        String strTmp[]=str;

        ArrayList<Integer> list = new ArrayList<Integer>();
        for (int i=0; i<str.length; i++) {
            list.add(new Integer(i));
        }

        Collections.shuffle(list);

        for (int i=0; i<str.length; i++) {
            strTmp[i]=str[list.get(i)];
            System.out.println(strTmp[i]);
        }
    }

The reason I do it like this instead of print it out directly is because I want to make it into a function later on. That's why I passed it to strTmp[] as that is what I want the function to return. But, the code just didn't function as I expected. It prints out several same value. How can I do it the right way? Thanks for the answer...

A: You almost had it, but you are referencing the same array twice and swap the contents of it. Change this line
 String strTmp[] = str;

to
 String strTmp[] = new String[str.length];

A: When you do String strTmp[]=str;, both str and strTmp are references to the same array. So when putting elements in, you are overwriting old elements including those have not yet been moved.
You may just do
    String str[]= {"Vxds", "Cvda", "Xcgi", "Atdr", "Mbeds", "0bda"};
    Collections.shuffle(Arrays.asList(str));

This works because Arrays.asList() does not create a new list, it merely provides a list view on the array. Any changes to the list change the array. Including shuffling it. Edit: This works for an array of strings and an array of any other reference type. As WJS points out, this will not work for an array of primitives (e.g., int[]) since Arrays.asList(arrayOfPrimitives) will create a list view of a newly created array of one elemeent, the primitive array.
If you require a new array with the shuffled strings and the old array unmodified, the solution is:
    List<String> list = new ArrayList<>(Arrays.asList(str));
    Collections.shuffle(list);
    String[] newStr = list.toArray(new String[0]);

    System.out.println("Original array:     " + Arrays.toString(str));
    System.out.println("New shuffled array: " + Arrays.toString(newStr));

Edit: Output from one example run:

Original array:     [Vxds, Cvda, Xcgi, Atdr, Mbeds, 0bda]
New shuffled array: [0bda, Cvda, Mbeds, Vxds, Xcgi, Atdr]

As you can see, the original array is unmodified.
Edit: Since Java 11 it's nicer to create the new array using Collection.toArray(IntFunction<String[]>):
    String[] newStr = list.toArray(String[]::new);

See both code snippets run live in IdeOne.

A: If you don't want to change the array str.  Try this.
String str[] = {"Vxds", "Cvda", "Xcgi", "Atdr", "Mbeds", "0bda"};
String strTmp[] = str.clone();
Collections.shuffle(Arrays.asList(strTmp));
System.out.println(Arrays.toString(strTmp));

output
[Xcgi, Cvda, Atdr, Mbeds, 0bda, Vxds]

A: I understand that you want to randomized your array in every execute. Here is the code for this.
import java.util.*;

 public static void main(String[] args) {
        String str[]= {"Vxds", "Cvda", "Xcgi", "Atdr", "Mbeds", "0bda"};
        List<String> list =Arrays.asList(str);
        Collections.shuffle(list);
        System.out.println(list);
     }


text:
Q: Converting string formula to mathematical formula in c# Hai all,
I am doing c#.NET application  to calculate different formulas and give result to user,users can enter any formula and each formula values are stored in database like this.

After saving like this i want to calculate the result.When calculating the result,application ask values for variables.But how can i calculate with this values.
Please help to retrieve each values from database and calculate the result.

A: You can use Shunting-yard algorithm to convert the expression to postfix notation or to ast directly. See this answer for nice explanation: Equation (expression) parser with precedence


text:
Q: Profile of users without QAs and with at least one rarest badge I've noticed a bug using Google Chrome on an Android 7.0. The normal user profile Rarest badge section should look like this

When going to the profile of a new user that has no QAs and at least one rarest badge, then the rarest badge section has wrong format (more to the right side of the page) as you can see in the following image

This happens across networks, that's why I'm sharing it here.
A way to reproduce using SO in the Android's browser: Click in Users > New Users > Creation Date. Then there you can see which users have at least one badge and click there. It can happen the badge isn't rare, so then nothing shows up. But if the badge is rare, you'll see that behavior.
Some of the users (to note the bahavior might change from the moment the users add one question or answer)
. https://pm.stackexchange.com/users/38908/user1898829
. https://pm.stackexchange.com/users/38901/marcus-edwards
. https://meta.stackexchange.com/users/716568/sree-vishnu
. https://meta.stackexchange.com/users/716536/faakhir


text:
Q: ASP.NET MVC table row including link on text from model I'm trying to display a table from a model. But the problem is that my model class has a string that already includes an  tag.
My view is:
@model MyWeb.Models.Incidente
@{
    Layout = null;
    ViewBag.Title = "Communication for " + Model.num.ToString();
}

@ViewBag.Title

         User
         Date
         Time
         Message

    @foreach (MyWeb.Models.Comunication item in Model.GetComunications())
    {

             @Html.DisplayFor(modelItem => item.user)
             @Html.DisplayFor(modelItem => item.date)
             @Html.DisplayFor(modelItem => item.time)
             @Html.DisplayFor(modelItem => item.message)

    }

The problem is that one item in GetComunications() has a message that include a link to Google:
You can Google it, just press Here!. Thank you!

So when the table is displayed the message shows the tag instead of creating the link in "Here!".
How can I solve this problem, and show a message that already has a link on the string?

A: If you are sure about the sanitation of your output, you can use Html.Raw:
@Html.Raw(Html.DisplayFor(modelItem => item.message))


text:
Q: Error relation does not exist SQL WITH on POSTGRESQL I get ERROR: relation "case_avg" does not exist in my sql request
    with case_avg AS
                (select
                               avg(vv.total_vcpu) as avgvcpu,
                               avg(vv.total_vram) as avgvram,
                               avg(vv.total_hdd) as avghdd,
                               pod,
                               report_date
                from common.vmware_vm vv
                group by pod,report_date)

select
    (ca.avgvcpu-v.total_vcpu) as vcpu,
    (ca.avgvram-v.total_vram) as vram,
    (ca.avghdd-v.total_hdd) as hdd,
    Concat(lower(v.vdc),lower(v.org)) as org_vdc
from
    common.vmware_vm v
inner join case_avg  ca on
    ca.pod = v.pod and ca.report_date = v.report_date
group by org_vdc

How i can resolve this?


text:
Q: pass data from app.js to components in ReactJs I have defined the customerid in my App.js as follows:
const customerid=this.state.userid;

I want to pass this customerid value into my customer component.
I call customerid as follows in customer component.
const result = await axios.get("https://localhost:44357/api/Orders/CustomerId/${customerid}");

How can I passe cutomerid from app.js to customer.js?
Can some genius help me with this?

A: To pass data from a parent component (app in this case) to a child component (customer in this case) just use props and access it in the child component.
<Child customerid={this.state.userid} />

A: While passing the data to the child component, which in this case is Customer, you just need to pass it as props when calling the Customer component.
<Customer customerid={this.state.userid}/>


text:
Q: grep positive/negative integer value only I am looking to grep any positive/negative integers only and no decimals, or any other variation including a number.
I have a testpart1.txt which has:
This is a test for Part 1
Lets write -1324
Amount: $42.27
Numbers:
       -345,64
067

Phone numbers:

       (111)222-2424

This should output the following code:
This is a test for Part 1
Lets write -1324
067

I am new to bash and I cannot find how to exclude any number separated with a character like a '.' or ','. I am able to get all the numbers with the following code but I am stuck after that:
egrep '[0-9]' testpart1.txt

This gives me the opposite of what I want:
grep '[0-9]\.[0-9]' testpart1.txt

A: You may use this grep:
grep -E '(^|[[:blank:]])[+-]?[0-9]+([[:blank:]]|$)' file

This is a test for Part 1
Lets write -1324
067

Details:

*

*-E: Enables extended regex matching

*(^|[[:blank:]]): Match line start or a space or a tab character

*[+-]?: Match optional + or -

*[0-9]+: Match 1 or more digits

*([[:blank:]]|$): Match line end or a space or a tab character


text:
Q: Get old text from change event? Can I somehow find out what was the change in the textfield? I would want to compare the old text with the new text ... the problem is, that I have multiple textAreas in a tab-editor, and all the textAreas are watched by one eventListener. I want to get a value calculated by the next formula:
globalChangeCount += thisTextArea.currentCharacterCount - thisTextArea.oldtCharacterCount
where the globalChangeCount is a value modified by all changes in any of the textAreas.
I am searching for these values through the event variable, but can't seam to find the old text of the textArea.

A: This may or may not be what you're looking to do:
package
{
    import mx.controls.TextArea;

    public class CountingTextArea extends TextArea
    {

        public var staleText : String = "";

        [Bindable("textChanged")]
        [NonCommittingChangeEvent("change")]
        public function get charDiff() : int
        {
            var diff : int = staleText.length - text.length;
            staleText = text;
            return diff;
        }

        public function CountingTextArea()
        {
            super();
        }
    }
}

I made it so that you can use it as a source for binding. Instead of subscribing to the event on each TextArea, you can use:
function addWatchers():void
{
    ChangeWatcher.watch(countingTextArea1, ["charDiff"], charDiffChangeHandler );
    ...
    ChangeWatcher.watch(countingTextArea5, ["charDiff"], charDiffChangeHandler );
}

With the event handler somewhere too:
function charDiffChangeHandler( event : PropertyChangeEvent ) : void
{
    trace(event.currentTarget.charDiff);
    // or
    trace(event.newValue);
}

A: You can use event.currentTarget to get a reference to the TextArea that fired the event, and use the focusIn event to execute a function to populate a variable with the old text value.

A: Maybe you should just subclass the TextArea and create an oldText field variable you update internally after all the external listeners have been notified.


text:
Q: how to insert data into a table that has a foreign key? I have 2 tables :
                 usine
======================================
id_usine | nom_usine | referance_usine

and for every usine we have ligneproduction so I have an other table :
  ligneproduction
===================
id | nom | fkUsine

I added an item in table using this:
INSERT INTO `USINE` (`id_usine`, `nom_usine`, `referance_usine`)
             VALUES ('3', 'LAFARGE BISKRA', 'LAFARGE_BISKRA');

I want to add a "ligne production" in ligneproduction table corresponding to that item in usine table.
How can I do that?

A: Use this ...set last inserted id and insert into child table and make ligneproduction's id is auto incremented
INSERT INTO `USINE` (`id_usine`, `nom_usine`, `referance_usine`)
                 VALUES ('3', 'LAFARGE BISKRA', 'LAFARGE_BISKRA');

    SET @id_usine = (SELECT LAST_INSERT_ID());

    INSERT INTO `ligneproduction` (`nom`, `fkUsine`)
                 VALUES ('any value depends on u', @id_usine);


text:
Q: What does "rather" mean in "rather Jimmy Olsen-ish"? Jimmy Olsenish means "similar to Jimmy Olsen":

He is a nice enough boy - rather Jimmy Olsen-ish I thought.
She has an unreal figure, rather Barbie-ish in its proportions!

When you say, for instance, he is similar to Jimmy Olsen (in appearance, behaviour and character) you would say Jimmy Olsen-ish.
However, I can not understand the grammar points and meaning of the word rather here.  Could you explain in detail?

A: Consider the word "childish". When we say it's a childish behavior we mean that it's a childlike behavior or the behavior is similar to a child. So in both the following sentences you are right about the meaning of Name + "-ish" construction

He is a nice enough boy - rather Jimmy Olsen-ish I thought. (Olsen-ish = Olsen like or similar to Olsen)
She has an unreal figure, rather Barbie-ish in its proportions! (Barbie like or similar to Barbie)

Here is a usage note from dictionary -

-ish

*

*(a suffix) used to form adjectives from nouns, with the sense of "belonging to" ( British; Danish; English; Spanish  ); "after the
  manner of," "having the characteristics of," "like" ( babyish;
  girlish; mulish  ); "addicted to," "inclined or tending to" ( bookish;
  freakish  ); "near or about" ( fiftyish; sevenish  ).

*(a suffix) used to form adjectives from other adjectives, with the sense of "somewhat," "rather" ( oldish; reddish; sweetish  ).

Now come to the usage of "rather" in this context -
Rather - [AS SUBMODIFIER] To a certain or significant extent or degree:
Example -

*

*She's been behaving rather strangely.

*He's rather an unpleasant man.

Now I am going to write the meaning of your sentences -

He is a nice enough boy - rather Jimmy Olsen-ish I thought. = He is a nice enough boy - almost like Olsen.
She has an unreal figure, rather Barbie-ish in its proportions! = She has an unreal figure, almost like Barbie in its proportions!

Hope it helps.

A: Rather has the same meaning as 'quite' or 'somewhat' in this context.

A: The following quote about rather is from WordNet:

• on the contrary; "rather than disappoint the children, he did two quick tricks before he left"; "he didnt call; rather (or instead), he wrote her a letter"; "used English terms instead of Latin ones"
• to some (great or small) extent; "it was rather cold"; "the party was rather nice"; "the knife is rather dull"; "I rather regret that I cannot attend"; "Hes rather good at playing the cello"; "he is kind of shy"
• more readily or willingly; "clean it well, preferably with warm water"; "Id rather be in Philadelphia"; "Id sooner die than give up"
• to a degree (not used with a negative) "quite tasty"; "quite soon"; "quite ill"; "quite rich"


text:
Q: Determining maximum usable memory android app I have an arraylist of byte array ( Arraylist<byte[]>). I am trying to read maximum amount of bytes from a file into memory.What's the best way to do it. How can i know the maximum available memory to be used.
I intend to avoid any outofmemory exceptions and lags


text:
Q: import all projects from svn repository folder I have that problem:
I checkout folder (myFolder for example) using tortoise svn.
import->existing projects into workspace

after it eclipse found a lot of projects(about 50) from different locations of myFolder.
BUT
eclipse doesn't understand that these projects from svn(no svn menu if make right click on any file and select team submenu)
I attempt to import-> team project set but after it in eclipse I see myfolder only. it is just folder - not projects. I cannot to compile it and use other features.
I think you are understand my problem.
Can you help me?

A: If you have already checkout your projects, import them in eclipse then follow below steps.
Right click on your project go to Team --> Share Project --> Select Repository type. Do next fill in required information and it should work.

A: Make sure you have installed a subversion plugin for eclipse which is is compatible with the version you have for tortoise, i.e the eclipse plugin you actually have - if any - is able to read the .svn meta data which was created by the tortoise client. This can happen for example if eclipse plugin is 1.6 and tortoise client is 1.7 or above.
When eclipse shows the ~50 projects deselect all and select only the one(s) you want to import, when passed a folder for importing an existing project, eclipse searches recursively for all folders containing a .project file and displays them as projects to be imported. Make a refresh (F5).
EDIT
From http://tortoisesvn.net/tsvn_1.8_releasenotes.html#compatibility

Local Client Compatibility
Subversion working copies are sometimes accessed using several different clients, e.g. TortoiseSVN, AnkhSVN, and the svn command line client. Because the working copy format has changed with this release, 1.8 clients cannot access an earlier working copy without first upgrading it. Pre-1.8 clients cannot access 1.8 working copies at all and there is no downgrade option

Please upgrade your eclipse svn-kit to the latest version, use this update site.


text:
Q: Scikit Learn GridSearchCV without cross validation (unsupervised learning) Is it possible to use GridSearchCV without cross validation? I am trying to optimize the number of clusters in KMeans clustering via grid search, and thus I don't need or want cross validation.
The documentation is also confusing me because under the fit() method, it has an option for unsupervised learning (says to use None for unsupervised learning). But if you want to do unsupervised learning, you need to do it without cross validation and there appears to be no option to get rid of cross validation.

A: I'm going to answer your question since it seems like it has been unanswered still. Using the parallelism method with the for loop, you can use the multiprocessing module.
from multiprocessing.dummy import Pool
from sklearn.cluster import KMeans
import functools

kmeans = KMeans()

# define your custom function for passing into each thread
def find_cluster(n_clusters, kmeans, X):
    from sklearn.metrics import silhouette_score  # you want to import in the scorer in your function

    kmeans.set_params(n_clusters=n_clusters)  # set n_cluster
    labels = kmeans.fit_predict(X)  # fit & predict
    score = silhouette_score(X, labels)  # get the score

    return score

# Now's the parallel implementation
clusters = [3, 4, 5]
pool = Pool()
results = pool.map(functools.partial(find_cluster, kmeans=kmeans, X=X), clusters)
pool.close()
pool.join()

# print the results
print(results)  # will print a list of scores that corresponds to the clusters list

A: I think that using cv=ShuffleSplit(test_size=0.20, n_splits=1) with n_splits=1 is a better solution like this post suggested

A: I recently came out with the following custom cross-validator, based on this answer. I passed it to GridSearchCV and it properly disabled the cross-validation for me:
import numpy as np

class DisabledCV:
    def __init__(self):
        self.n_splits = 1

    def split(self, X, y, groups=None):
        yield (np.arange(len(X)), np.arange(len(y)))

    def get_n_splits(self, X, y, groups=None):
        return self.n_splits

I hope it can help.

A: After much searching, I was able to find this thread. It appears that you can get rid of cross validation in GridSearchCV if you use:
cv=[(slice(None), slice(None))]
I have tested this against my own coded version of grid search without cross validation and I get the same results from both methods. I am posting this answer to my own question in case others have the same issue.
Edit: to answer jjrr's question in the comments, here is an example use case:
from sklearn.metrics import silhouette_score as sc

def cv_silhouette_scorer(estimator, X):
    estimator.fit(X)
    cluster_labels = estimator.labels_
    num_labels = len(set(cluster_labels))
    num_samples = len(X.index)
    if num_labels == 1 or num_labels == num_samples:
        return -1
    else:
        return sc(X, cluster_labels)

cv = [(slice(None), slice(None))]
gs = GridSearchCV(estimator=sklearn.cluster.MeanShift(), param_grid=param_dict,
                  scoring=cv_silhouette_scorer, cv=cv, n_jobs=-1)
gs.fit(df[cols_of_interest])


text:
Q: "ruby script.rb" versus "xterm -e ruby script.rb" I've run into a strange problem with Ruby that I can't explain.  I have the following script that grabs whatever code is currently in the clipboard, runs it through a syntax highlighter, then puts the new version BACK into the clipboard:
#!/usr/bin/ruby1.9.1

require 'coderay'

language = "auto";
if(ARGV.length > 0)
    language = ARGV[0];
end

print("Using language: #{language} \n");

codeToHighlight = `xsel --clipboard`

highlightedCode = CodeRay.scan(codeToHighlight, language.intern()).div

IO.popen("xsel --clipboard", mode='w') do |io|
  io.write highlightedCode
  io.flush
end

The odd part is that if I run it directly within a terminal, it works fine.  If I run it via "xterm -e", however, it doesn't work.  I found this thread on another site that asked the same question, but the person never got an answer: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/138423
That person found that if they added a pause at the end of the script like so...
10000.times do
   puts ""
end

...it works.  Why is this?  Is there a way to fix this?  I tried rewriting the script so that the popen returns an IO object and I could manually call close, but that doesn't make a difference.

A: How about if you execute it with gnome-terminal -e instead of xterm -e?
UPDATE:
OK, here is my best guess.  You know how if you send a terminal program to the background (either with & after the command or with ctl-z) and then you close the terminal it kills the program, right?  Well, xsel forks a child process to write to the clipboard, but it must be getting killed when the ruby wrapper script finishes and and xterm closes.
That would explain why the pause at the end allows it to work - it just gives enough time for the child process to finish before the terminal quits.  It also explains why it works when run manually - you leave the terminal open long enough for the child process to finish.
Try adding the -n option to your xsel command, and I bet it works.  -n keeps xsel from forking.


text:
Q: GWT CellTable Input Validation I would like to implement something similar to the Cell Validation showcase example, which can be found here
http://gwt.googleusercontent.com/samples/Showcase/Showcase.html#!CwCellValidation
After looking through the code and trying to implement it, there seems to be a class/variable deffinition missing for template. which shows up in the code in 2 places
public ValidatableInputCell(String errorMessage) {
  super("change");
  if (template == null) {
    template = GWT.create(Template.class);
  }
  this.errorMessage = SimpleHtmlSanitizer.sanitizeHtml(errorMessage);
}

SafeStyles safeColor = SafeStylesUtils.fromTrustedString("color: " + color + ";");
sb.append(template.input(pendingValue != null ? pendingValue : value, safeColor));

if (invalid) {
  sb.appendHtmlConstant(" ");
  sb.append(errorMessage);
  sb.appendHtmlConstant("");
}

After searching the web i found a few examples of what the template variable definition should be and came up with
interface Template extends SafeHtmlTemplates {
  @Template("<input type=\"text\" value=\"{0}\" tabindex=\"-1\" size=\"{1}\"></input>")
  SafeHtml input(String value, SafeHtml safeStyles);
}
private Template template;

with the above code added in there are no compiler warning howver when the code is executed i get this error

SafeStyles used in a non-CSS attribute context. Did you mean to use java.lang.String or SafeHtml instead?

Any ideas of how to fix this problem?

A: The template definition you are looking for, misses the @ShowcaseSource annotation, hence you do not see it in the source tab of the validation sample.
Anyway, here is the original code. And the template is:
interface Template extends SafeHtmlTemplates {
  @Template("<input type=\"text\" value=\"{0}\" style=\"{1}\" tabindex=\"-1\"/>")
  SafeHtml input(String value, SafeStyles color);
}

The error you see is because you are using a SafeStyle element (referenced by {1}) as a value of the size attribute (instead of style).


text:
Q: Generating functions and the Riemann Zeta Function The generating function for the terms of the harmonic series:
$\frac{1}{n}$
is $-\ln(1 - x)$.
Does an ordinary generating function exist for the terms of the zeta function $\zeta(s) = \sum_{n=1}^\infty \frac{1}{n^s}$
for any $ s > 1$?
That is, does there exist any function $f(x)$ that can be expressed in terms of elementary functions such that $f(x) = \sum_{n=1}^\infty \frac{1}{n^s}x^n$ for some $s > 1$?
I'm assuming that such a function in fact does not exist.  Can this be proven to be the case?

A: The function you are looking for is the Li$_s(z)$, the polylogarithm.

A: This is an answer to the initial question (asking for a generating function of $\zeta(s)$) :

*

*$−\ln(1−x)$ is the generating function of $\ \frac 1n$.

*$-\frac{\ln(1−x)}{1-x}$ is the generating function of the harmonic number $\ H_n=\sum_{k=1}^n\frac 1k$
The generating function of the generalized harmonic number $\ H_{n,s}:=\sum_{k=1}^n\frac 1{k^s}\ $ is given by :
$$\frac{\operatorname{Li}_s(x)}{1-x}$$
with $\operatorname{Li}_s$ the polylogarithm.
Should you simply want $\ \displaystyle\sum_{n=1}^\infty \frac{x^n}{n^s}=\operatorname{Li}_s(x)\ $ then dot dot's answer is right of course !
Note that a generating function for $\zeta(n)$ is known as the digamma function :
$$\psi(1+x)=-\gamma-\sum_{n=1}^\infty \zeta(n+1)\;(-x)^n$$
while the reflection formula allows to get the even values of $\zeta$ directly as :
$$\pi\;x\;\cot(\pi\;x)=-2\sum_{n=0}^\infty \zeta(2n)\;x^{2n}$$
A generating function for the polylogarithm was obtained too :
$$z\,\Phi(z, 1, 1-x)=\sum_{n=0}^\infty\;\operatorname{Li}_{n+1}(z)\;x^n$$
using the Lerch zeta function $\displaystyle\;\Phi(z, s, \alpha) := \sum_{k=0}^\infty \frac { z^k} {(k+\alpha)^s}$.


text:
Q: Graphing parametric complex equations I am given a group of functions that represent a decaying circle and I am trying to graph them so to better visualize them.
One of the equations I have is
z(t) = 2 * e^(-a*t) * e^(j*2*pi*0.5*t + (pi / 2))
for t from 0 to 4 and a = ln(3)

From this I know the following
Amplitude = 2
Decay = 1/3
Phase Shift = pi / 2 (90 degrees)
Frequency = 0.5
Period = 2

When I graph it I use parametric mode on my calculator (TI-84) and enter the following
X1T = 2e^(ln(3)*T) * (cos(2*pi*0.5*T) + cos(pi/2))
Y1T = 2e^(ln(3)*T) * (sin(2*pi*0.5*T) + sin(pi/2))

However I do not believe this is correct as the graph does not look like a normal circle that is decaying. Is this the correct graph and I am just misguided on what it should look like or did I misunderstand how to graph it?
WolframAlpha plot of it as http://bit.ly/1g2Lql9

A: I hope the following plot helps you. I made it by Maple environment using below codes:
[> with(plots):
   a := ln(3);
   complexplot(2*exp(-a*t)*exp((1/2)*(2*I)*Pi*t+(1/2)*Pi), t = 0 .. 4);


text:
Q: Angular application not loading images in hosted apache server I have an angular application and I run the ng build --prod command and deployed the files in the dist folder to the apache server /www/html/mywebsite folder in a ubuntu VM in DigitalOcean.
After the build of the angular application, the images called inside CSS files have come to the front directory even though originally they are in the assets directory as shown in the below screenshot.
Those images are showing fine without any issue in the website, but all the images called inside the HTML files are not displaying on the website. I don't think there is a permission issue to the assets folder because the javascript files inside the assets folder are loading without any issue. Here I have attached a screenshot of the permission of the files inside the assets folder.
Can you please help me to solve this?

A: Since you are setting up base href value in your index.html file like this:
<base href="/sedsslweb/sedssl/">

in your template you will need to access images without a leading slash, like this, so that they will form correct path:
<img class="rounded-circle mx-auto" src="assets/images/Projects/serendib.png">

I just checked in dev tool by editing images path without leading slash, and could see the images loading fine.


text:
Q: Bounded Set for Rational Number $$A = \{x \in \Bbb Q: x^2 < 11\}$$
I am looking for the upper and lower bounds of set $A$. I know they should be the greatest and the smallest rational number within $(- \sqrt{11}, \sqrt{11})$
So the difficulty is how to get those rational numbers in exact value.
Thanks

A: As you correctly noted, $A = (-\sqrt{11}, \sqrt{11}) \cap \mathbb Q$. However $\pm\sqrt{11}\notin \mathbb Q$ and $\mathbb Q$ is dense in $\mathbb R$. Therefor $A$ is dense in $(-\sqrt{11}, \sqrt{11})$ and we can find a sequence in $A$ converging to any of $\pm\sqrt{11}$. This proves that no upper or lower bound exists in the set (i.e. $\min A$ and $\max A$ are undefined). However, $\sup A$ and $\inf A$ are defined and are least upper and greatest lower bounds for $A$. Since we already have a convergent sequence to $\pm\sqrt{11}$ and both are bounds on $A$, we can see that
$$\sup A = \sqrt{11}\\
\inf A = -\sqrt{11}$$


text:
Q: Can apache DocumentRoot change perl @INC? I noticed that if I change DocumentRoot in my VirtualHost apache2 configuration perl @INC is also changed from
/opt/perl/lib/perl5/site_perl/5.28.0/x86_64-linux
/opt/perl/lib/perl5/site_perl/5.28.0
/opt/perl/lib/perl5/5.28.0/x86_64-linux
/opt/perl/lib/perl5/5.28.0

to
/var/www_local/WWWHub
/var/www_local/WWWHub/work
/etc/perl
/usr/local/lib/x86_64-linux-gnu/perl/5.22.1/
/Usr/local/share/perl/5.22.1
/usr/lib/x86_64-linux-gnu/perl5/5.22
/usr/share/perl5
/usr/lib/x86_64-linux-gnu/perl/5.22
/usr/share/perl/5.22
/usr/local/lib/site_perl
/usr/lib/x86_64-linux-gnu/perl-base

So if CGI script has CPAN module dependencies it wouldn't run correctly.
Why it could happen ?

A: You appear to have two different problems.
You are using your build of Perl 5.28.0 when you want to use your build of Perl 5.22.1.
To fix this, adjust the shebang (#!) line of the script to reference the correct build of Perl.
For example, you might be using
#!/opt/perl/bin/perl

and what you might want to be using is
#!/usr/bin/perl

You wish to locate modules installed in a position relative to the script.
The script should use use lib and a path relative to $RealBin for that.
use FindBin qw( $RealBin );
use lib $RealBin, "$RealBin/work";

(I'm assuming the script is in /var/www_local/WWWHub.)


text:
Q: What is this new Axum programming language? I read this story on slashdot today where they announce a new parallel programming language by Microsoft.
What is this new programming language about? It says Parallel Programming. But is it going to be an alternative/replacement for MPI, PVM, OpenMP and similar parallel libraries/frameworks?
Any thoughts?

A: Axum is a language structured in such a way as to make safe and performant concurrent programming simpler.  The concepts modelled by the language avoid the need to make thread synchronisation explicit via the use of lock (in C#), Monitor, ReaderWriterLockSlim, etc...
It could be argued that many of the ideas within Axum have been in the Erlang programming language since 1986 -- a language designed by researchers working in Sweden for Ericsson to run on telephone switches, and hence support for massive throughput under highly concurrent load was so essential it was designed into the language.  Whilst many of the ideas in Axum aren't new, they are certainly new to .NET and the CLR (at least at the language level.)
Existing .NET libraries that contain some of these ideas are:

*

*Retlang

*Concurrency and Coordination Runtime (CCR)
Like Erlang, message passing is a central concept in Axum.  Like Erlang, Axum is largely indifferent as to whether the recipient of the message is located in-process or remotely.  Axum currently provides integration with WCF.
Axum differs from the libraries mentioned above in that it includes support for these concepts at the language level, not just via use of libraries.  The Axum compiler deals not only with the Axum language, but also with some experimental extensions to the C# language itself; namely the isolated and readonly keywords.
Adding new features to a language is not something to be taken lightly.  Spec# is another C#-superset language developed at MSR (unrelated to concurrency).  As seen with the support for Code Contracts in .NET 4.0, Microsoft has decided to favour adding a new API rather than new language extensions (this benefits users of all languages on the CLR.)  However in the case of Axum, there is not enough richness in the C# 3.0 language to express the kinds of immutability constraints required of types and their members for truly safe concurrent programming.
Having dabbled in Erlang and liking what I saw, I'm very excited about where Axum might take us.  Some of the extensions to the C# language proposed by the team are useful for regular C# projects too.
Finally I'd like to point out that there's more to Erlang than just a good concurrency model.  Erlang is a strict functional programming language.  It supports hot swappable code, meaning that a system can be upgraded without it ever being stopped (a desirable feature of a telephone switch or any other 24x7 system).  I heard a report from a large British telecommunications organisation running a switch for a year and only failing to route four calls in that time.  Erlang has other characteristics such as remote exception handling as well.

A: Looks to me like you hit the nail on the head in your question. Looks like the Microsoft.NET alternative to some of the languages/frameworks you mentioned. Take a look at the Programmer's Guide here:
Axum Programmer's Guide
Looks like it should play nicely with the rest of the .NET Framework. It might open up some interesting C#/F#/Axum interactions...

A: Axum is the new name for Microsoft's "Maestro" language, which originally was a research language for parallel programming but has been "promoted" to a first-class language just recently.
A bit more information on Channel 9 here:
Maestro: A Managed Domain Specific Language For Concurrent Programming
... and on the official Axum team blog.

A: Here's an update on the state of Axum.  Apparrently some of the concurrency features will no longer be part of C#/VB.Net.

...the concepts around safe parallelism and
  agent-based programming were seen by many as too far outside the
  mainstream to be adopted now in languages like C# and VB. The idea of
  Axum was to not force these concepts on general-purpose languages, so
  those of us who have work on Axum are not surprised.


text:
Q: Need help creating a raw socket in Python I am using Python 2.7. I have tried everything and it is not connecting. The error I get is:
Socket could not be created. Error Code : 10013 Message An attempt was
    made to access a socket in a way forbidden by its access permissions.

I am making a ping.
def doOnePing(destAddr, timeout):
    icmp = socket.getprotobyname("icmp")
    # SOCK_RAW is a powerful socket type. For more details see:
    # http://sock-raw.org/papers/sock_raw
    # Fill in start
    # Create Socket here
    try:
        #mySocket = socket.socket(2, 3, 1)
        # the public network interface
        HOST = socket.gethostbyname(socket.gethostname())

        # create a raw socket and bind it to the public interface
        mySocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
        mySocket.bind((HOST, 0))

        # Include IP headers
        mySocket.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)

        # receive all packages
        mySocket.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)

        # receive a package
        print mySocket.recvfrom(65565)

        print ('Connected by', destAddr)
    except socket.error , msg:
        print ('Socket could not be created. Error Code : ' + str(msg[0]) +
              ' Message ' + msg[1])
    #Fill in end

A: Try running your script as a privileged user. The root user on Linux would be appropriate.


text:
Q: Can I automatically reboot if disconnected from the internet? I have an old desktop that I'm running as a web server from my home while I'm at college.  The internet at home is crappy and a lot of times when it goes down, the desktop can't reconnect without a reboot.
Is there a way to make a script that loads on startup and every 12 hours or so, will attempt to ping the router, and if it fails, reboots the server?
EDIT:
Ok, I was able to make this script after googling around a bit.
#!/bin/bash

ping -c 1 192.168.1.1 > /dev/null
if [ $? -ne 0 ]; then
  reboot
fi

That tests if the ping is successful, and if it's not it reboots.
Now what do I need to do to make this run on a set schedule?

A: You didn't mention the operating system, but if you're using Windows, something like this may be helpful:  JScript for Ping, Renew IP and Network Info / Repair.
This is a script I put together for a similar issue.  It does pretty much exactly what you're looking for, in that it pings the default gateway (which will be your router) on a given schedule, and then takes required action if the ping fails.
In this case, the problem PCs didn't need to be rebooted, but simply have an ipconfig /release and ipconfig /renew scripted in order to regain connectivity.  Something like this might work well for your case as well.  If a full reboot is still required, this script could be easily modified to account for that as well.
For Linux, you could use a shell script like this:
#!/bin/sh

ping -c5 192.168.1.1

if [ $? -eq 0 ]; then
    echo "ok"
else
    reboot
fi

This works because of the return code of ping, as detailed in the man page:

If ping does not receive any reply packets at all it will exit with
  code 1. If a packet count and deadline are both specified, and fewer
  than count packets are received by the time the deadline has arrived,
  it  will  also exit with code 1.  On other error it exits with code 2.
  Otherwise it exits with code 0. This makes it possible to use the exit
  code to see if a host is alive or not.

After replacing 192.168.1.1 with the address of your router, you could schedule this to run every hour or so using cron.  In order to reboot, you'll need to run this as root.  For default Ubuntu, you can add a cron job using:
sudo crontab -e

To have this check run every hour, for example:
00 * * * * /path/to/script/pingRouterCheckReboot.sh

You'll need to ensure that the script is executable (chmod +x).
If you find that bringing the interface down and back up is sufficient, you could do this instead, doing something like ifdown eth0; ifup eth0.  Or, combine approaches:  First do this, and then do the ping test again.  If connectivity still isn't restored, then force the drastic measure of a full reboot.


text:
Q: How to groupby different keys in javascript? I have an array of object which the keys are the page and link, I want the final result to group the page by links.
My code is :
  let Test =[
    {page:'getting link 1', lien:['lienPage1HTTP_404V']},
    {page:'getting link 2', lien:['lienPage2HTTP_404V1']},
    {page:'getting link 3', lien:['lienPage3HTTP_404V3','lienPage3HTTP_404V']},
    {page:'getting link 4', lien:['lienPage4HTTP_404V4']},
  ];

  var sorted = {};
  var Last1 =[];
  var Last2 =[];

  for( var i = 0; i< Test.length;  i++ ){
    if(Test[i].lien.length>1){
      for(let k=0; k<Test[i].lien.length; k++){
        Last1.push(({lien:Test[i].lien[k], page: Test[i].page}))
      }
    }
    else {
      Last2.push(Test[i])
    }
  }
  var Last = Last1.concat(Last2);
  for( var i = 0; i< Last.length;  i++ ){
    if( sorted[Last[i].lien] == undefined ){
      sorted[Last[i].lien] = [];
    }
    sorted[Last[i].lien].push(Last[i].page)
  }

when I try to console the sorted, I get :
[object Object] {
  lienPage1HTTP_404V: ["getting link 1"],
  lienPage2HTTP_404V1: ["getting link 2"],
  lienPage3HTTP_404V: ["getting link 3"],
  lienPage3HTTP_404V3: ["getting link 3"],
  lienPage4HTTP_404V4: ["getting link 4"]
}

But I want the final result will be :
[object Object] {
  lienPage1HTTP_404V: ["getting link 1", "getting link 3"],
  lienPage2HTTP_404V1: ["getting link 2"],
  lienPage3HTTP_404V3: ["getting link 3"],
  lienPage4HTTP_404V4: ["getting link 4"]
}

For each same key, we have the array of his value.
How can I fix it ?

A: You could only take a part of the strings of lien and get only HTTP_404V' for grouping in a temporary object.

var data = [{ page: 'getting link 1', lien: ['lienPage1HTTP_404V'] }, { page: 'getting link 2', lien: ['lienPage2HTTP_404V1'] }, { page: 'getting link 3', lien: ['lienPage3HTTP_404V3', 'lienPage3HTTP_404V'] }, { page: 'getting link 4', lien: ['lienPage4HTTP_404V4'] }],
    reference = {},
    grouped = {};

for (let { page, lien } of data) {
    for (let k of lien) {
        let key = k.match(/HTTP_404.*/)[0];
        if (!reference[key]) {
            reference[key] = [];
            grouped[k] = reference[key];
        }
        reference[key].push(page);
    }
}

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: You can replace the unnecessary part of the text and work with the remaining part.  Additionally, you should keep a pointers of the grouped values.

let arr =[{page:'getting link 1', lien:['lienPage1HTTP_404V']}, {page:'getting link 2', lien:['lienPage2HTTP_404V1']},{page:'getting link 3', lien:['lienPage3HTTP_404V3','lienPage3HTTP_404V']},{page:'getting link 4', lien:['lienPage4HTTP_404V4']}],
    result = arr.reduce((a, {page, lien}) => {
      lien.forEach(e => {
        let extractedPart = e.replace(/lienPage[0-9]+/, "");
        a.pointers[extractedPart] = a.pointers[extractedPart] || e;
        (a.group[a.pointers[extractedPart]] || (a.group[a.pointers[extractedPart]] = [])).push(page);
      });
      return a;
    }, {pointers: {}, group: {}}).group;

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: var newAr = []
Test.forEach((a,b)=>{newAr.push(a.lien)})
console.log(newAr.filter((a, b) => newAr.indexOf(a) === b))
//["lienPage1HTTP_404V,lienPage2HTTP_404V1,lienPage3HTTP_404V3,lienPage3HTTP_404V,lienPage4HTTP_404V4"]

//Use this unique array and loop through Test Object
Use Map of Object and loop through newAr and append to the Object as per requirement.

A: This can help:
let Test =[
    {page:'getting link 1', lien:['lienPage1HTTP_404V']},
    {page:'getting link 2', lien:['lienPage2HTTP_404V1']},
    {page:'getting link 3', lien:['lienPage3HTTP_404V3','lienPage3HTTP_404V']},
    {page:'getting link 4', lien:['lienPage4HTTP_404V4']},
  ];
var data={};

  Test.map(el=>{
      el.lien.map(dt=>{
          data[dt]=data[dt]?[...data[dt],el.page]:[el.page]
      })
  })
  console.log(data)


text:
Q: Controller usage get crash on Phalcon 2.0.9 So now, I code on my project using micro phalcon. It seems work without using controllers. By the time my code get bigger and bigger for increasing number of API routes. I put all of my codes in app.php. Is there any chance of me to get better looking of code block without losing performance? I've tried adding controller to use like tutorial in https://docs.phalconphp.com/en/latest/reference/micro.html#using-controllers-as-handlers but seems I can't do that. I always get error if I use MicroCollection. I need request->getRawJSON, modelsManager, and a Request funtion. Thanks

A: We don't support 1.x branch for a long time. Try 2.x please


text:
Q: In winform, how to add sort column functionaity into listview columns? In winform, how to add sort column functionaity into listview columns ?
I could not find any properity for column which allows>
Thanks

A: You have to write your own class that implements IComparer.
You then write a Compare method that Implements IComparer.Compare in this class.
Below is an example of one I wrote some time ago that sorts by number, date or string but you can modify this for your own use:
Public Class ListViewComparer
    Implements IComparer

    Private _columnNumber As Integer
    Private _sortOrder As SortOrder

    Public Sub New(ByVal colIndex As Integer, ByVal sortingOrder As SortOrder)
        _columnNumber = colIndex
        _sortOrder = sortingOrder
    End Sub

    ' Compare the items in the appropriate column
    ' for objects x and y.
    Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
        Dim itemX As ListViewItem = DirectCast(x, ListViewItem)
        Dim itemY As ListViewItem = DirectCast(y, ListViewItem)
        Dim stringX As String = "", stringY As String = ""
        ' Get the sub-item values.

        If itemX.SubItems.Count > _columnNumber Then stringX = itemX.SubItems(_columnNumber).Text
        If itemY.SubItems.Count > _columnNumber Then stringY = itemY.SubItems(_columnNumber).Text

        ' Compare them.
        If _sortOrder = SortOrder.Ascending Then
            If IsNumeric(stringX) And IsNumeric(stringY) Then
                Return CInt(stringX).CompareTo(CInt(stringY))
            ElseIf IsDate(stringX) And IsDate(stringY) Then
                Return DateTime.Parse(stringX).CompareTo(DateTime.Parse(stringY))
            Else
                Return String.Compare(stringX, stringY)
            End If
        Else
            If IsNumeric(stringX) And IsNumeric(stringY) Then
                Return CInt(stringY).CompareTo(CInt(stringX))
            ElseIf IsDate(stringX) And IsDate(stringY) Then
                Return DateTime.Parse(stringY).CompareTo(DateTime.Parse(stringX))
            Else
                Return String.Compare(stringY, stringX)
            End If
        End If
    End Function
End Class

Usage:
ListViewControl1.ListViewItemSorter = New ListViewComparer(2, SortOrder.Ascending)
ListViewControl1.Sort()


text:
Q: Slave I/O thread dies very often I have MySQL Replication working between two servers in master-master mode.
Replication has been working from day 1.
The IO Thread and the SQL Thread has never died. However, the Slave SQL thread dies very, very often.
The log only says:
120913 17:58:50 [Note] Slave I/O thread killed while reading event
120913 17:58:50 [Note] Slave I/O thread exiting, read up to log 'mysql-bin.004109',
    position 101146947
120913 17:58:50 [Note] Error reading relay log event: slave SQL thread was killed

I've Googled for the problem, but found no indication of what to look for or how to resolve the issue.
What could be causing the thread to die?

A: When the IO Thread dies, it usually dies for these reasons

*

*STOP SLAVE;

*STOP SLAVE IO_THREAD;

*Network Issues

The first two reasons are obvious, but many have been victimized by network connectivity. For example, if there are enough dropped packets along the traceroute of the IP you are using as the Master, the IO Thread will just die off. By default, mysql attempts to reconnect to the Master every 60 seconds.
The mysqld process does not record network level issues, but a dying IO Thread is usually a dead giveaway (no pun intended). If this is happening often, go to work troubleshooting the traceroute on that IP (perhaps ifconfig on that Master IP).


text:
Q: Maven: Could not resolve dependencies (artifact not found) I'm trying to build moquette using maven, being a complete newbie to Maven tough.
I'm using the following command to build.

mvn clean install -U

And

mvn clean install -U | grep ERROR

Results in the following:
[ERROR] Failed to execute goal on project moquette-broker: Could not resolve dependencies for project org.eclipse.moquette:moquette-broker:jar:0.7-SNAPSHOT: Could not find artifact org.mapdb:mapdb:jar:1.1.0-SNAPSHOT in Paho Releases (https://repo.eclipse.org/content/repositories/paho-releases/) -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException
[ERROR]
[ERROR] After correcting the problems, you can resume the build with the command
[ERROR]   mvn <goals> -rf :moquette-broker

The full output of:

mvn clean install -e -X -U

Can be found here.
My pom.xml looks like:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <netty.version>4.0.24.Final</netty.version>
        <source.version>1.7</source.version>
        <target.version>1.7</target.version>
    </properties>

    <groupId>org.eclipse.moquette</groupId>
    <artifactId>moquette-parent</artifactId>

    <packaging>pom</packaging>
    <version>0.7-SNAPSHOT</version>
    <name>Moquette MQTT parent</name>
    <url>http://code.google.com/p/moquette-mqtt/</url>

    <modules>
        <module>parser_commons</module>
        <module>netty_parser</module>
        <module>broker</module>
        <module>distribution</module>
        <module>bundle</module>
    </modules>

    <reporting>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>cobertura-maven-plugin</artifactId>
                <version>2.6</version>
            </plugin>
        </plugins>
    </reporting>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>${source.version}</source>
                    <target>${target.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

What is causing this problem and how do I fix this?

A: According to the documentation of Moquette, a simple mvn clean install should do it:

After a git clone of the repository, cd into the cloned sources and: mvn clean package. In distribution/target directory will be produced the selfcontained tar for the broker with all dependencies and a running script.

In other words, you are doing everything right.
However, dependency org.mapdb:mapdb:jar:1.1.0-SNAPSHOT is missing (as of january 20th 2015). In other words, the installation instructions are insufficient.
By refering to the MapDB documentation, they publish nightly builds to a repository. If you add this as a repository, it will work (I just verified this myself):
<repositories>
    <repository>
        <id>sonatype-snapshots</id>
        <url>https://oss.sonatype.org/content/repositories/snapshots</url>
    </repository>
</repositories>

You can put this definition directly in your pom file, or configure it in the settings.xml file of the maven installation, as per instructions here.
So for your pom, it will look like this:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <repositories>
        <repository>
            <id>sonatype-snapshots</id>
            <url>https://oss.sonatype.org/content/repositories/snapshots</url>
        </repository>
    </repositories>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <netty.version>4.0.24.Final</netty.version>
        <source.version>1.7</source.version>
        <target.version>1.7</target.version>
    </properties>

    <groupId>org.eclipse.moquette</groupId>
    <artifactId>moquette-parent</artifactId>

    <packaging>pom</packaging>
    <version>0.7-SNAPSHOT</version>
    <name>Moquette MQTT parent</name>
    <url>http://code.google.com/p/moquette-mqtt/</url>

    <modules>
        <module>parser_commons</module>
        <module>netty_parser</module>
        <module>broker</module>
        <module>distribution</module>
        <module>bundle</module>
    </modules>

    <reporting>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>cobertura-maven-plugin</artifactId>
                <version>2.6</version>
            </plugin>
        </plugins>
    </reporting>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>${source.version}</source>
                    <target>${target.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

To explain this a bit more, maven checks for the needed artifacts in the repositories configured. In most cases, the artifacts exist in the "default" repositories, and no extra repositories are needed.
On the other hand, let's say you have built your own maven artifact, and host your own maven repository. You publish the artifact to that repository. Now, if other users want to use it, they would have to do a configuration similar to the one above.
And by the way, -U forces updates, which is not needed unless you really want to force maven to download/re-download the dependencies.


text:
Q: Transactions in typeorm with mongodb I've a nestjs app with mongodb v4.2.2 I'm trying to run a function in a transaction by adding @Transactional() from typeorm-transactional-cls-hooked lib and I'm getting this error
TypeORMError: Transactions aren't supported by MongoDB.
as I know that transactions are supported in mongodb since 4.0. so typeorm is not supporting transactions for mongodb or am I missing something here?

A: According to this issue mongodb driver does not support transactions yet. There is a failed PR that has not been updated since 2019.


text:
Q: Is there any way to show data like this in listview? Hi I am completely new to Yii2 and I want to show the titles of the latest 10 posts with links to view the page. I found a way to do that but it's not good. Is there a better way to do this?
my controller:
public function actionIndex()
{

     $dataProviderlatenew=new ActiveDataProvider([
         'query'=>Post::find(),
         'pagination'=>[
         'pageSize'=>9,
         ],
         ]);
     return $this->render('index',[
        'dataProviderlatenew'=>$dataProviderlatenew,
        ]);

}

index.php:

<?php echo ListView::widget([
'dataProvider'=>$dataProviderlatenew,
'itemView'=>'latest_news',
'summary' => '',
'itemOptions' => [
     'tag' => false
 ],
 'pager' => [
 'options' => [
        'tag' => 'div',
         'style' => 'display: none;',
        'id' => 'pager-container',
        'class'=>'',
    ],
 ],
 ]);?>

latest_news.php

<a href="<?=\yii\helpers\Url::to(['/post/show','title'=>$model->title])?>"><?=$model->title?>

If there is a better way please say. Thank you.

A: The best thing to do would be to
1.) get the data using the select parameters and sort by create date n time.
2.) after the selection of row run a loop through all records selected and echo each row using while loop in same function and echo out the li items in the loop and call the function between the UL tags in html
In index.html

    <?php
function in php controller();
?>

In controller php file create a function
<?php
function called from html ul {
$sql = select query for getting data
$result = Db connection query
while($row = mysqli_fetch_assoc($result)){
echo '
'.$row['column_name'].'
';
}
}

This function will give you a list of all the news which u want to show
You can also write functiondirectly in the ul tags instead of calling function from another file
Then using bootstrap or jquery set pagination to it


text:
Q: Shopify: Get the userErrors from checkoutLineItemsReplace Mutation I have this Mutation and I am trying to access to the userErrors but I cannot get the code or field and mesage is the only one I can get or am I doing something wrong? The mutation is working because is removing the products but when some error occurs, I need to get to code or field in order to do a specific action.
export const ITEM_REMOVED = gql`
    mutation checkoutLineItemsReplace($lineItems: [CheckoutLineItemInput!] !, $checkoutId: ID!) {
        checkoutLineItemsReplace(lineItems: $lineItems, checkoutId: $checkoutId) {
            userErrors {
                code
                field
                message
            }
            checkout {
                ...CheckoutFragment
            }
        }
    }
    ${CHECKOUT_FRAGMENT}
`

const [mutationItemRemoved] = useMutation(ITEM_REMOVED)

// Item removed
const itemRemoved = (lineItems) => {
    mutationItemRemoved({
        variables: {
            checkoutId: props.checkout.id,
            lineItems,
        },
    }).then(r => {
        console.log(r.data.checkoutLineItemsReplace.checkout)
        props.updateCheckout(r.data.checkoutLineItemsReplace.checkout)
    }).catch(error => {
        console.log(error.code) // undefined
        console.log(error.field) // undefined
        console.log(error.message)
    })
}

A: I'm pretty sure Shopify haven't implemented a code return on userErrors. They will return a code on errors which include extensions. But userErrors seem to only return field and message, and field is often blank.