text:
Q: Why is it important for a correlation matrix to be positive semidefinite? Now I understand the definition of positive semidefiniteness but I am struggling to understand as to why a Correlation matrix must be positive semidefinite. What are the effects of negative eigenvalues in relation to correlation matrices?

A: Note that I've written this answer in terms of covariance matrices, but a correlation matrix is simply a scaled covariance matrix where
$\rho_{i,j}=\frac{C_{i,j}}{\sqrt{C_{i,i}} \sqrt{C_{j,j}}}$.
It's relatively easy to show that $C$ is positive semidefinite if and only if $\rho$ is positive semidefinite.
This answer is written in two parts because the term "covariance matrix" is sometimes used for the sample covariance matrix of a data set and other times for the theoretical covariance matrix of jointly distributed random variables.
First, the sample covariance.
Given a sequence of data vectors $x^{(1)}$, $x^{(2)}$, $\ldots$, $x^{(n)}$,
Let $X$ be the matrix whose columns are $x^{(1)}$, $x^{(2)}$, $\ldots$, $x^{(n)}$.
$X=\left[ x^{(1)}, x^{(2)}, \ldots x^{(n)} \right] $.
The sample mean is
$\bar{x}=\frac{\sum_{i=1}^{n} x^{(i)}}{n}$.
It's convenient to define
$\bar{X}=\bar{x}\left[1, 1, \ldots, 1 \right]$
to get a matrix whose columns are each $\bar{x}$.
The sample covariance matrix is
$C=\frac{1}{n-1} \left( XX^{T} - \bar{X}\bar{X}^{T} \right)$.
To see that this matrix is positive semidefinite, take any vector $z$ in $R^{n}$.  Then
$z^{T}Cz=\frac{1}{n-1} (z^{T}(X-\bar{X}))^{T}((X-\bar{X})z$.
$z^{T}Cz=\frac{1}{n-1} ((X-\bar{X})z)^{T}((X-\bar{X})z)=\frac{1}{n-1}\| (X-\bar{X})z \|_{2}^{2} \geq 0$.
Thus $C$ is positive semidefinite.
Note that, in practice, particularly if $n$ is smaller than the dimension of the vectors $x$, $C$ can be numerically singular and might have what appear to be small negative eigenvalues.
Next, the covariance matrix of a jointly distributed vector of random variables.
Suppose that the random variables $X_{1}$, $X_{2}$, $\ldots$, $X_{n}$ are jointly distributed.  We'll assume that $E[X]=0$, but it's an easy exercise to extend this to a nonzero mean $\mu$.  Then
$\mbox{Cov}(X)=C=E[XX^{T}]$.
To show that $C$ is positive semidefinite, take any vector $z$ in $R^{n}$, and consider the random variable
$W=z^{T}X=z_{1}X_{1}+z_{2}X_{2}+\ldots+z_{n}X_{n}$.
Since $E[X^{(i)}]=0$, $E[W]=0$, and
$\mbox{Var}(W)=E[W^{2}]$.
$\mbox{Var}(W)=E[(z^{T}X)^{2}]=E[z^{T}XX^{T}z]$.
$\mbox{Var}(W)=z^{T}Cz$.
But the variance of every random variable is greater than or equal to 0, so
$\mbox{Var}(W)=z^{T}Cz \geq 0$.
In practice, we usually try to avoid working with covariance matrices that are positive semidefinite but singular and prefer to work with covariance matrices that are actually positive definite.

A: The fact that a correlation matrix is positive-semidefinite (p.s.d.) is a property, not a desired attribute. Note that this is a theoretical fact, some algorithms may generate matrices with negative eigenvalues due to computational error and floating-point error.
Now let's take this discussion one step back so we can understand it better after.
The correlation matrix is part of a decompositon of the covariance matrix as shown below
$$
\Sigma = \operatorname{diag}(\sigma) C \operatorname{diag}(\sigma)
$$
where $\operatorname{diag}(\sigma)$ is a diagonal matrix with the standard deviations as it's entries.
Also notice that a p.s.d. matrix satisfy the following:
$$\forall x \in \mathbb{R}^{n}, \; x^\top\Sigma x \geq 0$$
A useful fact about p.s.d. matrices that comes from the above statement is that there diagonal elements $\sigma_{ii}$ are greater or equal to $0$. Just choose $x_j=0$ if $j \not = i$ and $x_j=1$ if $j = i$, this gives $\sigma_{ii}\geq 0$.
So, we know the correlation matrix is p.s.d.. What does that mean?
Notice that if $C$ isn't p.s.d. you may get negative variances in the diagonal as pointed out by user @leonbloy in the comments. Notice that $C$ p.s.d implies $\Sigma$ p.s.d becase for every non-singular matrix $P$, transformations of the form $P\Sigma P$ are p.s.d.
Other interesting property is that if $\Sigma$ is p.s.d. then $\Sigma^{-1}$ is p.s.d. .
Which leads us to another problematic fact, we can't guarantee the following expression is positive neither convex
$$
(y-\mu)^\top\Sigma^{-1}(y-\mu)
$$
This is a commonly encountered expression in statistics known as mahalanobis distance and it's also encountered in the multivariate gaussian distribution. Let $X$ be a $MVN(\boldsymbol\mu, \boldsymbol\Sigma)$ then it's density is given by
$$f_{\mathbf X}(x_1,\ldots,x_k) = \frac{\exp\left(-\frac 1 2 ({\mathbf x}-{\boldsymbol\mu})^\mathrm{T}{\boldsymbol\Sigma}^{-1}({\mathbf x}-{\boldsymbol\mu})\right)}{\sqrt{(2\pi)^k|\boldsymbol\Sigma|}}$$
Notice that the best case would be positive-definite $C$ because p.s.d. lets one or more variables be constant (A $0$ in the diagonal means a degenerate dimension and thus it's better to work in $N-1$ dimensions) or a linear combination of others and the $MVN$ pdf also becomes undefined.


text:
Q: How to add Date and Time in Android Sqlite Android Date and Time picker manually and insert in sqlite database.

*

*Date picker

*Time picker

A: You should have searched a bit before posting here, anyway if it helps,
private int mYear;
private int mMonth;
private int mDay;
private int mHour;
private int mMinute;
private Calendar mCalendar;

 private void datePicker() {
    mCalendar = Calendar.getInstance();

    mYear = mCalendar.get(Calendar.YEAR);
    mMonth = mCalendar.get(Calendar.MONTH);
    mDay = mCalendar.get(Calendar.DAY_OF_MONTH);

    DatePickerDialog datePickerDialog = new DatePickerDialog(this,
            new DatePickerDialog.OnDateSetListener() {

                @Override
                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                    mCalendar.set(Calendar.YEAR, year);
                    mCalendar.set(Calendar.MONTH, monthOfYear);
                    mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                     //here you request timePicker Dialog
                    timePicker();

                }
            }, mYear, mMonth, mDay);
    datePickerDialog.show();

}

private void timePicker() {
    mHour = mCalendar.get(Calendar.HOUR_OF_DAY);
    mMinute = mCalendar.get(Calendar.MINUTE);

    TimePickerDialog mTimePicker = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {

//     here you go, you got selectedHour and selectedMinute, convert them into String
            mCalendar.set(Calendar.HOUR_OF_DAY, selectedHour);
            mCalendar.set(Calendar.MINUTE, selectedMinute);
//                   Now if you want current time in long format

            long currentTime= mCalendar.getCurrentTimeInMilis();
               // now you can format this to dd-MM using SimpleDateFormat..

System.out.println(formateDate(curentTime));

        }
    }, mHour, mMinute, false);
    mTimePicker.setTitle("Select Time");
    mTimePicker.show();
}

//Conversion to proper date format
 public static String formatDate(long dateInMillis) {
    DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy hh:mm a", Locale.getDefault());
    Date date = new Date(dateInMillis);
    return dateFormat.format(date);
}

That's it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: IOUtils.toString() exception java.net.SocketTimeoutException: null On a web application, i use async servlet.
When i use IOUtils.toString() method, convert http inputstream to String.
But get java.net.SocketTimeoutException: null on production server,
and unable to reproduce on my local machine.
Below is the stack trace:
java.net.SocketTimeoutException: null
    at org.apache.tomcat.util.net.NioBlockingSelector.read(NioBlockingSelector.java:202) ~[tomcat-coyote.jar:8.0.42]
    at org.apache.tomcat.util.net.NioSelectorPool.read(NioSelectorPool.java:250) ~[tomcat-coyote.jar:8.0.42]
    at org.apache.tomcat.util.net.NioSelectorPool.read(NioSelectorPool.java:231) ~[tomcat-coyote.jar:8.0.42]
    at org.apache.coyote.http11.InternalNioInputBuffer.fill(InternalNioInputBuffer.java:133) ~[tomcat-coyote.jar:8.0.42]
    at org.apache.coyote.http11.InternalNioInputBuffer$SocketInputBuffer.doRead(InternalNioInputBuffer.java:177) ~[tomcat-coyote.jar:8.0.42]
    at org.apache.coyote.http11.filters.IdentityInputFilter.doRead(IdentityInputFilter.java:110) ~[tomcat-coyote.jar:8.0.42]
    at org.apache.coyote.http11.AbstractInputBuffer.doRead(AbstractInputBuffer.java:362) ~[tomcat-coyote.jar:8.0.42]
    at org.apache.coyote.Request.doRead(Request.java:476) ~[tomcat-coyote.jar:8.0.42]
    at org.apache.catalina.connector.InputBuffer.realReadBytes(InputBuffer.java:350) ~[catalina.jar:8.0.42]
    at org.apache.tomcat.util.buf.ByteChunk.substract(ByteChunk.java:395) ~[tomcat-util.jar:8.0.42]
    at org.apache.catalina.connector.InputBuffer.read(InputBuffer.java:375) ~[catalina.jar:8.0.42]
    at org.apache.catalina.connector.CoyoteInputStream.read(CoyoteInputStream.java:190) ~[catalina.jar:8.0.42]
    at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284) ~[na:1.8.0_65]
    at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326) ~[na:1.8.0_65]
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178) ~[na:1.8.0_65]
    at java.io.InputStreamReader.read(InputStreamReader.java:184) ~[na:1.8.0_65]
    at java.io.Reader.read(Reader.java:140) ~[na:1.8.0_65]
    at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:2001) ~[commons-io-2.4.jar:2.4]
    at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1980) ~[commons-io-2.4.jar:2.4]
    at org.apache.commons.io.IOUtils.copy(IOUtils.java:1957) ~[commons-io-2.4.jar:2.4]
    at org.apache.commons.io.IOUtils.copy(IOUtils.java:1907) ~[commons-io-2.4.jar:2.4]
    at org.apache.commons.io.IOUtils.toString(IOUtils.java:778) ~[commons-io-2.4.jar:2.4]
    at org.apache.commons.io.IOUtils.toString(IOUtils.java:803) ~[commons-io-2.4.jar:2.4]

A: Socket timeout implies either the connect timeout or the read timeout has been reached. This error is not caused by IOUtils.toString().
The connect timeout will be thrown immediately when trying to connect to a remote endpoint. if the socket is open at the remote end but no data is returned when trying to read data from the socket you will receive a read timeout.
Both the read and connect timeouts can be set although I suggest using telnet to validate the port is open at the remote end first outside of your application.


text:
Q: Search and replace entire files I've seen numerous examples for replacing one string with another among multiple files but what I want to do is a bit different. Probably a lot simpler :)
Find all the files that match a certain string and replace them completely with the contents of a new file.
I have a find command that works
find /home/*/public_html -name "index.php" -exec grep "version:1.23" '{}' \; -print

This finds all the files I need to update.
Now how do I replace their entire content with the CONTENTS of /home/indexnew.txt (I could also name it /home/index.php)
I emphasize content because I don't want to change the name or ownership of the files I'm updating.

A: find ... | while read filename; do cat static_file > "$filename"; done

efficiency hint: use grep -q -- it will return "true" immediately when the first match is found, not having to read the entire file.

A: If you have a bunch of files you want to replace, and you can get all of their names using wildcards you can try piping output to the tee command:
cat my_file | tee /home/*/update.txt

This should look through all the directories in /home and write the text in my_file to update.txt in each of those directories.
Let me know if this helps or isn't what you want.

A: I am not sure if your command without -l and then print it is better than to add -l in grep to list file directly.
find /home/*/public_html -name "index.php" -exec grep -l "version:1.23" '{}' \;  |xargs -i cp /home/index.php {}

Here is the option -l detail
   -l, --files-with-matches
          Suppress  normal  output;  instead  print the name of each input
          file from which output would normally have  been  printed.   The
          scanning  will  stop  on  the  first match.  (-l is specified by
          POSIX.)


text:
Q: Свой Курсор Добрый день. Каким образом в java можно поменять стандратную стрелочку курсора на свою собственную картинку?
A: Toolkit toolkit = Toolkit.getDefaultToolkit();
Image image = toolkit.getImage("pencil.gif");
Cursor cursor = toolkit.createCustomCursor(image, hotSpot, "Pencil");
setCursor(cursor);
//via http://www.codebeach.com/2008/02/using-custom-cursors-in-java.html


text:
Q: Create a folder via SSH in python I want to create a folder in which I can add a subfolder with the current date and a progressive number and move there a file in which I'm interested.
After the connection to the ssh server is made, I send this code:
from datetime import datetime
i=0
now=datetime.now()
var_log='/var/log/gwlog_0_debug'
folder_Salvo='mkdir /Salvo/'+now.strftime('%m-%d-%Y')+'/'+str(i)
print (folder_Salvo)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(folder_Salvo)
path_Salvo=' /Salvo/'+now.strftime('%m-%d-%Y')+'/'+str(i)
log_Salvo= path_Salvo+'/gwlog_0_debug'
command='cp '+ var_log + log_Salvo
print (command)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(command)

the output of the print commands seems correct
mkdir /Salvo/07-05-2022/0
cp /var/log/gwlog_0_debug /Salvo/07-05-2022/0/gwlog_0_debug

but the folder is not created. Any suggestions?

A: I've done like this:
folder="C:\try\attempts"
os.makedirs(folder)


text:
Q: Console Application -variables I want to import variables Console Application Ex; application.exe -variable1 -variable2 -variable3 And i want to run this exe in Web Application.
Shortly,
First problem; How to import variables out of exe?
Second problem; How to call exe in Web Application from Local Server? I think codes looks like;
CallExeInWebApplicationFromServer("ExePath\app.exe -variable1 -variable2");

Finally sorry my bad english..

A: You can get the parameters using the Environment.CommandLine value.
http://msdn.microsoft.com/en-us/library/system.environment.commandline.aspx
http://www.codeproject.com/KB/recipes/commandlineparser.aspx
and you can run your application using the Process.Start
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start.aspx

A: you should avoid to call executable file from your web app because is very unsafe.
It would be better if your web application store somewhere (let's say to a Sql Table) the action it wants to take (in this case call the .exe file) along with the parameter it needs. Another process could pooling this table and call your .exe file (you will just need to get the command to launch from the Sql Table)


text:
Q: Solve ILP with Branch and Bound and CPLEX C++ I want to solve an ILP using a branch and bound algorithm for a graph labelling problem. My ILP has an objective function and constraints for every possible pair of nodes from the graph. So I have n^2 / 2 possible constraints, and the constraints have following shape:
for two vertices i, j \in V(G) add the constraints:
|X_i - X_j| >= k + 1 - d(i,j)
its obvious that this isn't linear. So i want to implement my algorithm that uses binary branch and bound:

*

*start with empty LP only with the objective function

*start with empty branch tree with start node

*then at every node in the branch tree, create two child nodes.

*

*in the first child node

*

*add the constraints X_i - X_j >= k + 1 - d(i,j)

*and constraint X_i >= X_j

*for the second child node

*

*add the constraint -(X_i - X_j) >= k + 1 - d(i,j)

*and the constraint X_j >= X_i

*repeat this step and possibly bound, until we find best solution

If I do this branch and bound algorithm, and search for the best solution, I would get the best occupancy of which variable should be greater than which.
Then I would get a LP, with constant constraints and I would get the optimal integer solution.
My question now is, what is the best way of doing that in c++ and cplex?
Should I always create a new IloModel in CPLEX? Or can I do it all in the same IloEnv?
I know that there are built in options, to specify the branch and bound in CPLEX, but I would like to do it "manually", so I can also implement functions that selects the "best" next constraint to add.
Thank you very much in advance!

A: Within CPLEX you also have Constraint Programmming and with OPL for example you can directly write
forall( ordered c1, c2 in Cells: distance[c1,c2] > 0) {
      forall(t1 in 1..nbTrans[c1]) {
         forall(t2 in 1..nbTrans[c2] )
           abs(freq[<c1,t1>] - freq[<c2,t2>]) >= distance[c1,c2];
      }
   }

which is part of a frequency allocation model
The same can be done in C++


text:
Q: Sketching a Graph of a Particle Trajectory How can I sketch the trajectory of a particle of mass $m$ with a position vector
$\mathbf{r} = \cos(\omega t)\,\hat{\mathbf{i}} +
\sin(3\omega t)\,\hat{\mathbf{j}}$ ?
Will this be a three dimensional graph, with an $x, y, t$ coordinate system?

A: This will be a 2-dimensional graph, since the position vector r has 2 components.
Draw an x,y plane. At time t, the x position is $\cos(\omega t)$ and the y position is $\sin(3\omega t)$.


text:
Q: Regular expression: matching and grouping a variable number of space separated words I have a string:
"foo hello world baz 33"

The part between foo and baz will be some number of space separated words (one or more). I want to match this string with an re that will group out each of those words:
>>> re.match(r'foo (<some re here>) baz (\d+)', "foo hello world baz 33").groups()
('hello', 'world', '33')

The re should be flexible so that it will work in case there are no words around it:
>>> re.match(r'(<some re here>)', "hello world").groups()
('hello', 'world')

I'm trying variations with ([\w+\s])+, but I'm not able to capture a dynamically determined number of groups. Is this possible?

A: re.match returns result at the start of the string. Use re.search instead.
.*?  returns the shortest match between two words/expressions (. means anything, * means 0 or more occurrences and ? means shortest match).
import re
my_str = "foo hello world baz 33"
my_pattern = r'foo\s(.*?)\sbaz'
p = re.search(my_pattern,my_str,re.I)
result =  p.group(1).split()
print result

['hello', 'world']

EDIT:
In case foo or baz are missing, and you need to return the entire string, use an if-else:
if p is not None:
    result = p.group(1).split()
else:
    result = my_str

Why the ? in the pattern:
Suppose there are multiple occurrences of the word baz:
my_str =  "foo hello world baz 33 there is another baz"

using   pattern = 'foo\s(.*)\sbaz' will match(longest and greedy) :
'hello world baz 33 there is another'

whereas , using pattern = 'foo\s(.*?)\sbaz' will return the shortest match:
'hello world'

A: [This is not a solution, but I try to explain why is not possible]
What you're after is something like this:
foo\s(\w+\s)+baz\s(\d+)

The cool part would be (\w+\s)+ that would repeat the capturing group.
The problem is that most regex flavors, are storing only the last match in that capturing group; old captures are overwritten.
I recommend to loop over the string with a simpler regex.
Hope it helps

A: use index to find the foo and baz. then split the sub string
def find_between( s, first, last ):
    try:
        start = s.index( first ) + len( first )
        end = s.index( last, start )
        return s[start:end].split()
    except ValueError:
        return ""

s = "foo hello world baz 33"
start = "foo"
end = "baz"
print find_between(s,start,end)


text:
Q: Predefined type 'System.void' is not defined or imported I've installed Xamarin Studio Community a few minutes ago (on a windows 7 machine). Now I was trying to create a simple library in c# (target framework Mono/ .Net 4.0), but Xamarin Studios intellisense tells me that the "Predefined type 'System.Void' is not defined or imported". Well, the system/ system.core/ system.data and system.security assemblies are referenced. Is it possible that my installation of Xamarin Studio is broken?
The build log is also useless. Here's it's output
(As you can see there aren't further informations why the build process failed):
Erzeuge Projektmappe (Build projectmap): WinEasy.Backend (Debug)
--------------------- Fertig (Done) ---------------------
Erstellen fehlgeschlagen. (Failed to build)
Build: 1 Fehler (1 error), 0 Warnungen (0 warnings)

After all I can say that the upgrade from xamarin studio 5.10 → 6.0 is the reason for my problem. With version 5.10 it works!


text:
Q: Mobile Adhoc NETwork How to create a Mobile Adhoc NETwork using bluetooth for transmission and j2me for programming? Where should I start?

A: You can start by first choosing an API for Bluetooth like Bluecove etc. Google the available APIs that support java and you can choose any one you find better for you. I have personally worked on Bluecove. But i have never created an Adhoc network. I think you need to create a PAN (personal area network) via bluetooth. Please elaborate how you want to use your ad-hoc network so can tell you something more about it.


text:
Q: Eslint: "Unexpected token /" on jsx I'm trying to configure eslint to work with react:
This is my .eslintrc file:
module.exports = {
  env: {
    browser: true,
    es6: true,
    amd: true,
    node: true,
  },
  extends: ["eslint:recommended"],
  globals: {
    Atomics: "readonly",
    SharedArrayBuffer: "readonly",
  },
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 2018,
    sourceType: "module",
  },
  plugins: ["react"],
  rules: {
    "react/jsx-uses-vars": [2],
    indent: ["warn", 2],
    "linebreak-style": ["warn", "unix"],
    quotes: ["warn", "double"],
    semi: ["warn", "always"],
  },
};

And this is my index.js:
import React from "react";
import ReactDOM from "react-dom";

import App from "./App.js";

ReactDOM.render(<App />, document.getElementById("root"));

The thing keeps complaining about the slash on <App />:
6:22  error  Parsing error: Unexpected token /

I'm not sure whats going on. How can I get rid of that error?


text:
Q: Check if replacement string is valid This is my utility method to check if a replacement string is valid:
public static boolean isValidReplacementString(String regex, String replacement) {
    try {
        "".replaceFirst(regex, replacement);
        return true;
    } catch (IllegalArgumentException | NullPointerException e) {
        return false;
    }
}

I'd like to check this before executing the real replacement because getting the source string(s) is expensive (I/O).
I find this solution quite hacky. Is there already a method in the standard library I am missing?

Edit:
As pointed out by sln, this doesn't even work if no match is found.

Edit:
Following shmosel's answer, I came up with this "solution":
private static boolean isLower(char c) {
    return c >= 'a' && c <= 'z';
}

private static boolean isUpper(char c) {
    return c >= 'A' && c <= 'Z';
}

private static boolean isDigit(char c) {
    return isDigit(c - '0');
}

private static boolean isDigit(int c) {
    return c >= 0 && c <= 9;
}

@SuppressWarnings("unchecked")
public static void checkRegexAndReplacement(String regex, String replacement)  {
    Pattern parentPattern = Pattern.compile(regex);
    Map<String, Integer> namedGroups;
    int capturingGroupCount;

    try {
        Field namedGroupsField = Pattern.class.getDeclaredField("namedGroups");
        namedGroupsField.setAccessible(true);
        namedGroups = (Map<String, Integer>) namedGroupsField.get(parentPattern);
        Field capturingGroupCountField = Pattern.class.getDeclaredField("capturingGroupCount");
        capturingGroupCountField.setAccessible(true);
        capturingGroupCount = capturingGroupCountField.getInt(parentPattern);
    } catch (NoSuchFieldException | IllegalAccessException e) {
        throw new RuntimeException("That's what you get for using reflection!", e);
    }

    int groupCount = capturingGroupCount - 1;

    // Process substitution string to replace group references with groups
    int cursor = 0;

    while (cursor < replacement.length()) {
        char nextChar = replacement.charAt(cursor);
        if (nextChar == '\\') {
            cursor++;
            if (cursor == replacement.length())
                throw new IllegalArgumentException(
                        "character to be escaped is missing");
            nextChar = replacement.charAt(cursor);
            cursor++;
        } else if (nextChar == '$') {
            // Skip past $
            cursor++;
            // Throw IAE if this "$" is the last character in replacement
            if (cursor == replacement.length())
                throw new IllegalArgumentException(
                        "Illegal group reference: group index is missing");
            nextChar = replacement.charAt(cursor);
            int refNum = -1;
            if (nextChar == '{') {
                cursor++;
                StringBuilder gsb = new StringBuilder();
                while (cursor < replacement.length()) {
                    nextChar = replacement.charAt(cursor);
                    if (isLower(nextChar) ||
                            isUpper(nextChar) ||
                            isDigit(nextChar)) {
                        gsb.append(nextChar);
                        cursor++;
                    } else {
                        break;
                    }
                }
                if (gsb.length() == 0)
                    throw new IllegalArgumentException(
                            "named capturing group has 0 length name");
                if (nextChar != '}')
                    throw new IllegalArgumentException(
                            "named capturing group is missing trailing '}'");
                String gname = gsb.toString();
                if (isDigit(gname.charAt(0)))
                    throw new IllegalArgumentException(
                            "capturing group name {" + gname +
                                    "} starts with digit character");
                if (namedGroups == null || !namedGroups.containsKey(gname))
                    throw new IllegalArgumentException(
                            "No group with name {" + gname + "}");
                refNum = namedGroups.get(gname);
                cursor++;
            } else {
                // The first number is always a group
                refNum = (int)nextChar - '0';
                if (!isDigit(refNum))
                    throw new IllegalArgumentException(
                            "Illegal group reference");
                cursor++;
                // Capture the largest legal group string
                boolean done = false;
                while (!done) {
                    if (cursor >= replacement.length()) {
                        break;
                    }
                    int nextDigit = replacement.charAt(cursor) - '0';
                    if (!isDigit(nextDigit)) { // not a number
                        break;
                    }
                    int newRefNum = (refNum * 10) + nextDigit;
                    if (groupCount < newRefNum) {
                        done = true;
                    } else {
                        refNum = newRefNum;
                        cursor++;
                    }
                }
            }
            if (refNum < 0 || refNum > groupCount) {
                throw new IndexOutOfBoundsException("No group " + refNum);
            }
        } else {
            cursor++;
        }
    }
}

If this method throws, either the regex or the replacement string is invalid.
This is even stricter than replaceAll or replaceFirst because these methods won't call appendReplacement if no match is found, hence "missing" invalid group references.

A: I'd say your best bet is to copy the process implemented in Matcher.appendReplacement(), cutting out any logic pertaining to the source string or the result string. This inevitably means you won't be able to do certain validations, such as validating group names and indexes, but you should be able to apply most of them.


text:
Q: Android Layout Division I want to divide my screen in two parts,I have a LinearLayout and it contains two LinearLayouts again.
How to divide these two LinearLayouts into two equal parts?

A: Just add:
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"

to both of them. The layout_weight parameter being equal distributes the amount of space evenly.
Work on accepting some of the answers to your previous questions, as well.

A: Normally I use android:layout_weight="1" for this. Also you can use a table layout.

A: Check if this example helps you.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:id="@+id/rootlinearlayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <LinearLayout
        android:id="@+id/linearlayout01"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:orientation="vertical">
        <EditText
            android:id="@+id/et01"
            android:gravity="center"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="First TextBox"
            android:textSize="18sp" />
    </LinearLayout>
    <LinearLayout
        android:id="@+id/linearlayout02"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:orientation="vertical">
        <EditText
            android:id="@+id/et02"
            android:gravity="center"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Another TextBox"
            android:textSize="18sp" />
    </LinearLayout>
</LinearLayout>

A: we can use
android:layout_width="0dp" and
android:layout_weight="1" for both of fragment
and in parent of these, we can use android:layout_width="fill_parent"


text:
Q: how to get folder security properties on windows using java I want to check for the given folder path(local path,shared path) and credentials for the folder, whether user has access to this folder.
In windows, we can verify that by manually by right click on that folder and go to security tab.
I read some posts, but most of them are suggesting to create a file in that folder and then delete it to verify it. I am restricted to do that in my requirement.
please help me if we can do that it in java

A: *

*Create a new file with the given path:
File testFile = new File("path");

*If canRead:
if(file.canRead()) {
  // do something
}
For a complete list of what you can do with java.io.File, please visit the API (you can try/catch to delete, write, etc):
http://docs.oracle.com/javase/6/docs/api/java/io/File.html

A: The File class has several useful methods to achieve what you want:
File file = new File("path-to-file");
System.out.println(file.exists());
System.out.println(file.getAbsolutePath());
System.out.println(file.getParent());
System.out.println(file.canRead());
System.out.println(file.canWrite());
System.out.println(file.isHidden());

For more info, try using the official docs: http://docs.oracle.com/javase/6/docs/api/java/io/File.html

EDIT
As per OP's comment, here's a way to check a file's owner and the file's permissions:
    Path path = FileSystems.getDefault().getPath("path");
    UserPrincipal owner = null;
    Set<PosixFilePermission> posixFilePermissions = null;
    try {
        owner = Files.getOwner(path);
        posixFilePermissions = Files.getPosixFilePermissions(path);
    } catch (IOException ex) {
        Logger.getLogger(TestCenter.class.getName()).log(Level.SEVERE, null, ex);
    }

    System.out.println(owner);
    System.out.println(posixFilePermissions);

Output (the file has 664 permission on my Linux machine):
victor
[OWNER_WRITE, OWNER_READ, OTHERS_READ, GROUP_WRITE, GROUP_READ]


text:
Q: Spacing between tabs Is there a way to add spacing between tabs?
Here's an image:

I would like to add a space between "Presentation" tab and "testgame", any help?
Here's the css I'm using:
* {
    -fx-focus-color: transparent;
    -fx-faint-focus-color: transparent;

    -fx-background-radius: 0;
    -fx-background-insets: 0;

    -fx-border-radius: 0;
    -fx-border-insets: 0;
}

/* tabs */

.tab {
    -fx-background-color: linear-gradient(#9b2626, #721b1b);
    -fx-border-color: #721b1b;
}

.tab-label {
    -fx-text-fill: white;
}

.tab:hover {
    -fx-background-color: #9b2626;
}

.tab:pressed {
    -fx-background-color: #721b1b;
}

A: Not tested, but try using nested backgrounds instead of your border. That way you can have a transparent background extending on one side, creating the appearance of a space.

* {
    -fx-focus-color: transparent;
    -fx-faint-focus-color: transparent;

    -fx-background-radius: 0;
    -fx-background-insets: 0;

    -fx-border-radius: 0;
    -fx-border-insets: 0;
}

/* presentation tab */

.tab {
    -fx-background-color: transparent, tab-border-color , tab-color;
    tab-color: linear-gradient(light-tab-color, dark-tab-color) ;
    tab-border-color : dark-tab-color ;
    dark-tab-color: #721b1b ;
    light-tab-color: #9b2626 ;
    -fx-background-insets: 0, 0 5 0 0, 1 6 0 0 ;
    -fx-padding: 4 10 4 4 ;
}

.tab-label {
    -fx-text-fill: white;
}

.tab:hover {
    tab-color: light-tab-color ;
}

.tab:pressed {
    tab-color: dark-tab-color;
}

A: You should be able to do add padding or set the space.
  // VBox
VBox vb = new VBox();
vb.setPadding(new Insets(10, 50, 50, 50));
vb.setSpacing(10);


text:
Q: Meaning of the interval property of a set system From Wikipedia (Note that below I corrected a place which I think is a typo):

A set system $(E, F)$ is a collection $F$ of subsets of a ground set $E$.
   $(E, F)$ is said to have the Interval Property,
  if $A, B, C ∈ F$ with $A ⊆ B ⊆ C$, then, for all $x ∈ E \setminus C$, $A\cup \{x\} ∈ F$ and $C\cup \{x\} ∈ F$ implies $B\cup\{x\} ∈ F$.

Does the name "the Interval Property" suggest it comes from some properties of intervals on $\mathbb{R}$? Otherwise, how well can the interval property be understood?
Thanks and regards!

A: This is my guess. The interval property generalizes a certain behavior of intervals in $\mathbb{R}$. If $A$ is something like an interval and $A \cup \{ x \} $ is also something like an interval then either $x \in A$ or $x$ is something like an endpoint for $A$. For example $(0, 1) \cup \{ 1 \} = (0, 1]$, another interval.


text:
Q: image view size in splash-screen I'm creating a splash screen for my application but i have a problem:
I put the image in drawable does not occupy the entire screen of your smartphone.
how to solve?
it's my xml:
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:orientation="vertical" android:layout_width="fill_parent"
     android:layout_height="fill_parent">

     <RelativeLayout android:id="@+id/RelativeLayout01"
      android:layout_height="fill_parent"
      android:layout_width="fill_parent"
      android:gravity="fill"
      android:layout_gravity="center">

           <ImageView android:id="@+id/ImageView01"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:src="@drawable/fundo" />

     </RelativeLayout>

    </LinearLayout>

A: add android:scaleType="fitXY" to ImageView


text:
Q: Can't make use of dont_filter=true within a spider in the right way to avoid some unwanted activity I've created a spider to parse the link from different container from some identical site's (supplied by text file) landing page and then use the link to get the title from it's inner page. Few links have next page button which the spider handles accordingly.
The spider does parse the content but falls into an infinite loop caused by the dont_filter=True parameter. If I don't use that parameter, the spider doesn't reuse some links that were failed to produce desired response in the first place.
I've used this parameter dont_filter=True in three places.

*

*In _retry() method within middlewares

*In the last line within the parse() method

*In the last line within the parse_content() method

spider that I've created:
import os
import scrapy
import urllib
from bs4 import BeautifulSoup
from scrapy.crawler import CrawlerProcess

class YelpSpider(scrapy.Spider):
    name = "yelpspidescript"

    with open("all_urls.txt") as f:
        start_urls = f.readlines()

    def start_requests(self):
        for url in self.start_urls:
            yield scrapy.Request(url,callback=self.parse,meta={"lead_link":url})

    def parse(self,response):
        if response.meta.get("lead_link"):
            lead_link = response.meta.get("lead_link")
        elif response.meta.get("redirect_urls"):
            lead_link = response.meta.get("redirect_urls")[0]

        soup = BeautifulSoup(response.text, 'lxml')
        if soup.select("[class*='hoverable'] h4 a[href^='/biz/'][name]"):
            for item in soup.select("[class*='hoverable'] h4 a[href^='/biz/'][name]"):
                lead_link = response.urljoin(item.get("href"))
                yield scrapy.Request(lead_link,meta={"lead_link":lead_link},callback=self.parse_content)

            next_page = soup.select_one("a[class*='next-link'][href^='/search?']")
            if next_page:
                link = response.urljoin(next_page.get("href"))
                yield scrapy.Request(link,meta={"lead_link":link},callback=self.parse)

        else:
            yield scrapy.Request(lead_link,meta={"lead_link":lead_link},callback=self.parse,dont_filter=True)

    def parse_content(self,response):
        if response.meta.get("lead_link"):
            lead_link = response.meta.get("lead_link")
        elif response.meta.get("redirect_urls"):
            lead_link = response.meta.get("redirect_urls")[0]

        soup = BeautifulSoup(response.text, 'lxml')

        if soup.select_one("h1[class*='heading--inline__']"):
            try:
                name = soup.select_one("h1[class*='heading--inline__']").get_text(strip=True)
            except AttributeError: name = ""
            print(name)

        else:
            yield scrapy.Request(lead_link,meta={"lead_link":lead_link},callback=self.parse_content,dont_filter=True)

if __name__ == "__main__":
    c = CrawlerProcess({
        'USER_AGENT':'Mozilla/5.0',
        'LOG_LEVEL':'ERROR',
    })
    c.crawl(YelpSpider)
    c.start()

middlewares:
from fake_useragent import UserAgent

RETRY_HTTP_CODES = [500, 502, 503, 504, 408, 403, 401, 400, 404, 408]

class yelp_custom_Middleware(object):
    ua = UserAgent()

    def process_request(self, request, spider):
        request.headers['User-Agent'] = self.ua.random

    def process_exception(self, request, exception, spider):
        return self._retry(request, exception, spider)

    def _retry(self, request, reason, spider):
        retryreq = request.copy()
        retryreq.dont_filter = True
        return retryreq

    def process_response(self, request, response, spider):
        if request.meta.get('dont_retry', False):
            return response
        if response.status in RETRY_HTTP_CODES:
            reason = response_status_message(response.status)
            return self._retry(request, reason, spider) or response
        return response

How can I let the spider not to fall into an infinite loop?
EDIT:
I thought to include few of the urls I'm trying with which are within all_urls.txt file in case it helps identify the issue better.

A: You can count retries per URL:
class yelp_custom_Middleware(object):
    ua = UserAgent()
    max_retries = 3
    retry_urls = {}

    def process_request(self, request, spider):
        request.headers['User-Agent'] = self.ua.random

    def process_exception(self, request, exception, spider):
        return self._retry(request, exception, spider)

    def _retry(self, request, reason, spider):
        retry_url = request.url
        if retry_url not in self.retry_urls:
            self.retry_urls[retry_url] = 1
        else:
            self.retry_urls[retry_url] += 1

        if self.retry_urls[retry_url] > self.max_retries:
            # Dont' retry
        else:
            # Retry

A: DISCLAIMER: This solution is a workaround to the described problem, when facing a problem with infinite loops in request is always advisable to identify the cause instead of changing how the filter works.

*

*Create customdupefilter.py at the same level of you middlewares.py or settings.py.
import os

from scrapy.dupefilters import RFPDupeFilter

class CustomDupeFilter(RFPDupeFilter):
    default_max_retries = 5

    def __init__(self, path=None, debug=False):
        super().__init__(path, debug)
        self.request_counter = {}

    def request_seen(self, request):
        max_retries = request.meta.get('max_retries') or self.default_max_retries
        fp = self.request_fingerprint(request)
        if fp in self.fingerprints:
            if self.request_counter.get(fp) >= max_retries:
                self.logger.info('Requests to %s exceeded maximum retries.', request)
                return True
            else:
                self.request_counter[fp] += 1
                return None
        self.fingerprints.add(fp)
        self.request_counter.update({fp: 1})
        if self.file:
            self.file.write(fp + os.linesep)

This assumes you are using a standard folder structure of a scrapy project, if you change the folder structure or the file name just be sure to change the reference in the settings as well.

*

*Add the following line in your settings.py
DUPEFILTER_CLASS = 'YOUR_PROJECT_NAME.customdupefilter.CustomDupeFilter'

*If you use dont_filter=True in the request it will bypass this filter just like the standard class.

*You can send in the request meta the max_retries param to change the number of maximum retries allowed for that particular request, if you don't it will use default_max_retries. Just in case a particular request needs more requests than most of the others. Example:
yield Request(url=request_url, meta={'max_retries': 3})

Explanation:
This will simple overwrite the standard filter class RFPDupeFilter and implements a counter to see how many times that same request is allowed to be repeated, once the maximum number is passed it will filter just like before.
As mentioned, dont_filter will bypass this filtering method.


text:
Q: How do I get a list of the visible nodes in a Flex Tree? I have a basic Tree built in Flex.  The Tree works fine.  I'm attempting to get a list of all of the visible nodes.  I know there is a Tree.openItems, but that does not suffice because (for example) if you open all the items in your tree and then close the root, the invisible opened items are still counted.
I simply want a list of all the visible items.  Any help would be greatly appreciated!

A: Loop though the data items and call Tree.isItemVisible(item) for each.


text:
Q: Combining the UNIQUE and CHECK constraints I have a table with columns a b and c, and if c is false then I only want to allow insertions if columns a and b are unique, but if c is true then a and b do not need to be unique.
Example:
There can only be one (foo, bar, false) in the table, but no limit on how many (foo, bar, true) there can be.
I tried something like CONSTRAINT blah UNIQUE (a,b) AND CHECK (C is TRUE) but I can't figure out the correct syntax.

A: Unique constraints are for all rows, and there is no way to specify only some rows.
Check constraints are only for validation within a single row.
The only ways to achieve your requirements is to do any of the following:
1) create a stored procedure where all INSERTs are made from.  You can validate all of your logic here.  However rogue programs/users can avoid using this and defeat your logic.
2) create a trigger that validates your logic and causes invalid inserts/updates to fail.  Should be written to handle a set of rows at a time
3) create a check constraint that calls a user defined function that does your validation checks.  This is considered a bad practice and should be avoided because they are very slow and may fail for multi-row updates.
I recommend option #2, trigger, because this is exactly what triggers were designed for.

A: *

*Create an indexed view returning a and b with a filter WHERE C = false, then create a unique index on the view. This is a general approach

*If you have SQL Server 2008, then create a unique filtered index instead

*Stored procedure

*Trigger (before or after)

A: You can always create a trigger that checks the required conditions before inserting.

A: You can use a table constraint (depending on SQL engine -- not clear which one you're using) to make sure there aren't too many tuples of a particular kind.
Under Firebird 2.1:
fb> CREATE TABLE so2587151 (
  >   a VARCHAR(16) NOT NULL,
  >   b VARCHAR(16) NOT NULL,
  >   c VARCHAR(1) NOT NULL CHECK (c in ('T', 'F')),
  >   CONSTRAINT so2587151_only_one_false CHECK (    -- begin CONSTRAINT
  >     NOT EXISTS (   SELECT a, b, COUNT('x')
  >                      FROM so2587151
  >                     WHERE c = 'F'
  >                  GROUP BY 1, 2
  >                    HAVING COUNT('x') >= 1  )
  >   )                                              -- end CONSTRAINT
  > );
fb> INSERT INTO so2587151(a,b,c) VALUES ('foo', 'bar', 'T');
fb> INSERT INTO so2587151(a,b,c) VALUES ('foo', 'bar', 'T');
fb> INSERT INTO so2587151(a,b,c) VALUES ('foo', 'bar', 'F');
fb> INSERT INTO so2587151(a,b,c) VALUES ('foo', 'bar', 'F');
Error: Operation violates CHECK constraint  on view or table
-Operation violates CHECK constraint SO2587151_ONLY_ONE_FALSE on view or table SO2587151
-At trigger 'CHECK_15'
fb> SELECT * FROM so2587151;
 A  |  B  | C
==============
foo | bar | T
foo | bar | T
foo | bar | F

As you can see from the constraint violation error message, this is implemented in terms of Firebird's trigger mechanisms under the hood.


text:
Q: Sum of floating point numbers in a list is off by .00000001 I'm writing a python function that gets a list of probabilities (each rounded to 2 decimal points) in case the sum(list) is not equal to 1.0 and updates the first element of the list to make the sum(list) = 1.0. The Function is below:
def round_off_list_to_1(prob_list):
    if len(prob_list) != 0:
        prob_list[0] = round(prob_list[0] + (1.0 - sum(prob_list)), 2)
    assert sum(prob_list) == 1, "Sum of random probabilities not equal to 1.0"
    return prob_list

What I don't understand is that for the list = [.59, .33, .08] , sum(list) = .9999999. The function gets called and the list remains the same and assert fails.


text:
Q: Lookback API: Return visible work items only We are having several issues using the LBAPI to scope down from the portfolio items in our workspace. Since many teams contribute to a single project, and a user trying to pull metrics on these projects might not always have view access to all the contributing teams, we are faced with one of two options:

*

*Return the 403 error from the Rally servers to the user, giving them no useful information with regards to the requested metrics.

*Pass an array of "visible" teams to the LBAPI which will only return work items from teams which I have view access to.

So, the logical process would be to query with no team filter at first, and in the event that a 403 is encountered, figure out which teams I have view access to and only query for those teams. I don't necessarily mind writing the code for this; it's just that it seems like something that could easily be returned with a single API call. Ideally, in the event that a user does not have view access to any team(s), an array of those team's Object IDs would be returned with the error so that the user knew which teams to request access to.

A: This was an intentional design decision. We wanted to make sure that the same report would appear the same when viewed by two different people. One of the main enhancements to our previous reporting system was the ability to send someone a link to a report and be assured that the report would be viewed the same by all viewers.
We have added a parameter that will restrict the results to only the snapshots that the user has permissions to see.
If you add &removeUnauthorizedSnapshots=true to the url of the request it will filter out the responses you want without having to provide every single project.


text:
Q: How to Override a function in NgOnit by another function? I have two functions startTimer() Which I am calling in the NgOnit(). I have also another function stopTimer()and I want it to work when the timer reaches('00:00'). I tried placing the this.stoptimer()function inside the NgOnit and the constructor but it overrides the
startimer() function. If I put it outside the class I get an error error TS1068: Unexpected token. A constructor, method, accessor, or property was expected.
I am thinking I either need to call the stoptimer() differently or I need to put it inside an if statement in the constructor but I do not know how to call the time property
time: BehaviorSubject<string> = new BehaviorSubject('01:00');
export class Pagename implements OnInit {
  sub: any;

  time: BehaviorSubject<string> = new BehaviorSubject('01:00');

  timer: number;
  interval;

  state: 'start' | 'stop' = 'stop';

 ngOnInit() {

    this.startTimer(1);
}
 startTimer(duration: number) {
   this.state = 'start';
   clearInterval(this.interval);
   this.timer = duration * 60;
   this.interval = setInterval( () => {
     this.updateTimeValue();
   }, 1000);

 }
 stopTimer() {
   clearInterval(this.interval);
   this.time.next('00:00');
   this.state = 'stop';

 }

 updateTimeValue() {
   let minutes: any = this.timer / 60;
   let seconds: any = this.timer % 60;

   minutes = String('0' + Math.floor(minutes)).slice(-2);
   seconds = String('0' + Math.floor(seconds)).slice(-2);

   const text = minutes + ':' + seconds;
   this.time.next(text);

   --this.timer;
 }
}

A: updateTimeValue() {
    let minutes: any = this.timer / 60;
    let seconds: any = this.timer % 60;

    minutes = String('0' + Math.floor(minutes)).slice(-2);
    seconds = String('0' + Math.floor(seconds)).slice(-2);

    const text = minutes + ':' + seconds;
    this.time.next(text);

    --this.timer;
    // VVVVVVVVVVVV this is the change
    if (this.timer === 0) {
        this.stopTimer();
    }
}

Or, for short:
updateTimeValue() {
    let minutes: any = this.timer / 60;
    let seconds: any = this.timer % 60;

    minutes = String('0' + Math.floor(minutes)).slice(-2);
    seconds = String('0' + Math.floor(seconds)).slice(-2);

    const text = minutes + ':' + seconds;
    this.time.next(text);

    // decrement and check equality in the same line
    if (--this.timer === 0) {
        this.stopTimer();
    }
}

A: Since you're already using a behavior subject in the "time" property, why not subscribe to the changes to this value, use the tap operator, then act on it. this way you can keep your functional areas separate.
import { tap } from 'rxjs/operators';

this.time.pipe(
  tap( _time => {
    if (_time === '00:00') {
       this.stopTimer();
    }
  })
).subscribe();

You can put that in the constructor or call it from another method.


text:
Q: Why removing else causes recursive function to repeat the result? When I execute the following code on Python console using the below statement,
for L in permute([12, 32, 3]):
    print(L)

for the code below,
def permute(L):
    if len(L) <= 1:
        yield L
    else:
        for i in range(0, len(L)):
            L[0], L[i] = L[i], L[0]
            for L1 in permute(L[1:]):
                yield [L[0]] + L1

each result appears just once. But, if I remove else and remove the associated indentation of the code below it, I receive each result twice.
Why does it happen?

A: From docs:

The big difference between yield and a return statement is that on reaching a yield the generator's state of execution is suspended and local variables are preserved. On the next call to the generator's __next__() method, the function will resume executing.

So this happens because if body doesn't break execution, so it moves forward to the next yield statement and with else clause reaches end of function and implicitly returns.
Check
def counter(step):
    assert step >= 0, ('Can count only from non-negative number, but found '
                       + str(step))
    if step == 0:
        print('Reached end')
        yield step
    print('Step', step)
    for sub_step in counter(step - 1):
        yield sub_step

>>> list(counter(1))

Step 1
Reached end
Traceback (most recent call last):
  File "<input>", line 13, in <module>
Step 0
  File "<input>", line 8, in counter
  File "<input>", line 8, in counter
  File "<input>", line 3, in counter
AssertionError: Can count only from non-negative number, but found -1

and
def counter(step):
    assert step >= 0, ('Can count only from non-negative number, but found '
                       + str(step))
    if step == 0:
        print('Reached end')
        yield step
    else:
        print('Step', step)
        for sub_step in counter(step - 1):
            yield sub_step
    # implicitly returns here

>>> list(counter(1))
Step 1
Reached end

As we can see without else execution will continue and call counter with step equal to -1.
So you can leave else or refactor your if clause and add return statement into it to explicitly finish execution like
def permute(L):
    if len(L) <= 1:
        yield L
        return
    for i in range(0, len(L)):
        L[0], L[i] = L[i], L[0]
        for L1 in permute(L[1:]):
            yield [L[0]] + L1

Further reading

*

*Generators.

*return and yield statements.

A: Because you are yielding twice, if there is no else loop.


text:
Q: Spark Graphx shortest paths and print the vertexs I have generate a  graph G in Spark GraphX using Scala. I would like to find the number of edges that should be crossed starting from a known vertex pointA to arrive in another vertex pointB. In other words, I need the some shortest paths  and display the points from the vertex pointA to the vertex pointB calculated in number of edges (not using the edges' weights).
I am new to spark and scala , and i am struggling about these problems. is any possible that i can use the pregel to do that , pls let me know ! Thanks a lot!


text:
Q: Proving that disconnecting edges of a 3-edge-colorable graph are of the same color I'm struggling to prove the following:

Edges of a connected cubic graph G can be colored with 3 colors in
such a way that no adjacent edges are of the same color. 2 edges were
removed from the graph making it disconnected. Proof that those edges
were of the same color.

I've found an example of a cubic graph with two edges that disconnect it, and tried to color them with different colors and failed to do that, but I'm not sure how to prove that.

A: Proceed by contradiction. Let $H$ be $G$ after removing the two edges.
Take a connected component $C$ of $H$ and assume $e$ is a removed edge from a vertex $x$ in $C$ to a vertex not in $C$.
Also assume $e$ is blue and the other removed edge is green.
Let the other color be red. Note that the red edges with endings in $C$ form a matching of $C$ so $|C|$ is even.
On the other hand the blue edges with endings in $C$ form a matching of $C\setminus \{x\}$ so $|C|-1$ is even.
A contradiction.


text:
Q: how to dynamic load two different layout based on condition in android code I have a small project, which will require the one android application be used by different group.
For example: one group is the regular user, another group is the admin user.
My question is, if I like to create one similar UI android application, how to dynamically load the layout based on different condition (condition may be embedded in the local sqlite database), and move forward, the same condition will be kept, and the layout will be slightly different for different group of users.

A: as Android uses Java I believe that actually your problem is an exact match for an Abstract Factory implementation. Take a look at Abstract Factory Design Pattern. I believe that is what you need.
http://en.wikipedia.org/wiki/Abstract_factory_pattern
http://www.oodesign.com/abstract-factory-pattern.html
http://www.mydeveloperconnection.com/html/gof_design_patterns.htm
regards.
[]s

A: The code is the same, just different layouts? I would simply inflate different layouts depending on your condition.
Just a fast shot:

*

*res/layout/group01_main.xml

*res/layout/group02_main.xml
...

*res/layout-land/group01_main.xml

*res/layout-land/group02_main.xml
...

And in your activities setContentView() to the correct one.


text:
Q: Javascript search array of lists of arrays I have a list of items I need to loop thru. I need to search if an array of items contains an array of items. This is the array, first value is timestamp, second is a count:
const i = [
    [1614719782079, 1],
    [1614719782085, 1],
    [1614719782091, 2],
    [1614719782096, 2],
]

And I have a forEach loop that goes thru all this data from my backend and I need to check if the timestamp exists in the array(the first value) and if it does, add to the second value of the array(count). This is an example data from backend:
  const mockData = [
    {
      ...someData,
      details: {
        eventTimestamp: 1614719782079,
        equipmentId: 5,
        otherUselessData...
      }
    },
    {
      ...someData,
      details: {
        eventTimestamp: 1614719782079,
        equipmentId: 5,
        otherUselessData...
      }
    }
  ]

Basically if eventTimestamp in the mockData exists in the i, then increment the second value in that array. PS dont ask about the horrible structure of the this data lol. This is all I have to work with

A: Following code should do the trick:
mockData.forEach(mock => {
  const el = i.find(e => e[0] === mock.details.eventTimestamp);
  if(el) {
    el[1]++
  }
})

A: Here is a possible solution:

*

*Create a Map of the elements of i where the first item is the key and the second is the value

*Iterate over mockData, and in each iteration, if the eventTimestamp is in this map, increment its value

*In the end, update i to the entries of this map

let i = [
    [1614719782079, 1],
    [1614719782085, 1],
    [1614719782091, 2],
    [1614719782096, 2],
];
const mockData = [
    { details: { eventTimestamp: 1614719782079, equipmentId: 5 } },
    { details: { eventTimestamp: 1614719782079, equipmentId: 5 } }
];

const updateTimestampCounts = (arr=[]) => {
  const map = new Map();
  i.forEach(([ timestamp, count ]) => map.set(timestamp, count));

  arr.forEach(({ details={} }) => {
    const { eventTimestamp } = details;
    const count = map.get(eventTimestamp);
    if(count) map.set(eventTimestamp, count+1);
  });

  i = [...map.entries()];
}

updateTimestampCounts(mockData)
console.log(i);

A: here is my edited solution, sorry , didnt understand it in first time

const i = [
    [1614719782079, 1],
    [1614719782085, 1],
    [1614719782091, 2],
    [1614719782096, 2],
]

const mockData = [
    {
      details: {
        eventTimestamp: 1614719782079,
        equipmentId: 5,
      }
    },
    {
      details: {
        eventTimestamp: 1614719782079,
        equipmentId: 5,
        count: 1,
      }
    }
  ]

mockData.forEach(mock => {
  const el = i.find(e => e[0] === mock.details.eventTimestamp);
  if(el) {
    el[1]++
  }
})
  console.log(i)


text:
Q: Comma Separated File, appending encrypted charter instead of new line I am creating a comma separated file, that appends encrypted character at the end of each line instead of starting the next line in a new line?
        $inner_exported_header_array[] = 'ID';
        $inner_exported_header_array[] = 'First Name';

        $exported_customers_arr [] = $inner_exported_header_array;
        foreach ($_list AS $row) {
            $inner_exported_array = array();
            $inner_exported_array[] = $row['id'];
            $inner_exported_array[] = $row['v_first_name'];

            $exported_customers_arr[] = $inner_exported_array;
        }

        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header('Content-Description: File Transfer');
        header("Content-Type: text/plain");
        header("Content-Disposition: attachment; filename=test.txt");
        header("Pragma: no-cache");
        header("Expires: 0");

        outputCSV($exported_customers_arr);

function outputCSV($data) {
$outstream = fopen("php://output", "w");

function __outputCSV(&$vals, $key, $filehandler) {
    fputcsv($filehandler, $vals); // add parameters if you want
}

array_walk($data, "__outputCSV", $outstream);
fclose($outstream);
}

Output is showing:
"ID","First Name"[special character not copied here]1,Testname

But if would be:
"ID","First Name"
1,Testname

Any thought, that our new line should be in a new line rather than inserting special characters at end of line ans starting new line from where the first line ends?

A: What are these characters? Seems like they're coming from your database, somehow? These "special" characters seem to contain newline (i.e. \n), which messes up your output.
I suggest checking the value of the last character of your problematic field using PHP's ord() function:
http://php.net/manual/en/function.ord.php
You could clean your CSV output using PHP's trim() function:
http://php.net/manual/en/function.trim.php
trim() also clears newline, which should solve your issue, if applied to the output of each field, i.e change this:
$inner_exported_array[] = $row['v_first_name'];

to:
$inner_exported_array[] = trim($row['v_first_name']);

A: Summary from the comments:
The easiest solution may be to simply read the file in and replace every "\n" with "\r\n". The consumer of the file expects different line endings.


text:
Q: Problems scheduling a task on windows7 I have trouble to schedule a task I wrote.
Basically I created a .bat file which executes an R script (script.R). When I double click the .bar file, it gets executed. I can see a result file and also some kind of log file in script.Rout.
When I try to run everything in the scheduler I have problem to get it to run. When I click on Run to run my task, the task produces several entries in the History tab which shows my task starts, and also ends in the same second. So basically nothing gets executed.
Where can I check what problem occurs? My script writes some output which is located within this .Rout file but this is not created with the task scheduler.
I already added my user to the policy settings to schedule task and also by editing the task, windows does not complain, I think this is not the issue.
Would love to get some help to find the problem.
EDIT:
I realised now, my task is running as long I do not select Execute task whether user is logged in or not. If I switch to this setting, my script does not get executed. Is there maybe some security issue?

A: Task Scheduler Scheduled Batch Script Not Running Check
Task Scheduler Properties. . .
From Windows Task Scheduler on the job properties (see bottom most screen shots) in the. . .

*

*1. General tab, ensure that the below options are select/checked or unchecked just as shown in Print Screen A

*

*Uncheck Run only when user is logged on

*Check Run whether user is logged on or not

*Check Run with the highest privileges

*2. Conditions tab, ensure that the below options are select, checked, or unchecked just as shown in Print Screen B

*

*Check Wake the computer to run this task

*3. Actions tab, click Edit, and enure that the Start in (optional) is set just as shown in the below example (DO NOT put double quote marks around it) for the full path pointing where the batch script is located WITHOUT a final backslash "\" Print Screen C

Security Considerations

*

*Once you press OK (2. above) it should prompt you for the credential to run this as, and that credential is what will need access to EXECUTE the batch file where it exist, and it will also need access to do whatever the batch file is running that you scripted out.

*It may be best to setup a static service/proxy user account for this process and then use its credentials to run the process. You'd need to ensure its password is strong and it set to never expire—and it needs access to EXECUTE the batch and run whatever the batch scripted process is running and any commands and resources, ect. it utilizes as well.

*It seems the option Run whether user is logged on or not you MUST
check the option Run with highest privileges for it to actually
run as expected from the Task Scheduler.
Error Checking

*

*If there is an issue with the actual batch script but the Windows Task
Scheduler actually does execute it to run it but the batch script
logic errors out, etc. for whatever reason, the Task Scheduler may
not see this failure at this level. From its perspective (by default most of the time), it's
executing the batch file so as long as it can execute it and has
access to do so, its job is done successfully.

*Add error checking or logging to the batch script logic to catch (or troubleshoot) issues at this level including ensuring that the security context which the batch scheduler executes it as has appropriate access to commands, resources, etc. which the batch script runs as.

Group Policy Considerations
CHECK GROUP POLICY AND LOG ON AS A BATCH JOB PERMISSIONS

Answer: On Windows, this privilege is granted through the Local or Domain Security Policy. To do this using the Local Security Policy,
  follow these steps.

*

*In the Control Panel, open Administrative Tools, then Local Security
  Policy.

*Beneath Security Settings, open Local Policies and highlight User
  Rights Assignment.

*Locate Log on as a batch job. Open the properties and add any users
  that need this right.

*When finished, save your changes and close the Local Security
  Settings window.

  Your changes should take effect immediately. To make changes to the
  Domain Security Policy, on a domain controller, use the Domain
  Security Policy utility in the Control Panel

Batch Script Logic with Mapped Drives or Full UNC Path, and issues. . .
If your script is referencing a mapped network drive but you want it to Run whether the user is logged on or not, then under this context, the drive mapping may not actually be there for the batch process to do what's expected.
If possible, use UNC paths in your batch script logic rather than a mapped drive letter to avoid issues.  Otherwise, you may need to use PUSHD \\ServerName\ShareName at the beginning of the batch process and then use POPD at the end of the batch process. You could map the drive with NET USE X: \\ServerName\ShareName at the beginning of the batch process and then disconnect the drive with NET USE X: /DELETE at the end of the batch process.

*

*NET USE

*PUSHD

*POPD

OTHERS

*

*MS HOTFIX (KB977353): Group Policy Immediate Task preference item does not run on a client computer that is running Windows 7 or Windows Server 2008 R2

PRINT SCREENS
Print Screen A

Print Screen B

Print Screen C


text:
Q: Configuring DoctrineExtensions-Taggable in Symfony fullstack with config.yml I am having difficulty configuring the Doctrine Extension Taggable provided here:
https://github.com/FabienPennequin/DoctrineExtensions-Taggable
My project is using Symfony 2 Fullstack and my configuration is using yaml while my doctrine entities are using annotation. I installed DoctrineExtensions using composer. Adding "fpn/doctrine-extensions-taggable": "dev-master" to the require section on composer.json and then running composer update. This installed without issue.
I then become lost at this section: https://github.com/FabienPennequin/DoctrineExtensions-Taggable#setup-doctrine
I understand that the metadata is a Doctrine Entity however as previously mentioned I am using yaml for my symfony configuration as well as entity managers. Here is the excerpt from my config.yml file:
# Doctrine Configuration
doctrine:
    dbal:
        default_connection: default
        connections:
            default:
                driver:   "%database_driver%"
                host:     "%database_host%"
                port:     "%database_port%"
                dbname:   "%database_name%"
                user:     "%database_user%"
                password: "%database_password%"
                charset:  UTF8
    orm:
        default_entity_manager: main
        auto_generate_proxy_classes: "%kernel.debug%"
        entity_managers:
            main:
                connection: default
                mappings:
                    VendorMainBundle:
                        prefix: Vendor\MainBundle\Entity
            taggable:
                connection: default
                mappings:
                    taggable:
                        type: xml
                        prefix: DoctrineExtensions\Taggable\Entity
                        dir: %kernel.root_dir%/../vendor/fpn/doctrine-extensions-taggable/metadata

However, when I run php app/console doctrine:mapping:info --em=taggable I get the error:
[Exception]
  You do not have any mapped Doctrine ORM entities according to the current configuration. If you have entities or mapping files you should check your mapping configuration for errors.

Should the above command show the mappings described in the xml files?
Thereby allowing me to update the schema in the database?
I used this documenation as reference for the config.yml file: http://symfony.com/doc/current/reference/configuration/doctrine.html#mapping-configuration
I also added this under the config.yml in order to setup the TagListener. Is this correct?
services:
    taggable:
        class: DoctrineExtensions\Taggable\TagListener

EDIT [@Grimv01k]:
The TagListener requires an argument passed that is an instance of the TagManager Object. I created another service to handle that as follows and passed it to the TagListener:
tag.manager:
        class: DoctrineExtensions\Taggable\TagManager
        tags:
        - { name: doctrine.event_subscriber, connection: default }
        arguments:
            entity.manager: @doctrine.orm.entity_manager
    taggable:
        class: DoctrineExtensions\Taggable\TagListener
        arguments:
            manager: @tag.manager

The TagManager requires an argument of the entityManager however by doing so results in error:
[Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException]
  Circular reference detected for service "doctrine.dbal.default_connection", path: "doctrine.dbal.default_connection".

Across the web it's recommended to resolve this error by passing @service_container and in the constructor of the object pull out the entity_manager, however being a vendor I'd prefer not to modify their code. Is there another way?

A: Just guess: maybe that happens becuse you haven't got tags applied in service, and Doctrine doesn't use this in your complier pass. Try to do it like this:
services:
taggable:
    class: DoctrineExtensions\Taggable\TagListener
    tags:
        - { name: doctrine.event_subscriber, connection: default }


text:
Q: Getting invalid_argument error in Firestore Database Rules I have set the following rule in my Firestore Database rules.
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {

    function getUser(userId) {
        let user = get(/databases/$(database)/documents/users/$(userId));
      return user;
    }

    function getRole(userId) {
        let roleId = getUser(userId).data.role;
        let role = get(/databases/$(database)/documents/roles/$(roleId)).data; // ERROR
      return role;
    }

    function isPermitted(entity_action, userId) {
        return getRole(userId)[entity_action];
    }

    match /action_items/{action_item_id} {
      allow get, list, read: if request.auth != null && isPermitted("action_item.read", request.auth.uid);
    }
  }
}

But get the following error on simulation.

Error running simulation — Error: simulator.rules line [12], column [17]. Function not found error: Name: [get].;
Error: Invalid argument provided to call. Function: [get], Argument: ["||invalid_argument||"]

Any idea how I can resolve this error that I'm getting? Attaching a screenshot of the console.

A: The problem seems to be value of role in user document. It's value roles/admin which is not a valid document ID. That essentially like fetching a document with roles/roles/admin that looks a bit like path to a collection.
Try changing the value of role in user's document to just admin and also document ID in roles collection should be admin.
Users collection:

Roles collection:


text:
Q: UICollectionView iOS8 Wrong Offset Surprisingly, after updating to iOS8 my app does not behave as in iOS7.
In particular, I made a calendar with UICollectionView. In iOS7 fine, the month cells were displayed correctly. But in iOS8...

I see an offset toward the top, that's the cells are shifted upward...I do not understand, really.... The code is very simple.
- (void)viewDidLoad
{
    [super viewDidLoad];
 UINib * nib = [UINib nibWithNibName:@"AgendaYearCollectionCell" bundle:[NSBundle mainBundle]];
    [self.collectionView registerNib:nib forCellWithReuseIdentifier:agendaYearCellIdentifier];
    [self.collectionView setDelegate:self];
    [self.collectionView setDataSource:self];
    UICollectionViewFlowLayout *layout  = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing      = 0;
    layout.minimumLineSpacing           = 1;
    [self.collectionView setCollectionViewLayout:layout];
}

The collection was not scrollable. If I make it scrollable, I can scroll and see the cells of the first row. But I do not want a scrollable collection.
I think the problem is in the inset. In fact, if I play with:
- (UIEdgeInsets)collectionView:
(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(40, 2, 50, 60);

 }

I can eventually get the first row again. But how to calculate the value for all the screen/devices? My app is landscape only and only for iPad.
What Apple changed?

A: Your Collection View has negative top offset. Providing more code could help, however let's try this first.
You called:
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView
                    layout:(UICollectionViewLayout *)collectionViewLayout
    insetForSectionAtIndex:(NSInteger)section

I would not call this unless you want different insets for different sections. It looks like you have only one section. I would configure it with Flow Layout:
flowLayout.sectionInset = CGSizeMake(40.0, 2.0, 50.0, 60.0);

I recommend to drop iOS 7 support, all devices with iOS 7 can be upgraded to 8.

how to calculate the value for all the screen/devices?

Should be the same offset for any iPad. Even if Apple will ship iPad with bigger screen, your offset will be the same. If you want Universal app with support for iPhone you could put device condition check and assign different numbers depending on the device paradigm.
Also, it could be something on the top. Did you messed with Navigation Bar? It doesn't clear from the picture.


text:
Q: how to get text from a dynamic table in wtforms I want to create a flask form where data is dynamically added.
I have this table where its columns are inputs, and the last one is an 'add' button which adds the inputs into a new row. And I have to get the data in those rows into flask form with wtforms.
The following is just an example of what my problem is, but I have different inputs.
Here is an example HTML where the user added the first name

            name<input type="text">
            age<input type="number">
            <button type="button" class="addRow">Add</button>

            John
            25

So I want the names as a list and their corresponding ages as a list. But I don't know what form field I can use if its possible,


text:
Q: Powershell - how do I list files and write their path into an output file? I want to list *.xml files which are in several subdirectories. Then I want to write their path and their names into an txt file.
I managed to write the names into an txt file, however, I have no idea how to add their paths. What do I need to change/add?
Get-ChildItem path -recurse -include *.xml| ForEach-Object { $_.Name } > path\output.txt

Thank you for your help!
Cheers,
Iris

A: FullName will print the full path to the file.
Get-ChildItem path -recurse -include *.xml| ForEach-Object { $_.FullName } > path\output.txt

Here's a list of properties that the object returned in this instance provides: FileInfo Class


text:
Q: Area inside polar curve Find the area of the region inside
$r=7\sin\theta$ but outside $r=1$.
I have tried finding the area of both using $A=\frac{1}{2}\int_\alpha^\beta r^2 d\theta$, tried arc length...but I can't find the answer.

A: Draw a picture, when possible! Don't try arc length, you're finding polar area. Your first integral is the one to use!
Our functions are $r_1=7\sin(\theta)$ and $r_2=1$ (why I number them will be clear I hope later)
So we see we should be integrating from where $7\sin(\theta)=1$ to $\pi/2$ ($\alpha$ and $\beta$, respectively) and then by symmetry we just multiply our integral's result by 2. State this last part and remember to do it!
So we should have an integral like $\int_{\alpha}^{\beta} (outside - inside) d\theta$, better said $\int_{\alpha}^{\beta} r_1^2 - r_2^2 d\theta$
I've left actually writing out the integral (do that!), finding the limits, and doing the calculation. Hopefully there is enough help here, though.

A: \begin{align*}
  A &= \frac{1}{2}
       \int_{\sin^{-1} \frac{1}{7}}^{\pi-\sin^{-1} \frac{1}{7}}
       (r^{2}-1) \, d\theta \\
    &= \frac{1}{2} \int_{\sin^{-1} \frac{1}{7}}^{\pi-\sin^{-1} \frac{1}{7}}
       (49\sin^{2}-1) \, d\theta \\
    &= \frac{1}{2} \int_{\sin^{-1} \frac{1}{7}}^{\pi-\sin^{-1} \frac{1}{7}}
       \left[ 49\left( \frac{1-\cos 2\theta}{2} \right)-1 \right] \, d\theta \\
    &= \left[
         \frac{47}{4}\theta-\frac{49}{8} \sin 2\theta
       \right]_{\sin^{-1} \frac{1}{7}}^{\pi-\sin^{-1} \frac{1}{7}} \\
    &= \frac{47\pi}{4}-\frac{47\pi}{2}\sin^{-1} \frac{1}{7}+
       \frac{49}{4} \sin \left( 2\sin^{-1} \frac{1}{7} \right) \\
    &= \frac{47\pi}{4}-\frac{47\pi}{2}\sin^{-1} \frac{1}{7}+
       \frac{49}{2} \times \frac{1}{7} \times \sqrt{\frac{48}{49}} \\
    &= 2\sqrt{3}+\frac{47\pi}{2}-\frac{47}{2}\sin^{-1} \frac{1}{7} \\
    &= 2\sqrt{3}+\frac{47}{2}\cos^{-1} \frac{1}{7}
\end{align*}


text:
Q: Transfer keystore from Adobe Air to Unity Hope all is well.
We moved a game from Adobe Air to Unity.
But I have issues signing the new Unity game on Google Play.
Do you know how we can move signature / keystore from Adobe Air (p12) to unity (keystore)?
Your help would be much appreciated.
Thank you!
hjeko
We tried different ways to sign the unity game but we always get rejected.

A: You are going to need to change your existing .p12 to .jks in order to use it. For this you will need the java keytool (this is part of your Java SDK).
Then launch your terminal and use this:
keytool -importkeystore -srckeystore [MY_FILE.p12] -srcstoretype pkcs12
 -srcalias [ALIAS_SRC] -destkeystore [MY_KEYSTORE.jks]
 -deststoretype jks -deststorepass [PASSWORD_JKS] -destalias [ALIAS_DEST]

MY_FILE.p12 is your existing .p12 file
MY_KEYSTORE.jks is the destination path where the new file will be saved.
PASSWORD_JKS is your new password for the generated keystore
ALIAS_SRC this should be the same as the current name of your p12
ALIAS_DEST this should be the same as the keystore name.
I hope this works for you.
EDIT:
If you dont have the alias of your keystore you can use this simpler version:
keytool -importkeystore  -srckeystore [MY_FILE.p12] -destkeystore [MY_KEYSTORE.jks] -srcstoretype PKCS12
-deststoretype jks -deststorepass [PASSWORD_JKS]

I have tested on one of my p12 files and it works as should.


text:
Q: Need property to store completion handler with generic type i have defined a typealias like this:
public typealias ResponseCompletion<T> = (Result<T>, [AnyHashable: Any]?) -> Void

Then i have a class with a related method:
public func load<T>(completion: @escaping ResponseCompletion<T>)

this works fine until i forward the completion handler from this method to another. But now i have the requirement to store the completion handler for later use.
When i do something like this:
class ServiceOperation<T: Any>: Operation {
    private let completion: ResponseCompletion<T>

And then try to store the handler
    public func load<T>(Result<T>, [AnyHashable: Any]?) -> Void {
        self.completion = completion
    }

I get the following error:
Cannot assign value of type 'ResponseCompletion<T>' (aka '(Result<T>, Optional<Dictionary<AnyHashable, Any>>) -> ()') to type '(Result<T>, [AnyHashable : Any]?) -> Void'

Anyone has an idea, how to define the property correctly so that i can store the completion handler?

A: I'm not sure what do you want to achieve, but this code will store completion after you will call load() function.
struct Result<T> {}
typealias ResponseCompletion<T> = (Result<T>, [AnyHashable: Any]?) -> ()
class ServiceOperation<T: Any>: Operation {
    private var completion: ResponseCompletion<T>?
    public func load(completion: @escaping ResponseCompletion<T>) {
        self.completion = completion
    }
}

Example of usage:
ServiceOperation<Int>().load { (result, params) in

}


text:
Q: How to not interpret string as command I'm writing a script which should copy a client system and change some lines in a file.
There is a source file which has a line like:
$DB_HOST = "LegitDbHost";

And the destination file has a line like:
$DB_HOST = "testDbHost";

So i need to replace the destination line with the source line and I want to print out something like this:
Replacing line 12: '$DB_HOST = "testDbHost";' ==with==> '$DB_HOST = "LegitDbHost";'(y/n):

So far i got this:
toReplace='$DB_HOST';

sourceLine=$(cat ./sourceFile.php | grep -m 1 "$toReplace[[:space:],=]");
destLineNr=$(cat ./destFile.php | grep -n -m 1 "$toReplace[[:space:],=]" | grep -Eo '^[^:]+');
destLine=$(cat ./destFile.php | grep -m 1 "$toReplace[[:space:],=]");
read -p "Replacing line $destLineNr: $destLine ==with==> $sourceLine.(y/n): ";

however, my output looks like this:
==with==> $DB_HOST    ST   = "testDbHost";.(y/n):

I think it's because the sourceLine has a ; inside and that gets interpreted as a command end.
I just don't know how to get around that.
I hope it's understandable.
Edit:
as suggested i tried using echo -n
toReplace='$DB_HOST';

sourceLine=$(cat ./sourceFile.php | grep -m 1 "$toReplace[[:space:],=]");
destLineNr=$(cat ./destFile.php | grep -n -m 1 "$toReplace[[:space:],=]" | grep -Eo '^[^:]+');
destLine=$(cat ./destFile.php | grep -m 1 "$toReplace[[:space:],=]");

echo -n "Replacing line $destLineNr: "
echo -n $destLine
echo -n " ===with===> "
echo -n $sourceLine

this prints out:
===with===> $DB_HOST = "testDbHost";OS";

A: Try:
#! /bin/zsh -
die() {
  print -ru2 -- "$@"
  exit 1
}

srcFile=./sourceFile.php
dstFile=./destFile.php

toReplace='$DB_HOST'

sourceLine=$(<"$srcFile" grep -Pm1 "\Q$toReplace\E[\s,=]") ||
  die "Can't find $toReplace in $srcFile"

<"$dstFile" grep -nPm 1 "\Q$toReplace\W[\s,=]" |
  IFS=: read -r destLineNr destLine ||
  die "Can't find $toReplace in $dstFile"

if
  read -q "?Replacing line $destLineNr: ${(q+)destLine} ==with==> ${(q+)sourceLine}? (y/n): "
then
  (
     export destLineNr destLine
     perl -lpi -e '$_ = $ENV{destLine} if $. == $ENV{destLineNr}' -- "$dstFile"
  )
fi

Using ${(q+)line} zsh parameter expansion, will make sure CR characters in that variable (as it looks like your input files have MSDOS CRLF delimiters instead of Unix LF ones) is rendered as C-M instead of being sent as-is to the terminal (for a terminal, a CR character makes the cursor go back to the beginning of the line (makes the carriage return for teletypewriter ones)).


text:
Q: counting and probability question I need help figuring out this exercise. I am stuck on it and am not sure how to get it started. Any help is appreciated.
Exercise: An instructor gives an exam with 14 questions. Students are allowed to choose any 10 to answer. I am stuck on part B of this exercise. Part B states, suppose 6 questions require proof and 8 do not. How many groups of 10 questions contains at most three 3 that require proof? I am not sure how to build the necessary equation to answer this.
Thanks,
Tony

A: Since there are only $8$ questions that do not require proof, any set of $10$ questions must have at least $2$ that do require proof.

*

*How many ways are there to choose $2$ questions that require proof and $8$ that do not?

*How many ways are there to choose $3$ questions that require proof and $7$ that do not?

The sum of those two numbers is your answer.


text:
Q: Why an int type of object and a number can not be added? I have a int type variable which is derived from object and when I tried to sum this variable with a number can not sum them. Even though both of them are type of System.Int32 why I can not sum. What is the reason of this ?
Here is my codes:
        object number_1 = 34;
        number_1 = number_1 + 10;

        Console.WriteLine(number_1);

A: You can not sum number with object
it is better :
            object number_1 = 34;
            int numb1 = (int)number_1 + 10;

            Console.WriteLine(numb1);


text:
Q: error: instance type null does not match any allowed primitive type I am trying to create compute instance in gcp using following yaml file (terraform)
resources :
- type : compute.v1.instance
  name: quickstart-deployment-vm
  properties:
       zone: us-central1-f
       machineType: f1-micro
       disks:
                 - deviceName: boot
                   type: PERSISTENT
                   boot: true
                   autoDelete: true
                   initializeParams:
                             sourceImage: debian-cloud/debian-9
       networkInterfaces:
                 - network:
                   accessConfigs:
                     - name: ExternalNAT
                       type: ONE_TO_ONE_NAT

but receiving following error
ERROR: (gcloud.deployment-manager.deployments.create) Error in Operation [operation-1673778262629-5f24adec6dda7-44a3a3ab-e5cbf301]: errors:
- code: CONDITION_NOT_MET
  location: /deployments/my-deployment/resources/quickstart-deployment-vm->$.properties
  message: |
    error: instance type (null) does not match any allowed primitive type (allowed: ["string"])
        level: "error"
        schema: {"loadingURI":"#","pointer":"/schemas/NetworkInterface/properties/network"}
        instance: {"pointer":"/networkInterfaces/0/network"}
        domain: "validation"
        keyword: "type"
        found: "null"
        expected: ["string"]

So help me to resolve this error

A: The error is stating that the network key needs a string type value, but instead there is a null value. This is accurate as there is no value for that key. We can fix this with the following:
networkInterfaces:
- network: default
  accessConfigs:
  - name: ExternalNAT
    type: ONE_TO_ONE_NAT


text:
Q: WordPress in subdirectory of subdirectory This should be simple - can't figure out where I'm going wrong:
We have WordPress installed in the following location: http://example.com/gallery/cms
and I want the site to be visible at http://example.com/gallery
I have the WordPress Address set to http://example.com/gallery/cms and the Site Address set to http://example.com/gallery
I copied the .htaccess and index.php to the /gallery folder. The .htaccess contains the following code:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /gallery/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /gallery/index.php [L]
</IfModule>

The index.php contains the following code:
define('WP_USE_THEMES', true);
require('./cms/wp-blog-header.php');

The home page loads up fine, but any interior pages kick of a "Not Found" error: http://playstartshere.com/gallery/specs/ yields The requested URL /gallery/specs/ was not found on this server.
Where am I going wrong? I tried changing index.php to:
define('WP_USE_THEMES', true);
require('./gallery/cms/wp-blog-header.php');

but that broke the site entirely.
EDIT: ANSWER
Apache was indeed incorrectly configured; RewriteEngine was not enabled. However, the .htaccess was also wrong. Correct .htaccess for a configuration like what's above is:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /gallery/cms/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /gallery/cms/index.php [L]
</IfModule>

Hope that helps someone else.

A: /gallery/specs/ is matched by this rule:
RewriteRule ^index\.php$ - [L]

which block access
Try /gallery/.htaccess with:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php [L]

without / prepending index.php, apache will search in current directory
edit
Once again with different approach:
set all wordpress URLs to http://example.com/gallery
put all wordpress files in /gallery/cms
put one .htaccess in /gallery/cms
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php [L]

put second .htaccess in /gallery (without index.php)
RewriteEngine On
RewriteCond %{REQUEST_URI} !/gallery/cms
RewriteRule ^(.*)$ /gallery/cms/$1 [L]


text:
Q: How to write $x^{p-1}-1$ as $(p-1)x^{p-2}\cdot g(x)+(p-1)\cdot r(x)$ How to write $x^{p-1}-1$ as $(p-1)x^{p-2}\cdot g(x)+(p-1)\cdot r(x)$? How to find the appropriate polynomials $g(x),r(x)$
$\deg r(x)$ needs to be less than $p-2$
For context I am trying to show that if the caracteristic of the field over which those polynomials lie divides $p-1$ than $x^p-x$ has a multiple root.
I tried to work with $g(x)=x$ but it seems like it's not going to work this way...

A: Over a field of characteristic $\ell$ where $\ell\mid(p-1)$, then
$$x^p-x=x(x^{(p-1)/\ell}-1)^\ell$$
and so certainly $1$ is zero with multiplicity at least $\ell$.


text:
Q: Highlighting for 'f#' tag I have 'f#' in my list of interesting tags. I've just noticed that questions tagged with 'f#' don't get highlighted.
Is this expected? edit: apparently, yes

A: As Tim Stone noted, this is a (relatively) recent change and by design.


text:
Q: How can I Limit or forbid download from my Storage? Every month we have huge number of data download from our Google storage, when we have only about 4Gb pics and docs.
How to understand who use our storage, who and what download and upload in our storage.
How to fix it?
Here it is the examples of
July 2015
Cloud Storage Download US EMEA: 61.511 Gibibytes (Project:API Project) - 7.38
June 2015
Cloud Storage Download US EMEA: 449.487 Gibibytes (Project:API Project) - 53.94
May 2015
Cloud Storage Download US EMEA: 39.645 Gibibytes (Project:API Project) - 4.76

A: You can turn on Access Logging which will provide you a log with every access to your data. This will allow you to see who is downloading your data, when.
You can limit who has access by setting up appropriate Access Control.


text:
Q: How can I send a verification email in Swift 3 with Firebase? How can I send a verification Email with the Firebase Verification Email template to an user when trying to create an account in Swift 3? Until now I have this code:
@IBAction func CreateAccount(_ sender: AnyObject) {

    let username = UserText.text
    let password = PasswordText.text

    FIRAuth.auth()?.createUser(withEmail: username!, password: password!, completion: { (user, error) in
        if error != nil {

            //error creating account
            let alert = UIAlertController(title: "Error", message: "Error creating account", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            self.present(alert, animated: true, completion: nil)
        } else {
            //success
            let vc = self.storyboard?.instantiateViewController(withIdentifier: "mainVC")
            self.present(vc!, animated: true, completion: nil)
        }
    })
}

What I want is to confirm that the user is using a valid email.

A: As the Firebase documentation on sending a password reset email shows:

You can send a password reset email to a user with the sendPasswordResetWithEmail:completion: method. For example:
FIRAuth.auth()?.sendPasswordReset(withEmail: userInput) { (error) in
  // ...
}

A: don't know if you managed but I would use this:
final FirebaseUser user = mAuth.getCurrentUser();
user.sendEmailVerification()
    .addOnCompleteListener(this, new OnCompleteListener() {
        @Override
        public void onComplete(@NonNull Task task) {
            // Re-enable button
            findViewById(R.id.verify_email_button).setEnabled(true);

            if (task.isSuccessful()) {
                Toast.makeText(EmailPasswordActivity.this,
                         "Verification email sent to " + user.getEmail(),
                         Toast.LENGTH_SHORT).show();
             } else {
                 Log.e(TAG, "sendEmailVerification", task.getException());
                 Toast.makeText(EmailPasswordActivity.this,
                          "Failed to send verification email.",
                          Toast.LENGTH_SHORT).show();
             }
    }


text:
Q: MATLAB, how to evaluate multiple indices in one line? I don't know how to explain this better than by giving you an example.
Suppose I have the following array:
a = magic(6)

And then I take a 'slice' of that like this:
a(:,1)

It will print:
35
 3
31
 8
30
 4

Now I want the first number, so I want to write:
a(:,1)(1)

Instead of:
b = a(:,1)
b(1)

Also, is there a way to do something like this (assignment and comparison, i.e. set b, then evaluate against it):
(b = a(:,1))(1)

Ok, here's an update with a function where it isn't trivial to use a(1, 1)
come_on = sprintf('%i, ', magic(3));
come_on(1:end-2)
8, 3, 4, 1, 5, 9, 6, 7, 2

Also, what if I only want the first 4 numbers on magic(3)?
It would be better to write
sprintf('%i, ', magic(3)(1:4))(1:end-2)

instead of tens of lines, MHO.

A: You cannot concatenate indexing as foo(1)(2)(3). However, you can index multiple dimensions at once. So in this case, a(1,1) will give you what you want.


text:
Q: Laravel 8 SQLSTATE[42S02]: Base table or view not found: 1146 Table even though I am trying to create this table I am using Laravel 8. I am trying to create a new table and this table does not exist in database and there are not any other table that has the same name. I did the migration and this is the migration code:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCertificateTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('certificate', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('vac_id');
            $table->time('last_shot_date');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users');
            $table->foreign('vac_id')->references('id')->on('vaccination');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('certificate', function (Blueprint $table) {
            //
        });
    }
}

after doing
php artisan migrate

This is the full error message I get:
   Illuminate\Database\QueryException

  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'vaccinationappointme
nts.certificate' doesn't exist (SQL: alter table `certificate` add `id` bigint un
signed not null auto_increment primary key, add `user_id` bigint unsigned not nul
l, add `vac_id` bigint unsigned not null, add `last_shot_date` time not null, add
 `created_at` timestamp null, add `updated_at` timestamp null)

  at D:\xampp\htdocs\Vaccination_Appointments\vendor\laravel\framework\src\Illumi
nate\Database\Connection.php:692
    688▕         // If an exception occurs when attempting to run a query, we'll
format the error
    689▕         // message to include the bindings with SQL, which will make thi
s exception a
    690▕         // lot more helpful to the developer instead of just the databas
e's errors.
    691▕         catch (Exception $e) {
  ➜ 692▕             throw new QueryException(
    693▕                 $query, $this->prepareBindings($bindings), $e
    694▕             );
    695▕         }
    696▕

  • A table was not found: You might have forgotten to run your migrations. You c
an run your migrations using `php artisan migrate`.
    https://laravel.com/docs/master/migrations#running-migrations

  1   D:\xampp\htdocs\Vaccination_Appointments\vendor\laravel\framework\src\Illum
inate\Database\Connection.php:485
      PDOException::("SQLSTATE[42S02]: Base table or view not found: 1146 Table '
vaccinationappointments.certificate' doesn't exist")

  2   D:\xampp\htdocs\Vaccination_Appointments\vendor\laravel\framework\src\Illum
inate\Database\Connection.php:485
      PDOStatement::execute()

I have tried to do:
php artisan migrate:refresh

and still the same problem. I have not used Models.

A: if you want to create a table with migration, you need to use ::create() instead of ::table()
::table() function tries to alter your table