text:
Q: Unity Multiple Toggle Buttons Reversing I am making a unity project. The situation is that I have two toggle buttons (actually more than two) toggle1 and toggle2 and two gameobjects cube1 and cube2. On start both the toggles are unchecked and gameobjects are SetActive(false). What I want is if both buttons toggle1.isOn && toggle2.isOn then cube1 SetActive and if toggle2.isOn && toggle1.isOn then cube2 SetActive according to toggle orders i.e. which toggle is selected first.
Now the problem is that When I Checked toggle1 then toggle2 in order both cubes appears and when I Checked toggle2 then toggle1  then again both cubes appears....
using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class ToggleToggle : MonoBehaviour {

    public Toggle toggle1;
    public Toggle toggle2;
    public GameObject cube;
    public GameObject cube2;

    // Use this for initialization
    void Start () {
        cube.SetActive (false);
        cube2.SetActive (false);
    }

    // Update is called once per frame
    void Update () {

        // Toggle1 Selected First then Toggle2
        if (toggle1.isOn && toggle2.isOn) {
            cube.SetActive (true);
        }

        // Toggle2 Selected First then Toggle1
        if (toggle2.isOn && toggle1.isOn) {
            cube2.SetActive (true);
        }
    }
}

A: The error in your program is you forget to notify the first button pressed:
public int first;
void Start () {
    cube.SetActive (false);
    cube2.SetActive (false);
    first = 0;
}

    // Update is called once per frame
void Update () {
    if (!toggle1.isOn && !toggle2.isOn) {
        first = 0;
    }

    if (first == 0 && toggle1.isOn) {
        first = 1;
    }

    if (first == 0 && toggle2.isOn) {
        first = 2;
    }

    if (first == 1 && toggle2.isOn) {
        cube.SetActive (true);
    }

    if (first == 2 && toggle1.isOn) {
        cube2.SetActive (true);
    }
}

A: If I understand well, you want to enable only one GameObject based on multiple Toggles.
The first ticked determines which GameObject.
So you have to store the first ticked Toggle.
Here is an example :
public class ToggleToggle : MonoBehaviour {
/*
    public Toggle toggle1;
    public Toggle toggle2;
    public GameObject cube;
    public GameObject cube2;
*/

    public Toggle[] toggles;
    public GameObject[] cubes;

    public static Toggle firstTickedToggle;

    void Start ()
    {
        for (int i = 0; i < cubes.Length; i++)
        {
            cubes[i].SetActive(false);
        }
    }

    public void OnToggleClick(Toggle toggle)
    {
        if (toggle.enabled)
        {
            if (firstTickedToggle == null)
                firstTickedToggle = toggle;

            int toggleIndex = 0; // Index of the first clicked toggle

            // Check if all toggles are ticked
            for (int i = 0; i < toggles.Length; i++)
            {
                // If one is not ticked
                if (!toggles[i].enabled)
                    return;
                if (toggles[i] == firstTickedToggle)
                    toggleIndex = i;
            }

            // Here all toggles are ticked
            cubes[toggleIndex].SetActive(true);
        }

        else
        {
            for (int i = 0; i < toggles.Length; i++)
            {
                // If one toggle is still ticked, don't do anything
                if (toggles[i].enabled)
                    return;
            }

            // If all toggles are unticked, remove the reference to the first ticked
            firstTickedToggle = null;
        }
    }
}

All toggles need a OnValueChanged


text:
Q: How to git grep only a set of file extensions How do you perform a git grep and limit the files checked to a set of files. I would like to be able to grep the contents of .cpp and .h files looking for MyFunc. eg:
git grep "MyFunc" -- *.[hc]*

However this also matches, .c files and .cs files.

A: This can be achieved when using git bash in Windows by using:
git grep "MyFunc" -- *.{cpp,h}

or even simpler:
git grep "MyFunc" -- *.cpp *.h

The explanation of pathspec on the git glossary mentions that patterns are matched using fnmatch(3). Which matches patterns (including multiple characters) as described by Shell and Utilities volume of IEEE Std 1003.1-2001, Section 2.13.1 and leads to basic regular expressions matching multiple characters and gave me the first solution.
Further research lead me to the second solution by looking into documentation on glob.

A: Use:
git grep "MyFunc" -- '*.cpp' '*.h'

The quotes are necessary so that git expands the wildcards rather than the shell. If you omit them, it'll only search files in the current directory, rather than including subdirectories.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Autocompletetext и Sqlite Здравствуйте, возник вопрос.  Есть текстовое поле с автозаполнением и возможностью редактирования вводимого текста. Автозаполнение идет из базы данных. Но я никак не могу, сделать так, чтобы появлялись не все записи из базы данных, а только относящиеся к вводимому в поле тексту.
Файл MainActivity:
      final AutoCompleteTextView Search = (AutoCompleteTextView) findViewById(R.id.name);
     int[] to = new int[]{android.R.layout.select_dialog_item};
     mCursor = managedQuery(
                           NameProvider.CONTENT_URI, mContent, null, null, null);
     SimpleCursorAdapter scaComments = new SimpleCursorAdapter(this,R.layout.auto_complete_item,
                   mCursor,new String[] {NameDbHelper.NAME},new int[]{R.id.text1});
    scaComments.setCursorToStringConverter(new CursorConverter());
    Search.setAdapter(scaComments);

    scaComments.setFilterQueryProvider(new FilterQueryProvider(){

      public Cursor runQuery(CharSequence constraint)
        {

    Cursor cursor = NameDbHelper.getMatchingStates((constraint != null ? constraint.toString() : null));
                    return cursor;
                    }
                    });

И файл NameDbHelper
 public class NameDbHelper extends SQLiteOpenHelper implements BaseColumns {

public static final String TABLE_NAME = "names";
public static final String NAME = "name";

private static SQLiteDatabase db;
public NameDbHelper(Context context) {
    super(context, NameProvider.DB_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE " + TABLE_NAME
            + " (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
            + NAME + " TEXT);");

    ContentValues values = new ContentValues();

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
    onCreate(db);
}

public static Cursor getMatchingStates(String constraint) {

    // TODO Auto-generated method stub
    return db.query(TABLE_NAME, new String[] { "NAME"}, "constraint like " + "'%"+constraint+"%'", null, null, null, null);
    }

}
Подскажите, пожалуйста, в чем моя ошибка ?
Предполагаю, что ошибка в

       return db.query(TABLE_NAME, new String[] { "NAME"}, "constraint like " + "'%"+constraint+"%'", null, null, null, null);

A: db.query(TABLE_NAME, new String[] { "NAME"}, "NAME like " + "'%"+constraint+"%'", null, null, null, null);

В обычном SQL это будет аналогично запросу:
select name from NAMES where name like '%constraint%'

А вообще лучше написать:
db.query(TABLE_NAME, new String[] { "NAME"}, "NAME like ?", new String[]{ "'%"+constraint+"%'"}, null, null, null);

Будет работать быстрее, поскольку конструкция с "?" предполагает прекомпиляцию выражения на стороне SQLite при первом выполнении


text: Q: Django dynamic fields view This post answers how to dynamically return a subset of fields based on the field section in the URL. This is done by creating a dynamic serializer. This works great against a ModelViewSet, but will this affect the query to the database in any way, or will it still query all the fields, and then only the selected fields are returned to the client? If it is the later, is it possible to make it so that the query to the database is only for the specific fields if any is provided, or will I have to create a view for each query I wish to make?


text:
Q: How to write expect in shell This is continuation to my previous question :Spawn command not found
After referring to few old posts, I have written those commands, If its wrong, then how I can run ssh to remote server and run some commands ?

A: One possiblity is: create an expect-syntax file, and call that via a shell script:
 #!/bin/bash
 expect -f my-file.exp $1 # parameter 1 is the server name

In the my-file.exp you would only have expect commands:
spawn ssh "username@[lindex $argv 0]"  # param 1 : server name
                                # expect now reads the input and does what you tell it on certain patterns

expect {
  "password:" { send "my-password\r"; send "do_this_command\r"; send "do_that_command\r"; exp_continue; }
  "done" { send_user "exiting"; }
}

This example logs on to the server sending the clear-text password, then sends some command and continues.
If it reads "done" from the input, it terminates, Otherwise it will time out after a few seconds.
As long as you do a "exp_continue", it stays inside the expect {}-loop, matching input and doing the appropriate output.

A: You can also use an expect shebang in your shellscript and write an expect script.
#!/usr/bin/expect -f
spawn ssh localhost
expect "password: "
send "password\r"
expect "{[#>$]}"         #expect several prompts, like #,$ and >
send -- "command.sh\r"
expect "result of command"
etc...


text:
Q: Combinatorial restriction on choosing adjacent objects I am having trouble understanding an approach to the following problem.

Suppose 14 books are aligned in a bookcase. How many ways can we choose 5 books so that no adjacent books are chosen?

I think my Labeling method is the best, please show me how to proceed to a solution from the best method.
Approaches:
Brute Force Method: Choose a book (not the first or the last) this can happen in 14 different ways, choose the second book (not the first or last) this can happen in 8 ways. And this is where I stopped because I realized I am not accounting for the first and last books, as well as the fact that I am introducing order.
Inclusion-Exclusion: Count the total number of ways to choose $5$ books. This is $14\choose 5$. Subtract the number of ways of choosing all non-adjacent books. This means that we always choose an adjacent book. This again leads to the complication of choosing or not choosing the first or last books in the alignment.
Labeling: My idea here is to label 5 books by bars and then 9 x's denoting books that were not chosen. The problem then reduces to finding the number of sequences of x's and bars such that no two bars are adjacent. If no two bars are adjacent, this means that there is an x between each bar, and there may be x's at both ends of the alignment. But, how do I count this?

A: Your labeling approach is indeed best. There are $4$ spaces between bars, each of which must contain a book, and a space at each end, each of which may contain no books. If $x_k$ is the number of books in space $k$ for $k=0,1,\dots,5$ (with the spaces numbered from left to right), you want the number of solutions in non-negative integers to the equation
$$x_0+x_1+x_2+x_3+x_4+x_5=9$$
subject to the condition that $x_1,x_2,x_3,x_4\ge 1$. This is essentially the same as counting the solutions in non-negative integers to
$$x_0+x_1+x_2+x_3+x_4+x_5=5\;:$$
we just pretend that we've already placed one book in each internal space, thereby accounting for $4$ of the $9$ extra books, and allocate the remaining $5$ arbitrarily. The answer is therefore
$$\binom{5+6-1}{6-1}=\binom{10}5\;.$$
(See this article if you've not seen that before at all, though I suspect that you have.)

A: Let me generalize (your question is obtained for $n = 14$ and $k = 5$):

Let $n$ and $k$ be nonnegative integers. Let $\left[n\right] = \left\{1,2,\ldots,n\right\}$. A set $S$ of integers is called lacunar if it contains no two consecutive integers (i.e., there exists no $s \in S$ satisfying $s+1 \in S$).
Find the number of all $k$-element lacunar subsets of $\left[n\right]$.

The answer is $\dbinom{n-k+1}{k}$ when $k \leq n+1$ (and obviously $0$ in all other cases). For a proof, see the solutions to Exercise 3 (a) on UMN Fall 2017 Math 4707 homework set #2. The first solution is the bijective argument some are alluding to in this thread. The second is a straightforward but annoying ("thanks" to the $k \leq n+1$ condition) induction on $n$.
Your $n = 14$ books correspond to the $n$ elements of $\left[n\right]$, in the order in which they appear on the shelf.

A: We describe your labelling method in another way. Imagine taking out $5$ books. But now we space out the unchosen books, so that no one will know where the $5$ books came from. There are then $10$ "gaps" that our $5$ books could have come from (this includes the "endgaps"),
The actual books taken came from $5$ of these gaps, which can be chosen in $\dbinom{10}{5}$ ways.

A: If you are looking for an even easier way to come up with the answer, a formula for choosing k out of n without any two of the k adjacent to one another is $\binom{n-k+1}{k}$. It is easy to come up with this expression by observing the properties of the problem and then coming up with a recurrence relation that satisfies the restriction of "no adjacent choices". There is a much more detailed description here.


text:
Q: How can I receive sms messages with pushbullet? I can't figure out how to receive sms messages from my phone to my computer using pushbullet. Every time I try to receive pushes I only get the pushes from my laptop and not my phone. I want receive input from my phone then output my sending a text back via pushpullet.
Here is my code so far (not working)
from pushbullet import Pushbullet
api_key = "my api key here"
pb = Pushbullet(api_key)
device = pb.devices[1]
print(pb.devices)
while True:
    hello = pb.chats
    print("hello ", hello)
    hi = pb.get_pushes()
    print(hi)
    sms_message = # Can't figure this out
    author_ph = # Can't figure this out


text:
Q: Find a path in G which cross all the edges in $A\subseteq E$ Given a directed graph $G=(V,E)$ and a subset $A\subseteq E$. I need to find an efficient algorithm to find a path (it doesn't have to be a simple one) which cross all of the edges of A, or inform that there is no such path. The path can cross other edges which are not in A.
Sadly, I didn't come up to any smart algorithm.
I'd really appreciate your help with this

A: You can't hope for a better worst-case behavior than $O(|A|\times|E|)$, because just printing the solution can take that long -- consider a graph consisting of a linear sequence of nodes
$$0\to 1\to 2\to\cdots\to n$$
plus an edge from each node back to $0$ with $A$ consisting of these back edges.
On the other hand, $O(|A|\times|E|)$ can easily be achieved:

*

*Partition the graph into strongly connected components, and topologically sort the components.

*Handle the edges in $A$ in order of the components their starting vertices belongs to. Within each component, treat internal $A$-edges first (in some arbitrary order), then any $A$-edge that leaves the component. If there are more than one leaving $A$-edge, there is clearly no solution.

*For every $A$-edge other than the first one, do a straightforward $O(|E|)$-time search for a path connecting the end of the previous one with the front of the current one.

*If any $A$-edge cannot be connected to the previous endpoint, it must be because there are $A$-edges in two different connected components such that neither can be reached from the other. In that case there is obviously no solution.


text:
Q: Pandas: matrix correllation for words I am new in pandas and python. I want to find common words for my data set. e.g i have list of companies ["Microsoft.com", "Microsoft", "Microsoft com", "apple" ...] etc. I have around 1M list of such companies and i want to calculate correlation between them to find the relevance for the words e.g Microsoft.com, Microsoft, Microsoft com there are common words.
This is what i did but its very slow:
import hashlib
companies = pd.read_csv('/tmp/companies.csv', error_bad_lines=False)
unique_companies = companies.groupby(['company'])['company'].unique()
df = DataFrame()

for company in unique_companies:
   df[hashlib.md5(company).hexdigest()] = [{'name': company[0], 'code': [ord(c) for c in company[0]]}]

rows = df.unstack()
for company in rows:
   series1 = Series(company['code'])
   for word in rows:
      series2 = Series(word['code'])
      if series1.corr(series2) > 0.8:
        company['match'] = [word['name']]

can anyone please guide me how to find matrix correlation for the words ?

A: I don't think there's a corr function that will work for strings - only numerics.
If you can somehow compress your words into meaningful numeric values that preserves the "closeness" of one against another, you might then be able to "corr" them, but other options are available.
Hamming Distance is one (basic) method, but slightly better is calculating the Levenshtein difference: http://en.wikipedia.org/wiki/Levenshtein_distance
It's tricky but one way of trying this would be to build a matrix of m x n cells. Where m is the number of unique words in your first wordlist, and n is the number of unique words in the secornd wordlist - then calculate the Hamming, or Levenshtein distances between row/column identifiers.
There are python modules that package up the distance-algorithms for you -
e.g. https://pypi.python.org/pypi/python-Levenshtein/
Or you could write your own, I think the packaged ones are likely to be faster as they're C'ified.
So, assuming the Levenshtein module (I don't know, as have not used it) provides a function say getLev (word1, word2) that generates a numeric score, you should be able to feed in the contents from two wordlists from sources 1 and 2. If you make sure your inputs are already filtered for uniqueness, and maybe sorted alphabetically, that would help too.
Feed them into a matrix generation function.
Here, I've imported numpy as np and am using that module for speed
def genLevenshteinMatrix(wordlist1, wordlist2):
    x = len(wordlist1)
    y = len(wordlist1)
    l_matrix = np.zeros(( x, y))
    for i in range( 0 , x ):
        x_word = wordlist1[i]
        for j in range ( 0 , y ):
            y_word = wordlist[j]
            l_matrix[i][j] = getLev ( x_word, y_word )

Something like that should allow you to generate a matrix that stores a measure of which words are most like which other words.
Once that's created, you can interrogate it using a function like this:
def interrogate_Levenshtein_matrix (ndarray_x, wordlist1, wordlist2, float_threshold):
    l = []
    x = len(ndarray_x)
    y = len(ndarray_x[0])
    for i in range(0 , x ):
        for j in range(0 , y ):
            if ndarray_x[i][j] >= float_threshold:
                l.append ([(wordlist1[i],wordlist2[j]),ndarray_x[i][j]])
    return l

And that will output a list of words that are "close" (i.e. have a lower distance) as measured by the Levenshtein function used earlier, as a list, containing a list of the two similar words.
You might need to trim it down somehow, as I think you'll get all like-combinations twice, i.e. ['word','work'] as one return value, and ['work','word'] as another.
As you develop the code, you could swap in different correlation functions and try different threshold values.


text:
Q: How to get hold of graph from tf.function in tensorflow 2.0? Previously, sess.graph was used as a handle to push things to tensorboard.
There is no current replacement AFAIK. Visualizing graphs is fundamental.
How can we viz graphs in tensorflow 2.0? Must be some hook into the functions.

A: Tensorboard works in 2.0. This example for keras and this without


text:
Q: TeX Gyre fonts in XeLaTeX and LuaLaTeX: call by name or file name? Is there any downside of using file names with \setmainfont, except for the fact that it takes more typing?
I ask because I am experiencing problems with using names for TeX Gyre fonts on my Linux Mint box: as explained here, XeLaTeX on Linux will not find TeX-installed fonts by name. Hence, I installed the fonts also system-wide (Ubuntu package tex-gyre), but the font names are different from my Windows box: the spaces are gone, so "Tex Gyre Termes" becomes "TeXGyreTermes" etc. This means that using names, the code becomes system-dependent :-(
(By the way, should this be considered a bug and reported to the maintainers of the tex-gyre package?)
On the other hand, calling the font by file name should work as long as the font file names are the same - can one trusts that? And is there any other potential problem with using file names?
Thanks

A: I discussed some of the problems and choices in my article in TUGboat 117 (vol 37 no 3, 2016) at http://tug.org/TUGboat/tb37-3/tb117inn.pdf — it's basically down to how you work, what your workflow is, and how much you wish to trade off the conveniences of one against the inconveniences of the other. Basically, using filenames (and paths) ties your document to one directory structure, but it's more likely to be accurate for you. Using font names is supposed to be more system-independent, but they are sometimes weird and not always obvious.


text:
Q: How can I create a React Js Layouts Can someone help me with create ReactJs Horizontal and Vertical layout component.
It would be great if you can provide example or tutorial.

A: I found useful npm repository.
https://www.npmjs.com/package/react-layout-pane


text:
Q: Using JavaScript to call and display JSON data from a URL This is my html code to fetch data from the link which contains json data. But it is not working so can anyone tell me why?

 <button id="btnjson">Load!!!</button>

ID:

Item Name:

Item Price:

A: The HTTP response of http://waitrapp.co/bipin/practice.php does not contain proper CORS headers, if you set this in the php file it should work:
header("Access-Control-Allow-Origin: *");

This may be too simplified, so take a look at this SO post: https://stackoverflow.com/a/9866124/441907
Also as Salec pointed out you JSON is invalid, you are missing enclosing brackets [] and commas between the elements:
[
    {
        "ID": "10",
        "Item_Name": "Pizza",
        "Item_Price": "2.99",
        "Date_Created": "2014-10-01 08:27:41"
    },
    {
        "ID": "11",
        "Item_Name": "Burrito",
        "Item_Price": "2.99",
        "Date_Created": "2014-10-01 09:13:03"
    },
    {
        "ID": "12",
        "Item_Name": "Burger",
        "Item_Price": "4.99",
        "Date_Created": "2014-10-06 19:56:01"
    },
    {
        "ID": "13",
        "Item_Name": "Steak",
        "Item_Price": "10.99",
        "Date_Created": "2014-10-06 19:56:17"
    }
]

A: Your Json doesn´t look to be ok.
Try to check it first: http://jsonformatter.curiousconcept.com/
You need to create an array of Objects


text:
Q: Linux "ls -Z" shows question mark for security context I've got some files that aren't being served on a site, and assuming it was a permissions issue I ran ls -Z but keep seeing ? in place of the security context:
-rw-rw-r--  pete pete ?                                index.cfm

I get this running sudo as well. Can anyone explain what the ? means or what I need to do to fix the file?
I've tried using sudo chcon system_u:object_r:httpd_config_t:s0 index.cfm to match the other permissions of files in the folder, but that doesn't help. Also if I try to recreate the file I get the ? again
cat index.cfm > index.bkp
sudo ls -Z
-rw-rw-r--  pete pete ?                                index.bkp
-rwxrwxrwx. pete pete system_u:object_r:httpd_config_t:s0 index.cfm
mv index.bkp index.cfm
-rw-rw-r--  pete pete ?                                index.cfm

A: The meaning of the exclamation mark is only given in ls info page, not in its man page:

'-Z'
'--context'
'--scontext'
'--lcontext'
'--format=context'
Display the SELinux security context or '?' if none is found.  '-Z'
counts as format option and enables displaying of SELinux context.
'--scontext' prints SELinux context left to the file name.
'--lcontext' prints long format with SELinux context in the middle.
'--context' prints permissions, user/group, context and file name
(in comparison to '--lcontext', omits size, modification time and
number of hardlinks).

Thus, this means that no security context was added to the file. And the fact that it still has no security context when you re-create the file indicates that the parent directory has no security context that can be inherited from.


text:
Q: How can I find out if a `QPixmap` has transparency? I have some QGraphicsPixmapItem that will contain images...  of any kind.
I will have to perform certain processing, that is very simple if the image contained in the item is fully opaque, but more complicated if there is transparency. So I want to separate these 2 situations.
How can I find out if a QGraphicsPixmapItem or a QPixmap has transparency ?
(the only thing I found so far is QPixmap::mask():

Extracts a bitmap mask from the pixmap's alpha channel.
  Warning: This is potentially an expensive operation. The mask of the pixmap is extracted dynamically from the pixeldata.

not sure what i do with it...
or I can iterate myself through pixel data till I find a pixel with some transparency... either version seems ineffective)
Update:
After implementing it myself, I found an older similar question:
Checking if a QImage has an alpha channel
(seems nobody else found an alternative to iterating through all pixel data)


text:
Q: Difference between these two standard deviation formulas? Today I started reading statistics and I came across these two S.D formulas:
$$\sqrt{\frac 1 n \sum (X - \overline X)^2} \textrm{ and } \sqrt{\frac 1 {n-1}\sum (X - \overline X)^2}$$
What is the difference between these two and in which situations I should use them?

A: The first one is used for population and second one is for sample.
What is the difference between a population and a sample?
A sample is a subset of people, items, or events from a larger population that you collect and analyze to make inferences. To represent the population well, a sample should be randomly collected and adequately large.
To understand the basic foundation for hypothesis testing and other types of inferential statistics, it's important to understand how a sample and a population differ.
A population is a collection of people, items, or events about which you want to make inferences. It is not always convenient or possible to examine every member of an entire population. For example, it is not practical to count the bruises on all apples picked at an orchard. It is possible, however, to count the bruises on a set of apples taken from that population. This subset of the population is called a sample.
If the sample is random and large enough, you can use the information collected from the sample to make inferences about the population. For example, you could count the number of apples with bruises in a random sample and then use a hypothesis test to estimate the percentage of all the apples that have bruises.

A: Neither of these is the actual definition of standard deviation. If you have a random variable $X$, the standard deviation $\sigma$ is defined by
$$
\sigma^2 = E [ (X-EX)^2 ]
$$
where $E$ denotes the expected value (i.e., if $X$ takes $k$ values $a_1, ..., a_k$ with probabilities $p_1,...,p_k$ respectively, $EX=\sum_{i=1}^k p_i a_i$). Of course, $\sigma^2$ is called the variance. When people refer to "population" quantities, they mean taking expectations as above.
The 2 formulae given are ways to estimate $\sigma$ when you have observations $X_1,..., X_n$ that are independent and drawn from the same distribution as $X$ (which you do not know the standard deviation of). Often it is assumed that the distribution of $X$ (or any of the $X_i$) is Gaussian, but with unknown mean and variance; in this situation, you say that you have a parametric statistical model for the unknown distribution from which you have data. The goal of statistical inference is to figure out something about the unknown distribution from the data, and if you are looking at IID data from an unknown Gaussian distribution, it is not hard to show that the sample mean $\bar{X}$ is the best way to estimate the unknown mean. (When people refer to "sample" quantities as opposed to "population" quantities, they mean these are quantities computed from a data sample.) When it comes to estimating the unknown standard deviation, there are various natural candidates that arise, and the 2 formulae mentioned in the question are among them. As pointed out in a comment, they are almost the same when the sample size $n$ is large, as one should expect (since when $n$ is large, we want both to converge to the unknown standard deviation, or they would be rather useless estimates). The main difference is that when your goal is estimating the variance rather than the standard deviation, the formula with $1/n$ is the maximum likelihood estimate but is biased, whereas the formula with $1/(n-1)$ is unbiased. Here unbiased means that the expected value of the estimated variance is equal to the unknown variance; it was a traditional criterion that people considered important some decades ago but is no longer considered that critical these days.

A: The first one is used, if $\bar X$ is indepently calculated.
This second one, if you compute $\bar X  = \frac{1}{N} \sum X$ with the data you are also using for the S.D.
This is important for the epxectation of those to be equal fo the real S.D.


text:
Q: How to set a dynamic task as a defaultTask Sorry for the newbie question, but I have yet to see an example or question related to specifying dynamic tasks as a defaultTask in a gradle project.
So, how do I specify the dynamic $boostLibName tasks as the defaultTasks?
build.gradle
defaultTasks 'whatgoeshere'

ext {
    // The boost directory, which changes according to version
    // there should be a better way to do this
    boostDir = './boost_1_53_0'

    // The list of boost libraries that we want to build
    boostLibs = ['smart_ptr', 'filesystem', 'array.hpp']
}

// Create a task to build each boost library
boostLibs.each { def boostLibName ->
    println boostLibName
    tasks.create(name: boostLibName, dependsOn: aBoostBcp, type: Exec) {

        workingDir project.boostDir

        def b2compiler = 'toolset=' + System.properties['boost_toolset']
        def b2target = '--with-' + boostLibName
        def cmd

        if(System.properties['platform'] == 'windows') {
            //on windows
            cmd = ['cmd', '/c', '.\\b2', b2compiler, b2target]
        } else {
            //on unix and mac
            cmd = ['./b2', b2compiler, b2target]
        }

        // set exec commandLine
        //commandLine cmd.split()
        commandLine 'cmd', '/c', 'echo', "Command to execute: $cmd"
    }
}

Background
I am trying to implement a cross-platform Boost C++ build in gradle, where you bootstrap the build, build bcp, use bcp to customize our namespace, and, finally, build each of our boost libraries that we depend on.

A: It's defaultTasks = boostLibs, and has to come after declaring boostLibs. Alternatively, you can declare a task named build that depends on boostLibs, and make "build" the default task.
Unless you need to access these properties from other build scripts, you can turn them into local variables (e.g. def boostLibs = ... instead of ext.boostLibs = ....)


text:
Q: Determining median values with nested IF and AND array formulas I'm trying to create two similar array formulas:
One is to determine the median value of the cells in a column (B), but only if there are both corresponding blank values in column J, and there are numeric values in column D. (D and J are in separate sheets.)
The other formula is the do the same thing, except it will only determine the median for the cells in B for which the corresponding cells in column J are not blank.
I should note I am making sure to enter them in with command-shift-enter, since they are array formulas. However, it's coming out to zero for both of them. I've tried for a long time and can't figure out why. I'm new to Excel formulas, so please let me know if I should clarify my question.
First formula:
=MEDIAN(IF(

 AND('Raw Data'!$J$3:'Raw Data'!$J$999="", ISNUMBER('Raw Data'!$D$3:'Raw Data'!$D$999)),

 B$6:B$1002))

Second formula:
=MEDIAN(IF(

 AND(NOT(ISBLANK('Raw Data'!$J$3:'Raw Data'!$J$999)), ISNUMBER('Raw Data'!$D$3:'Raw Data'!$D$999)),

 B$6:B$1002))

A: Array equivalent of AND is multiplication *:
=MEDIAN(IF(('Raw Data'!$J$3:$J$999="")*
            ISNUMBER('Raw Data'!$D$3:$D$999),
            B$6:B$1002)
       )

with array entry (CTRL+SHIFT+ENTER).
For second formula:
=MEDIAN(IF(NOT(ISBLANK('Raw Data'!$J$3:$J$999))*
           ISNUMBER('Raw Data'!$D$3:$D$999),
           B$6:B$1002)
       )

also with array entry.

Explanation why AND not working.
What you expect is that AND({TRUE,FALSE,FALSE},{TRUE,TRUE,FALSE}) returns {TRUE,FALSE,FALSE}.
However, AND takes array of boolean values and returns single boolean value - which indicates whether all values are TRUE or FALSE.
So, AND({TRUE,FALSE,FALSE},{TRUE,TRUE,FALSE}) returns FALSE because not all values are TRUE.
But, multiplication  {TRUE,FALSE,FALSE}*{TRUE,TRUE,FALSE} works exactly as you need it - it returns {TRUE*TRUE,FALSE*TRUE,FALSE*FALSE} = {TRUE, FALSE, FALSE}


text:
Q: How can I do algabraic sum? I would like to know how I can sum an algebraic sum.
For example, I have a function with two parameters:

    function sumAlga(paramA, paramB) {
        return paramA + paramB;
    }

How I should do it for algebraic sum in JavaScript?

A: Incorrect Code
As "don't angry me" has said in the comments, you have return paramA + paramBM not return paramA + paramB so that should fix that (assuming that was an unintentional typo, correct me if we're wrong).
More than two arguments
To accomplish this with  any number of parameters you could do the following,
function algebraicSum() {

    var sum = 0;
    for (var i = 0; i < arguments.length; ++i) {
        sum += arguments[i];
    }
    return sum;

}

Usage
algebraicSum(1,2,3,4) = 10;
algebraicSum(1,-2,3) = 2;

A: you can try something like this:
var age_child = parseInt(10);
var age_gap = parseInt(10);
alert(age_child+age_gap);
Unlike Java or C, which are strongly typed languages, Javascript is smart and hence is also called a weakly typed language. You don't have to specify the data-type of your variable while declaring it. but in this case, you should specify the data type to match with your operations.

A: The main purpose is to have a function which could be used as callback for Array#reduce, for example.
An array with values could be summed by taking the function and a start value of zero (this is necessary, if an empty array or an array with only one item is supplied).

function add(a, b) {
    return a + b;
}

console.log([1, 2, -5].reduce(add, 0));
console.log([1].reduce(add, 0));
console.log([].reduce(add, 0));

The following code uses an arrow function, which has some differences to the standard function, but is sometimes shorter.

const add = (a, b) => a + b;

console.log([1, 2, -5].reduce(add, 0));
console.log([1].reduce(add, 0));
console.log([].reduce(add, 0));


text:
Q: Why does @RequestBody not work in this SpringMVC Ajax Form Post for an Object Param? Just curious, the following SpringMVC handler for an Ajax POST Request which submits a serialized form doesn't work and throws "Unsupported Media Type" (415).
@PostMapping("/myapp/add")
public boolean add(@RequestBody Person person) throws Exception { .. }

However, after changing @RequestBody to @ModelAttribute, it does work.
@PostMapping("/myapp/add")
public boolean add(@ModelAttribute Person person) throws Exception { .. }

I thought that @RequestBody/@ResponseBody were appropriate for Ajax-handling SpringMVC methods, but that @ModelAttribute was for regular form submission. But in this Ajax POST Request the @ModelAttribute works.
Ajax is called from JS as
$.ajax({
       type: "POST",
       url: '/myapp/add',
       data: $("#myform").serialize(), // serializes the form's elements
       dataType : "json"
     })
     .done(function(data) {
         alert('Success!');
     });

There is a form which is getting serialized/submitted,
<form:form id="myform" .. >
   <!-- .. -->
</form:form>

The serialized DTO object is fully valid. It has an empty constructor, and implements Serializable, and backs all the form fields.

A: is that Jquery? According to the docs: The .serialize() method creates a text string in standard URL-encoded notation. So this is not JSON.
Serialize
Perhaps you can try this
data : JSON.stringify( $(myForm).serializeArray() );


text:
Q: Ext.Panel display error using custom css borders I have created a JSfiddle to let you show the issue...
http://jsfiddle.net/mrgamer/u3Z48/
element.width of x-panel-body is incorrectly calculated, in the example above it's set on 340px, instead to CORRECTLY show the borders i've set should've been set to 338px!
Screenshots to clarify even more:
How it is:

How it should be:

I understand this is a really tiny 'issue', still i don't know how to correct it, it's annoying to have such display errors in a overused component like Ext.Panel.

A: Try the following
.x-panel-body .body_border{
    padding: 2px;
    border: 1px solid red;
    margin: 1px;
}

A: To solve the problem is enough defining the width in the style config, like this:
var panel1 = new Ext.Panel({
    title: 'Inner Panel',
    height: 300,
    style: {width: '350px'},
    border: false,
    cls: 'panel_class',
    bodyCssClass: 'body_border'
});

It's not as clean as possible, but i think it's a decent solution to the ExtJS miscalculation!


text:
Q: Why is drawing contours not working in image after erosion and dilation? I have and portrait image. To which I:

*

*Convert to Grayscale

*Then convert to binary

*Then I used morphological erosion operation.

*Then I used morphological dilation operation.

Now, as last process, I am trying to find out the contours and drawing them. However, contours are getting found and drawn too, but, it is only getting drawn in white color, which made it looked like, contours is not drawn at all. What am I doing wrong??
Here is my code:
import numpy as np
import cv2

img = cv2.imread("Test1.jpg")
image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow("GrayScaled", image)
cv2.waitKey(0)

ret, thresh = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY_INV)
cv2.imshow("Black&White", thresh)
cv2.waitKey(0)

kernel1 = np.ones((2,2),np.uint8)
erosion = cv2.erode(thresh,kernel1,iterations = 4)
cv2.imshow("AfterErosion", erosion)
cv2.waitKey(0)

kernel2 = np.ones((1,1),np.uint8)
dilation = cv2.dilate(erosion,kernel2,iterations = 5)
cv2.imshow("AfterDilation", dilation)
cv2.waitKey(0)

contours, hierarchy = cv2.findContours(dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cv2.drawContours(dilation, contours, -1, (255, 0, 0), 2)
cv2.imshow("Contours", dilation)
cv2.waitKey(0)

cv2.destroyAllWindows()

Here are images step by step:
Original Image:

GrayScaled Image:

Binary Image:

After Erosion:

After Dilation:

Contour:

I am defining the color of the contours boundary to be red in above code. So, why is it not showing red boundaries??


text:
Q: Can I run a .bp/.meta graph generated by single node tf.sess on a distributed environ with multi-ps/worker nodes? Will future versions of tensorflow provide a way to run the tensorflow graph generated by single node tf.sess on a distributed environments with multiple ps nodes and worker nodes through python interfaces?
Or is it supported right now?
I am trying to build my tf.graph on my notebook (single node) and save then graph into a binary file,
and then loading the binary graph into a distributed environment (with multiply ps and worker nodes) to train and verify it. It seems it is not supported now.
I tried it on tensorflow-0.10 and failed.
By using
tf.train.write_graph(sess.graph_def, path, pb_name)

interface: The graph saved is not trainable as loading the .pb file through import_graph_def will only g.create_ops according to the .bp file but not add then into ops.collections. So the graph loaded is not trainable.
By using tf.saver.save to save a .meta file: The loaded graph cannot fit into the distributed environment as devices assignment is messy.
I tried the
tf.train.import_meta_graph('test_model.meta', clear_devices=True)

interface to let the load clean the original device assignment and let the with tf.device(device_setter) reassign the device for each variable, but there is a problem as operations belonging to Saver and Restore still can not be assigned correctly. When creating operations for Saver and Restore ops through g.create_op inside import_graph_def called by import_meta_graph, the device_setter will not assign ps node to these ops as their name is not Variable.
Is there any way to do so?


text:
Q: Why isn't Validation a Monad? an example use case:
def div2(i: Int): Validation[String, Int] =
    if (i%2 == 0) Validation.success(i/2)
    else Validation.failure("odd")

def div4(i: Int) = for {
    a <- div2(i)
    b <- div2(a)
} yield b

error: Unable to unapply type scalaz.Validation[String,Int] into a type constructor of kind M[_] that is classified by the type class scalaz.Bind
I guess the error is caused by the compiler can't find a Monad instance for Validation[String, Int]
I can make one for myself, like:
object Instances {
implicit def validationMonad[E] = new Monad[({type L[A] = Validation[E, A]})#L] {
    override def point[A](a: => A) =
        Validation.success(a)
    override def bind[A, B](fa: Validation[E, A])(f: A => Validation[E, B]) =
        fa bind f
}
}

but why doesn't Validation have it already? after all, Validation already has the bind method defined.
moreover, I can't have import Validation._ and import Instances._ together anymore (this took me looong to figure out...), because of another complicated error...
ambiguous implicit values: something like both validationMonad (my instance), and method ValidationInstances1 in trait ValidationInstances2... both match some Functor of Validation...
should I modify the source of scalaz? or I'm completely missing something~?
please help~
I'm using scalaz 7.0.0-M2

A: The issue is that the applicative functor as implied by the monad does not equal the actual applicative functor

A: As discussed in the Scalaz group, the problem seems to be that ap would accumulate errors whereas (pseudo-)monadic composition would only operate on the value part of Validation.
Therefore, one cannot be expressed in terms of the other and thus no monad instance exists for Validation.


text:
Q: Write size of a byte array (C# winforms) I am writing some content to a binary file. one item is an image, so converting image in to a byte array and writing it as below.
 BinaryWriter bw = (BinaryWriter)writer;
 WritePropertyTag(property); //IMAGE_TAG
 bw.Write((short)(sizeofshort + imagedata.Length + (writesize ? sizeofshort : 0)));
 if (writesize)
 {
     bw.Write((short)(imagedata.Length));
 }
 bw.Write(imagedata);

and reads it back with the below code:
short datasize = binReaderIn.ReadInt16();
byte[] data = new byte[datasize];
binReaderIn.Read(data, 0, datasize);
Image img = (Bitmap)((new ImageConverter()).ConvertFrom(data));

The above works very well if the byte array is relatively smaller (Short numbers).
When we want to store larger images (with approx byte array size 25k) it fails. I tried using long instead of short in the above code blocks and read with ReadInt64() method, but not getting the right size. Please help. Thanks.

A: BinaryWriter bw = (BinaryWriter)writer;
WritePropertyTag(property);
bw.Write((uint)(sizeofshort + data.Length + (writesize ? sizeofshort : 0)));
if (writesize)
{
   bw.Write((uint)(data.Length));
}
bw.Write(data);

Using uint instead of short solved the problem.


text:
Q: linked list of objects without duplicates (C++)? I've developed a simple template linked list.. my method for add an object is this:
void add(T *obj) {
    Node *n = new Node;
    T *copy = new T(*obj);
    n->info = copy;
    [...]

where my Node is a struct:
struct Node {
    T* data;
    Node *next;
    Node *prev;
};
Node *head;

How can I do a method to see if an object was already added? (Because I don't want duplicates)
This is a template, so the only solution that I've thinked it's control if a node already points the object (viewing memory address passed in add method and searching it into a node).. but the add method, do a copy of the object and inserts it into a new node, so this solution don't work
I've thinked to use a list of T pointer and insert the address of object every time I add a new object in add method but I can't use standard list (because this is an homework) and I can't use my class because it's not defined yet.. (g++ don't compile)
If I use a private pointer in the class, that point the last object added this work if I try to add the same object twice consecutively.. but if I add another object and then add the same, the list will add the object
some ideas?
Another short question:
is it right the copy in add method? or this copy can do a strange memory crash? (I'm new to C++)
Thanks all for your patience :)


text:
Q: How to convert this ScrollView into ListView without any error It currently displays list of files from sdcard, however I want to add  some additional features.
But I'm unable to add those in scroll view and also the styling is limited in ScrollView hence want it to change to ListView.
Any help would be appreciated.
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/scrollView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
    android:id="@+id/view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="8dp" >
</LinearLayout>
</ScrollView>


text:
Q: Robot / female humanoid film I'm looking for a movie from the late 90's early 2000's, maybe sooner but definitely not later, that has human looking robots. I was very young, about 6, and I remember seeing two distinct scenes from this film.  Uunfortunately, I don't have much more information to give that can help because it was so long ago.
I remember one of the girls who was a robot was walking down the stairs, then she "malfunctioned" and started walking backwards UP the stairs, as if it was going in reverse. She fell back afterwards and turned off I believe.
Then second scene I remember was at the end. It's a little hazy but a guy's head (also a robot) was taken off and one lady was devastated and took the head and fell backwards with it. This happened at a fancy dance/ball room, so the final camera view was her holding the head and her dress spread like wings. She almost looked like a doll.

A: Could this be The Stepford Wives (2004) remake?

The next day, Joanna, Bobbie and Roger go to Sarah's home to check up on her, where upon entering, they hear her upstairs, ecstatically screaming during sex with her husband Herb. As they scramble to sneak out, they find a remote control labeled SARAH, discovering a button that causes Sarah's breasts to enlarge and makes her walk backwards robotically.
...
At the ball, the wives corner their husbands and reveal that Joanna never received the microchip implant. Mike threatens Walter, but Joanna decapitates him with a candlestick, exposing him as a robot. Mike's wife Claire explains that she created Stepford because she, too, was a bitter career-minded woman. When she discovered Mike's affair with her research assistant, she murdered them in a jealous rage. Claire then electrocutes herself by kissing Mike's severed robotic head.

The staircase scene is here (warning, NSFW audio content)

And the scene with the removal of the robot head is here


text: Q: Rewrite files last modified date I have a folder of contents which I wish to archive. Each file has a different last modified date. Is there a way to change the last modified date of all the files to a specific one from the past? I do not mind if the change is before or after zipping the content.


text:
Q: PHP Menu Items Count then add under more button I use the bellow code to load the main menu elements from some CMS, the present code is perfect except that it loads ALL the main items on a single line of menu - which will make the width of it unusable in any centered design (under 1000px).. I want to change this script so after 15 main elements will add a "MORE" button under which the rest of the main menu items will show as sub-items of this "MORE" button (they will not have their own sub-items as the first 15 do).. How can I do it?
Thanks!
        <?php

require_once( '../../../inc/header.inc.php' );
require_once( DIRECTORY_PATH_INC . 'membership_levels.inc.php' );
require_once( DIRECTORY_PATH_ROOT . "templates/tmpl_{$tmpl}/scripts/TemplMenu.php" );

            class SimpleMenu extends TemplMenu
            {
            function getCode()
            {
            $this->iElementsCntInLine = 100;
            $this->getMenuInfo();
            $this->genTopItems();
            return $this->sCode;
            }

            function genTopItem($sText, $sLink, $sTarget, $sOnclick, $bActive, $iItemID, $isBold = false, $sPicture = '')
            {
            $sActiveStyle = ($bActive) ? ' id="tm_active"' : '';

            if (!$bActive) {
            $sAlt= $sOnclick ? ( ' alt="' . $sOnclick . '"' ) : '';
            $sTarget  = $sTarget  ? ( ' target="_parent"' ) : '';
            }

            $sLink = (strpos($sLink, 'http://') === false && !strlen($sOnclick)) ? $this->sSiteUrl . $sLink : $sLink;

            $sSubMenu = $this->getAllSubMenus($iItemID);

            $sImgTabStyle = $sPictureRep = '';
            if ($isBold && $sPicture != '') {
            $sPicturePath = getTemplateIcon($sPicture);
            $sPictureRep = "";
            $sText = ' ';
            $sImgTabStyle = 'style="width:38px;"';
            }

            $sMainSubs = ($sSubMenu=='') ? '' : " {$sSubMenu} ";
            $this->sCode .= "

{$sPictureRep}{$sText}

{$sMainSubs}

            ";
            }
            }

            $objMenu = new SimpleMenu();
            echo "
";
            echo $objMenu->getCode();
            echo "
";

    ?>

A: Personally I'd use CSS and Javascript (+jQuery) to do this.
Use Javascript to find any lis within ul#ddmenu that have an index of 15 or more, and give them a different class. Then, add your "More" button, and use onclick/hover etc to display the remaining lis.


text:
Q: $Error variable in a Powershell Script Module/ Commandlet First, let me start off with what I want to achieve.
I am writing a PowerShell Script Module (let's call it Get-FdkUser) that's internally calling Get-AdUser and should retry a couple of times in case every but a certian Exception is thrown. Of course, because it's retrying, the error should not be logged -- it's only an error if the retries don't work.
This PowerShell Script Module is used as part of a script to go through >100,000 users. In addition to AD data, I am pulling in data from Exchange and AzureAD.
Before implementing the retries, I was recording any kind of error by checking the $Error variable. Basically like this
$Error.clear()
Get-ADUser
Get-Mailbox
Get-AzureADUser
if($Error.Count -gt 0) {
  Do something
}

Works like a charm.
Now, my issue...
1) In a PowerShell Script Module, the $Error variable doesnt seem to be populated. It's only populated after execution of the commandlet.
You can replicate this by checking the following code.
I find this odd even without my requirement. It seems I can never use the $Error variable in a PowerShell Script Module?
File: ErrorTest.psm1
function Get-FdkTest
{
  [CmdletBinding()]
  Param
  ()

  try {
      $temp[-1]
  } catch {
      Write-Host "there was an error"
  }
  Write-Host "Commandlet error count $($Error.Count)"

}
Export-ModuleMember -Function *

Script
Import-Module .\ErrorTest.psm1 -Force
$Error.Clear()
Get-FdkTest
"Error count outside of commandlet $($Error.Count)"

Output
there was an error
Commandlet error count 0
Error count outside of commandlet 1

2) As mentioned, Exceptions that can be fixed with retries shouldnt even surface up. Ideally I would like to remove them from the $Error variable or avoid them from being captured. Besides this not working anyway due to 1), there is maybe a better way to tackle this.
Lastly, here is the PowerShell version I am running.
Name                           Value
----                           -----
PSVersion                      5.1.15063.1029
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.15063.1029
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1


text:
Q: Typo3 v9 how to query my extension with specific url? im in the process of developing a Typo3 extension and i want to access the data of this extension from a static URL.
The extension will be used in multiple systems and i want to query them like so: https://example.com/myextension
the specific URL slug is not relevant. The goal is that i dont have to configure in every of the systems the specific url where i
can reach the data gathered by my extension to summarize them all in a dashboard overview.
So my question is how can i set that my extension controller action is triggered with the call of a specific url?
If there are better ways to do this, please let me know
Many thanks!

A: You can add a Middleware https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/RequestHandling/Index.html that calls your action for a specific URL.
Or you could add a real page with a given slug and your plugin with an Upgrade Wizard https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/UpdateWizards/Creation.html or Extension update script https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/UpdateWizards/ExtUpdateFile.html.
For the nice URL you would use a routeEnhancer in the Site Config.

If this is something like a webservice where you need control over the HTTP verbs or implement OAuth, I would go with 1.
For something like a landing page I would go with 2. Also to expose an Extbase plugin action.


text:
Q: Asterisk - Cleaning up MySQL() Connections in 'h' Extension In one of our very simple custom contexts I would like to add some database logging outside of the built-in cdr app. I have something like the following:
[inbound-custom]
exten => _X.,1,MixMonitor(/mnt/temp/inbound-${STRFTIME(${EPOCH},,%Y%m%d-%H%M%S)}-${CALLERID(num)}-${EXTEN}-${UNIQUEID}.wav)
exten => _X.,n,MYSQL(Connect connid mysqlip cdr_logger mysqlpw asteriskcdrdb)
exten => _X.,n,MYSQL(Query resultid ${connid} INSERT INTO `call_recordings` (`asterisk_uniqueid`,`clid`,`filename`,`context`) VALUES (${UNIQUEID},${CALLERID(num)},inbound-${STRFTIME(${EPOCH},,%Y%m%d-%H%M%S)}-${CALLERID(num)}-${EXTEN}-${UNIQUEID}.wav,"inbound"))
exten => _X.,n,MYSQL(Clear ${resultid})
exten => _X.,n,MYSQL(Disconnect ${connid})
exten => _X.,n,Dial(SIP/cs1000/${EXTEN})
exten => _X.,n,Hangup()

This seems to work fine for the most part, however if someone hangs up before the context reaches the MYSQL(clear...) line there is a zombie connection left open on the MySQL server. On the voip info wiki there is mention of doing connection clean up in the h extension for a context, but there are no samples of this. I tried the following to no avail:
[inbound-custom]
exten => _X.,1,MixMonitor(/mnt/temp/inbound-${STRFTIME(${EPOCH},,%Y%m%d-%H%M%S)}-${CALLERID(num)}-${EXTEN}-${UNIQUEID}.wav)
exten => _X.,n,MYSQL(Connect connid mysqlip cdr_logger mysqlpw asteriskcdrdb)
exten => _X.,n,MYSQL(Query resultid ${connid} INSERT INTO `call_recordings` (`asterisk_uniqueid`,`clid`,`filename`,`context`) VALUES (${UNIQUEID},${CALLERID(num)},inbound-${STRFTIME(${EPOCH},,%Y%m%d-%H%M%S)}-${CALLERID(num)}-${EXTEN}-${UNIQUEID}.wav,"inbound"))
exten => _X.,n,Dial(SIP/cs1000/${EXTEN})
exten => _X.,n,Hangup()

exten => h,1,MYSQL(Clear ${resultid})
exten => h,n,MYSQL(Disconnect ${connid})

I imagine I'm doing something wrong in there but I cant quite tell what it is.

A: I was able to get this mostly working however clear seems to love throwing errors on inserts and the documentation is minimal at best. Gave up on using MYSQL() and opted to use system() to send the insert statement to a waiting python daemon.


text:
Q: Flex: How to scale the results of using ImageSnapshot.captureImage on a canvas I'm using ImageSnapshot.captureImage(canvas, 0, jPEGEncoder) to capture a drawing canvas to a bitmap, but I'd like the resulting jpeg much larger than the canvas itself.
For example, the canvas is 100x400 but I want the resulting image of the canvas to be 200x800.  I can't enlarge/scale the canvas up to this size because it'll mess up the UI.

A: scaleLimited:Boolean (default = true) — The maximum width or height of a bitmap in Flash is 2880 pixels - if scaleLimited is set to true the resolution will be reduced proportionately to fit within 2880 pixels, otherwise, if scaleLimited is false, smaller snapshot windows will be taken and stitched together to capture a larger image. The default is true.
Info Site


text:
Q: Magento How To Show Full Error Message Instead of Truncated One Anyone know how do you make Magento show the full error message and not truncate it with ...
example:
Warning: include() [function.include]: Filename cannot be empty  in /home/kevinmag/public_html/app/code/core/Mage/Core/Block/Template.php on line 241

0 /home/kevinmag/public_html/app/code/core/Mage/Core/Block/Template.php(241): mageCoreErrorHandler(2, 'include() [fetchView('frontend/base/d...')

I want to know what the [fetchView('frontend/base/d...') it cutting off with the ...

A: Don't blame Magento, it's all PHP's fault :) The Exception::getTraceAsString native method cuts the backtrace output, and it seems there's no normal way to handle it.
The only solution I've got to work is next:

*

*I've added a function, which I got from kind sir Steve (How can I get the full string of PHP's getTraceAsString()) to app\code\core\Mage\Core\functions.php:
function getExceptionTraceAsString($exception) {
    $rtn = "";
    $count = 0;
    foreach ($exception->getTrace() as $frame) {
        $args = "";
        if (isset($frame['args'])) {
            $args = array();
            foreach ($frame['args'] as $arg) {
                if (is_string($arg)) {
                    $args[] = "'" . $arg . "'";
                } elseif (is_array($arg)) {
                    $args[] = "Array";
                } elseif (is_null($arg)) {
                    $args[] = 'NULL';
                } elseif (is_bool($arg)) {
                    $args[] = ($arg) ? "true" : "false";
                } elseif (is_object($arg)) {
                    $args[] = get_class($arg);
                } elseif (is_resource($arg)) {
                    $args[] = get_resource_type($arg);
                } else {
                    $args[] = $arg;
                }
            }
            $args = join(", ", $args);
        }
        $rtn .= sprintf( "#%s %s(%s): %s%s(%s)\n",
            $count,
            $frame['file'],
            $frame['line'],
            isset($frame['class']) ? $frame['class'] . '->' : '',
            $frame['function'],
            $args );
        $count++;
    }
    return $rtn;
}

*I've modified Mage.php file (printException method) - instead of $e->getTraceAsString() I've inserted getExceptionTraceAsString($e) - notice that there's two appearances: for Debug mode on, and off.
To demonstrate  the results, here is an example of two backtraces - without the fix, and with the fix accordingly.
Old:
0 C:\apache\htdocs\checkout\lib\Varien\Db\Statement\Pdo\Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
1 C:\apache\htdocs\checkout\lib\Zend\Db\Statement.php(300): Varien_Db_Statement_Pdo_Mysql->_execute(Array)
2 C:\apache\htdocs\checkout\lib\Zend\Db\Adapter\Abstract.php(479): Zend_Db_Statement->execute(Array)
3 C:\apache\htdocs\checkout\lib\Zend\Db\Adapter\Pdo\Abstract.php(238): Zend_Db_Adapter_Abstract->query('SELECT COUNT(DI...', Array)
4 C:\apache\htdocs\checkout\lib\Varien\Db\Adapter\Pdo\Mysql.php(389): Zend_Db_Adapter_Pdo_Abstract->query('SELECT COUNT(DI...', Array)
5 C:\apache\htdocs\checkout\lib\Zend\Db\Adapter\Abstract.php(825): Varien_Db_Adapter_Pdo_Mysql->query(Object(Varien_Db_Select), Array)
6 C:\apache\htdocs\checkout\lib\Varien\Data\Collection\Db.php(217): Zend_Db_Adapter_Abstract->fetchOne(Object(Varien_Db_Select), Array)
7 C:\apache\htdocs\checkout\lib\Varien\Data\Collection.php(225): Varien_Data_Collection_Db->getSize()
8 C:\apache\htdocs\checkout\lib\Varien\Data\Collection.php(211): Varien_Data_Collection->getLastPageNumber()
9 C:\apache\htdocs\checkout\app\code\core\Mage\Eav\Model\Entity\Collection\Abstract.php(996): Varien_Data_Collection->getCurPage()
10 C:\apache\htdocs\checkout\app\code\core\Mage\Eav\Model\Entity\Collection\Abstract.php(831): Mage_Eav_Model_Entity_Collection_Abstract->_loadEntities(false, false)
11 C:\apache\htdocs\checkout\app\code\core\Mage\Review\Model\Observer.php(78): Mage_Eav_Model_Entity_Collection_Abstract->load()
12 C:\apache\htdocs\checkout\app\code\core\Mage\Core\Model\App.php(1299): Mage_Review_Model_Observer->catalogBlockProductCollectionBeforeToHtml(Object(Varien_Event_Observer))
13 C:\apache\htdocs\checkout\app\code\core\Mage\Core\Model\App.php(1274): Mage_Core_Model_App->_callObserverMethod(Object(Mage_Review_Model_Observer), 'catalogBlockPro...', Object(Varien_Event_Observer))
14 C:\apache\htdocs\checkout\app\Mage.php(416): Mage_Core_Model_App->dispatchEvent('catalog_block_p...', Array)

New:
0 C:\apache\htdocs\checkout\lib\Varien\Db\Statement\Pdo\Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
1 C:\apache\htdocs\checkout\lib\Zend\Db\Statement.php(300): Varien_Db_Statement_Pdo_Mysql->_execute(Array)
2 C:\apache\htdocs\checkout\lib\Zend\Db\Adapter\Abstract.php(479): Zend_Db_Statement->execute(Array)
3 C:\apache\htdocs\checkout\lib\Zend\Db\Adapter\Pdo\Abstract.php(238): Zend_Db_Adapter_Abstract->query('SELECT COUNT(DISTINCT e.entity_id) FROM `catalog_product_entity` AS `e`
 INNER JOIN `catalog_category_product_index` AS `cat_index` ON cat_index.product_id=e.entity_id AND cat_index.store_id=1 AND cat_index.visibility IN(2, 4) AND cat_index.category_id='3' AND cat_index.is_parent=1
 INNER JOIN `catalog_product_index_price` AS `price_index` ON price_index.entity_id = e.entity_id AND price_index.website_id = '1' AND price_index.customer_group_id = 0 WHERE (d=1) AND (d=1)', Array)
4 C:\apache\htdocs\checkout\lib\Varien\Db\Adapter\Pdo\Mysql.php(389): Zend_Db_Adapter_Pdo_Abstract->query('SELECT COUNT(DISTINCT e.entity_id) FROM `catalog_product_entity` AS `e`
 INNER JOIN `catalog_category_product_index` AS `cat_index` ON cat_index.product_id=e.entity_id AND cat_index.store_id=1 AND cat_index.visibility IN(2, 4) AND cat_index.category_id='3' AND cat_index.is_parent=1
 INNER JOIN `catalog_product_index_price` AS `price_index` ON price_index.entity_id = e.entity_id AND price_index.website_id = '1' AND price_index.customer_group_id = 0 WHERE (d=1) AND (d=1)', Array)
5 C:\apache\htdocs\checkout\lib\Zend\Db\Adapter\Abstract.php(825): Varien_Db_Adapter_Pdo_Mysql->query(Varien_Db_Select, Array)
6 C:\apache\htdocs\checkout\lib\Varien\Data\Collection\Db.php(217): Zend_Db_Adapter_Abstract->fetchOne(Varien_Db_Select, Array)
7 C:\apache\htdocs\checkout\lib\Varien\Data\Collection.php(225): Varien_Data_Collection_Db->getSize()
8 C:\apache\htdocs\checkout\lib\Varien\Data\Collection.php(211): Varien_Data_Collection->getLastPageNumber()
9 C:\apache\htdocs\checkout\app\code\core\Mage\Eav\Model\Entity\Collection\Abstract.php(996): Varien_Data_Collection->getCurPage()
10 C:\apache\htdocs\checkout\app\code\core\Mage\Eav\Model\Entity\Collection\Abstract.php(831): Mage_Eav_Model_Entity_Collection_Abstract->_loadEntities(false, false)
11 C:\apache\htdocs\checkout\app\code\core\Mage\Review\Model\Observer.php(78): Mage_Eav_Model_Entity_Collection_Abstract->load()
12 C:\apache\htdocs\checkout\app\code\core\Mage\Core\Model\App.php(1299): Mage_Review_Model_Observer->catalogBlockProductCollectionBeforeToHtml(Varien_Event_Observer)
13 C:\apache\htdocs\checkout\app\code\core\Mage\Core\Model\App.php(1274): Mage_Core_Model_App->_callObserverMethod(Mage_Review_Model_Observer, 'catalogBlockProductCollectionBeforeToHtml', Varien_Event_Observer)
14 C:\apache\htdocs\checkout\app\Mage.php(416): Mage_Core_Model_App->dispatchEvent('catalog_block_product_list_collection', Array)

Update: the above logic only modified Error/report output; to add this logic to Exception log as well you'll want to modify the Mage::logException method - change
self::log("\n" . $e->__toString(), Zend_Log::ERR, $file);

with
self::log("\n" . $e->getMessage() . getExceptionTraceAsString($e), Zend_Log::ERR, $file);

Hope it helps!

A: This is PHP and not Magento.
See here where the truncation is happening - https://github.com/php/php-src/blob/master/Zend/zend_exceptions.c#L383
I'd personally just live with it and use other debugging methods as opposed to hacking core files :)

A: You can do it just by simple change in your file.
Just open you index.php present on the root folder and write the following line just after the starting tag of the <?php error_reporting(E_ALL);
After this save and upload your file and  clear the cache and now all errors will be displayed.


text:
Q: SAS: Non-sequential do loop within a data step I would like to be able to execute a do loop for a non-sequential set of values. The way I have written this code runs a new data step for each value - so therefore the end product is a data table with a column added for the final value of the do loop only. What I want is for the the values in the varlst to loop through the if/then statements - thereby adding multiple columns to the table - without executing a new data step each time (which only results in adding one final column to the table).
INPUT DATA
DATA have;
INPUT id order Q3 Q5 Q6 Q50 Q75 Q102;
DATALINES;
 1  1  2 0  7 2 2 0
 1  2  3 0  5 5 3 0
 3  1  6 1  7 2 7 1
 3  2  6 0  7 5 7 0
 6  1  3 1  4 7 7 2
 6  2  5 2  7 7 7 1
 7  1  3 5  6 5 3 0
 7  2  4 1  7 5 2 1
 9  1  4 1  6 5 6 1
 9  2  1 3  5 7 5 0
;
run;

/********/
 %macro test;
    %let varlst=2 3 5 6 50 75 102 /*more values*/;
    %do i=1 %to %sysfunc(countw(&varlst));
    %let value=%scan(&varlst,&i);
    data want;
    set have;
    by id order;
    if Q&value ne lag(Q&value) and not first.id then do;
            Q&value.Equal = 0;
                end;
        if Q&value=lag(Q&value) and not first.id then do;
        Q&value.Equal = 1;
                end;
                %end;
       run;
    %mend;
    %test;

/**********/
OUTPUT
id  order   Q3  Q5  Q6  Q50  Q75 Q102 Q102Equal
1   1       2    0   7   2    2   0     .
1   2       3    0   5   5    3   0     1
3   1       6    1   7   2    7   1     .
3   2       6    0   7   5    7   0     0
6   1       3    1   4   7    7   2     .
6   2       5    2   7   7    7   1     0
7   1       3    5   6   5    3   0     .
7   2       4    1   7   5    2   1     0
9   1       4    1   6   5    6   1     .
9   2       1    3   5   7    5   0     0

A: Why don't you try using PROC COMPARE?
data have ;
  input id  order   Q3  Q5  Q6  Q50  Q75 Q102;
cards;
1   1       2    0   7   2    2   0     .
1   2       3    0   5   5    3   0     1
3   1       6    1   7   2    7   1     .
3   2       6    0   7   5    7   0     0
6   1       3    1   4   7    7   2     .
6   2       5    2   7   7    7   1     0
7   1       3    5   6   5    3   0     .
7   2       4    1   7   5    2   1     0
9   1       4    1   6   5    6   1     .
9   2       1    3   5   7    5   0     0
;;;;

proc compare
   data=have(where=(order=1))
   compare=have(where=(order=2))
   outdiff out=want
;
  id id ;
  var q: ;
run;


text:
Q: Complex business logic in WordPress The question: from a programming point of view, does WordPress allow a similar kind of flexibility that I would get by writing my own Java EE system? E.g. if the site owners suddenly decided that users whose birthday was on a Wednesday had to be sent a notification email and their birthday event had to be entered into a calendar that other members of the site could then RSVP to and then give a star rating afterwards to say how much they enjoyed it... could I do that easily with WP?
Hope that's clear, really welcome any feedback.

A: Wordpress is a bit easier to get started out with, and you can install whatever plugins you want easily. The only problem with it, is that it is a lot like windows: it accounts for many people's use cases.
For you, with a business/corporate (you mentioned corperate applications before the edit of your question)/extensible platform in mind, I would recommend sticking with what you've got. You've written it yourself (or as a team) so you know everything about it, and what to look for when there is a bug. It's easily extended with your own code, and you don't have to sort through and learn a new language.
Wordpress is great for blogs, as that is what it is designed for. It is good for general purpose websites with dynamic layouts, but relatively static content (blog posts, write it once, edit a few times, but relatively static). Sure, you could write plugins for it, and many have been written, But it won't have nearly the capabilities you seem to require without major extensions.
Also, being written in PHP, it has to be interpreted, as opposed to java, which is a semi-compiled/optimized bytecode (a bit complex) but java runs faster than the equivalent PHP code.
So benefits of your system:

*

*Faster

*More reliable

*Suited for very dynamic content

Benefits of wordpress:

*

*Easier to extend

*Suited for static content

*Easier for novices to use (but your own interface may work just fine)

A: WordPress is incredibly flexible, and can, without a doubt, be a viable framework for your app.  You should definitely check out it.
That said, if you're building something this complicated, I'd go with what you know.  You're gonna make mistakes and do things in weird ways on your first few WP projects.


text:
Q: Is there a way to show recommend Documents for the current logged-in user Inside our SharePoint online modern page >> we can add a News modern web part and define the source as the "Recommended for current user", as follow:

But can we do the same to show recommended Documents for the current user? using other web parts?

A: SharePoint recommendations on modern pages help you and your users discover pages and news in your organization.
You may refer to the following link: SharePoint Recommendations

A: There is no recommended documents web part in SharePoint Online.
However, there is "Recent documents" web part in SharePoint which shows the most recent documents accessed by the current user of the page.
Documentation: Use the Recent documents web part


text:
Q: javascript disable multiselect based on selections in another multiselect box using plain JS I have two multi select boxes one for country list and one for state list
<select multiple="multiple" name="country[]" id="country" >
      <option value="0">Select a Country</option>

  <?php
    foreach($country_list as $key=>$value){
    echo "<option value=\"$key\"";
      if($html['Country Name']==$key|| $row['Country Name']==$key){
       echo ' selected="selected"';
      }
    echo ">$value</option>\n";
    }?>
</select>

<select multiple="multiple" name="state[]" id="state">
      <option value="">Select a State</option>
      <?php
        foreach($state_list as $key=>$value){
        echo "<option value=\"$key\"";
          if($html['state']==$key|| $row['state']==$key){
            echo ' selected="selected"';
          }
        echo ">$value</option>\n";

        }?>
    </select>

I have this javascript code
window.onload = function() {
    var selectCountry = document.getElementById('country');
    selectCountry.onchange = function() {
        document.getElementById('state').disabled = (selectCountry.value != 'USA')? true : false;
    };
};

This code disables the select box when countries other than USA is selected. I want it to be disabled even when more than 1 country is selected in the first drop down (If user selects USA and CAN, it should be disabled too). Any suggestions. I have the working code in Jquery, but my server doesn't seem to support Jquery at all, I want it in Traditional JS.

A: Just go through all selected options and check if one of them has a value equal to USA:
selectCountry.onchange = function() {
        var disabled = false;
        for(var i = 0; i < this.options.length; i++){
            if(this.options[i].selected && this.options[i].value == 'USA') {
                disabled =true;
                break
            }
        }
        document.getElementById('state').disabled = disabled;
    };

Note that this will point to selectCountry element.
Also, server never "support" jquery. You just put jquery.js file under website directory and add a link to it on your website.
You can get slightly simpler code by using selecteOptions property, but can't find if it is supported by all browsers:
var disabled = false;
    for(var i = 0; i<this.selectedOptions.length; i++){
        if(this.selectedOptions[i].value == "3") {
            disabled =true;
             break
        }
    }

A: Here is a little bit of code that should help you. You'll have to iterate over all of the option elements checking if they are selected. If one is, then you'll need to match it against "USA" -
Given this HTML -
<select id="country" multiple="multiple">
    <option value="usa">usa</option>
    <option value="canada">canada</option>
    <option value="israel">israel</option>
</select>

You would do something like this -
var selectCountry = document.getElementById('country');

var usaIsMarked = false;
selectCountry.onchange = function () {
    usaIsMarked = false;
    for (i = 0; i < selectCountry.options.length; i++) {
        var currentOption = selectCountry.options[i];
        if (currentOption.selected && currentOption.value == 'usa') {
            usaIsMarked = true;
        }
    }
    if (usaIsMarked) {
        alert("usa was marked!");
    }
};

Here is a simple demo

A: In order to test whether more than one option is selected you'll need to loop through the options and test the selected property:
window.onload = function() {
    var selectCountry = document.getElementById('country'),
        selectState = document.getElementById('state');

    selectCountry.onchange = function() {
        var options = this.options,
            selected = 0, i, o;

        // Loop over <option> tags
        for (i = 0, o = options.length; i < o; i++) {
            option = options[i];

            // If selected options are less than 1 and country value is NOT 'USA'
            if (selected <= 1 && this.value !== 'USA') {

                // ...check if option is selected and increment "selected" var if true
                if (option.selected) {
                    selected += 1;
                }
            } else {
                // ...otherwise disable the state select ad break out of the loop
                selectState.disabled = true;
                break;
            }
        }
    };
};

As SebastianG said though, running jQuery is not server-dependant. You can run jQuery on any server - you just need to ensure it is loading correctly from your server or chosen CDN before referencing 'jQuery' or the '$' alias. Here's a getting started tutorial that details including jQuery (Tiny URL'd for space):
http://tinyurl.com/arhmcro


text:
Q: Custom Loading Screen with jQuery mobile Hey i use jquery/jquery mobile and phonegap for developing an app communicating to an webservice. I want a screen which will be displayed during something will be loaded (e.g. an ajax request). I looked for the jQm-function $.mobile.showPageLoadingMsg but this does not block the screen for user interaction. So i build an own screen, actually a simple div, which i make visible, calling a function. This works pretty well when i test the site in browser, but when i load it to my android phone it does not work anymore. Have anybody an idea? or had the same problem?

A: You could try blockUI?
http://jquery.malsup.com/block/


text:
Q: How to fix Django / python free(): invalid pointer? When I run the django manage.py app, I got free(): invalid pointer error.
Example:
>python manage.py check
System check identified no issues (0 silenced).
free(): invalid pointer
Abortado (imagem do núcleo gravada)

The django app is running fine but I'm trying to get rid off this message.
How can I fix this error or get more info to debug it?
Python 3.8.10 (default, Jun 22 2022, 20:18:18)
[GCC 9.4.0] on linux (Ubuntu 20.04)
Django==2.2.28
with virtualenv

A: I have tested with same environment with same Django version and I ran the check command, which did not yield this problem. I assume it is an issue with Pytorch, as mentioned in here: GitHub issue #21018.
To resolve it, you can take the following steps (copy pasted from this SO answer: https://stackoverflow.com/a/56363390/2696165)

There is a known issue with importing both open3d and PyTorch. A few possible workarounds exist:
(1) Some people have found that changing the order in which you import the two packages can resolve the issue, though in my personal testing both ways crash.
(2) Other people have found compiling both packages from source to help.
(3) Still others have found that moving open3d and PyTorch to be called from separate scripts resolves the issue.

A: That's a C error related to memory freeing, probably due to a bug from some unpatched dependency package, since you're using an old Django version.
Some options:

*

*Check your project at debug level:
python3 manage.py check --fail-level DEBUG

*List your dependencies and look online for which one originates that error:
python3 -m pip freeze

*Log files.

A: This usually happens with external dependencies.
You can run the check command on a specific app:
    python manage.py check app1 app2 app3

For Example:
    python manage.py check auth user myapp

Running on any specific database is also possible.
    python manage.py check --database default --database other

A few similar articles found:
https://github.com/duckietown/apriltags3-py/issues/1
https://github.com/googleapis/python-pubsub/issues/414
https://bugs.python.org/issue41335


text:
Q: Remove N items from IList where match predicate I would like to remove N items from an IList collection. Here's what I've got:
public void RemoveSubcomponentsByTemplate(int templateID, int countToRemove)
{
    //  TaskDeviceSubcomponents is an IList
    var subcomponents = TaskDeviceSubcomponents.Where(tds => tds.TemplateID == templateID).ToList();

    if (subcomponents.Count < countToRemove)
    {
        string message = string.Format("Attempted to remove more subcomponents than found. Found: {0}, attempted: {1}", subcomponents.Count, countToRemove);
        throw new ApplicationException(message);
    }

    subcomponents.RemoveRange(0, countToRemove);
}

Unfortunately, this code does not work as advertised. TaskDeviceSubcomponents is an IList, so it doesn't have the RemoveRange method. So, I call .ToList() to instantiate an actual List, but this gives me a duplicate collection with references to the same collection items. This is no good because calling RemoveRange on subcomponents does not affect TaskDeviceSubcomponents.
Is there a simple way to achieve this? I'm just not seeing it.

A: Unfortunately, I think you need to remove each item individually.  I would change your code to this:
public void RemoveSubcomponentsByTemplate(int templateID, int countToRemove)
{
    //  TaskDeviceSubcomponents is an IList
    var subcomponents = TaskDeviceSubcomponents
                         .Where(tds => tds.TemplateID == templateID)
                         .Take(countToRemove)
                         .ToList();

    foreach (var item in subcomponents)
    {
        TaskDeviceSubcomponents.Remove(item);
    }
}

Note that it is important to use ToList here so you are not iterating TaskDeviceSubcomponents while removing some of its items.  This is because LINQ uses lazy evaluation, so it doesn't iterate over TaskDeviceSubcomponents until you iterate over subcomponents.
Edit: I neglected to only remove the number of items contained in countToRemove, so I added a Take call after the Where.
Edit 2: Specification for the Take()-Method: http://msdn.microsoft.com/en-us/library/bb503062(v=vs.110).aspx


text:
Q: Android Studio 3.0 Layout Editor/Previewer I am using Android Studio 3.0 to make an Android App.
But the issue I am facing is that the Layout editor/previewer is not working properly. It is sometimes not showing anything and at times it is showing a grey box with all the navigation buttons.
These are the screenshots

I am using the buildToolsVersion '26.0.2' and the support libraries version is 23.0.1
Any help would be really helpful.
EDIT: This is my XML Layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000000"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="100dp"/>

        <ImageView
            android:id="@+id/logo"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_gravity="center"
            android:background="@drawable/logo" />

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="10dp"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="#FFFFFF"
            android:textSize="33dp"
            android:textStyle="bold" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"
            android:layout_marginBottom="15dp">
            <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="15dp"
            android:textColor="#FFFFFF" />

     </LinearLayout>

     </LinearLayout>

</RelativeLayout>

A: You had a couple of problem with structuring your UI. Here is a fix, also make sure that the @drawable/logo file is at the drawable folder
   <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<LinearLayout
    android:id="@+id/linearLayout"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toTopOf="@+id/logo"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:orientation="horizontal" />

<ImageView
    android:id="@+id/logo"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_marginBottom="10dp"
    android:background="@drawable/logo"
    app:layout_constraintBottom_toTopOf="@+id/name"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/linearLayout" />

<TextView
    android:id="@+id/name"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginBottom="10dp"
    android:background="#FFF"
    android:textColor="#000"
    android:textSize="33sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toTopOf="@+id/textView"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/logo" />

<TextView
    android:id="@+id/textView"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginBottom="207dp"
    android:background="#FFF"
    android:textColor="#000"
    android:textSize="33sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/name" />


text:
Q: What does the output of findContours mean and how can I parse it? When using the findContours() function I get an array. I am confused as to what the numbers in the array mean and also what a 'dtype' is.
code:
contour = str(cv2.findContours(edges, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE))
print(contour)

output:
([array([[[21, 21]],

       [[21, 90]],

       [[90, 90]],

       [[90, 21]]], dtype=int32), array([[[21, 22]],

       [[22, 21]],

       [[89, 21]],

       [[90, 22]],

       [[90, 89]],

       [[89, 90]],

       [[22, 90]],

       [[21, 89]]], dtype=int32), array([[[23, 23]],

       [[23, 88]],

       [[88, 88]],

       [[88, 23]]], dtype=int32), array([[[23, 24]],

       [[24, 23]],

       [[87, 23]],

       [[88, 24]],

       [[88, 87]],

       [[87, 88]],

       [[24, 88]],

       [[23, 87]]], dtype=int32)], array([[[-1, -1,  1, -1],
        [-1, -1,  2,  0],
        [-1, -1,  3,  1],
        [-1, -1, -1,  2]]], dtype=int32))

How would I go about parsing this array to use later? I plan on making a turtle application that reads instructions from a file containing image data. I want to know how I would be able to convert this into said instructions.

A: cv2.findConturs()
cnt,heirarchy = cv2.findContours(edged_img,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)     # Finding contours detection

This method returns two values. contours, and hierarchy. contours is a Python list of all the contours in the image. Each individual contour is a Numpy array of (x,y) coordinates of boundary points of the object.
And in your case, it's returning the same two values but the difference is that you are parsing it to string and getting it in a single variable which is making it hard to understand.(Read the fix part)
Dtype
Every ndarray has an associated data type (dtype) object. This data type object (dtype) informs us about the layout of the array. This means it gives us information about :

*

*Type of the data (integer, float, Python object etc.)

*Size of the data (number of bytes)

*Byte order of the data (little-endian or big-endian)

*If the data type is a sub-array, what is its shape and data type.

In your case, it is telling that the data inside ndarray is of int type along with array dimension
Fixing your code
In your code, the problem is with this part:
contour = str(cv2.findContours(edges, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE))

In this, you are parsing the values returned by findCountours to str type.
cnt,heirarchy = cv2.findContours(edged_img,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)     # Finding contours detection

Edit ::
For drawing
If you want to draw all the detected contours then you have to use cv2.drawContours() method.
cv2.drawContours(image,contours,-1,(255,0,0),2)        # Drawing the detected contours on the image.

It takes 5 values. Its first argument is source image, the second argument is the contours which should be passed as a Python list, the third argument is the index of contours (useful when drawing the individual contour. To draw all contours, pass -1) and remaining arguments are color, thickness, etc.
If you want to see a python program rather which takes an image and draws contours(INFORMATION) on it then you can check this open Source code.
https://github.com/0xPrateek/ComputerVision-OpenCV3-Python/blob/master/contours%20detection.py


text:
Q: Ways of speeding up THREE.js I am writing a simple minecraft clone in THREE.js.
However, the result is very laggy.
I am using box geometry for the voxels, but I need to remove blocks when they are broken and need to use mouse picking.
I have heard that joining geometries speeds it up but as far as I am aware, this means that you cannot remove any of the voxels or use mouse picking.
What are the other ways of speeding up in THREE.js?

A: Using a box per voxel (making one draw call per voxel) will be too slow on any machine even if you wrote it in assembly language.
You need to build a mesh for every section of your world. As in divide the world into 48x48x48 unit chunks and build one mesh that contains all the voxels in that area. When the user edits a box you edit the mesh (the vertices) rather than remove a Box object.


text:
Q: Fastdebug/debug builds for JDK 7 I'm searching for debug (or fast debug builds as they call it I guess) of the JDK to enable printing assembly generated at runtime and other diagnostics required when hunting down performance issues. As it stands, I can't seem to find a "ready" fast debug build binary bundle which can be directly used. Can someone please help me out in giving a download link or at least providing hints as to what would be the path of least resistance to get those builds?

A: You say about "hunting down performance issues".
I can suggest you to use some profiler tool, like http://visualvm.java.net/ or tptp inside eclipse.
But, if you really want the fastdebug budle, you can download then at: http://download.java.net/jdk6/6u25/promoted/b03/index.html


text:
Q: Python-Networkx Graph Generating Function - For Loop I have created a function to generate 100 random graphs in Networkx, and I want the output to be the graph list, as well as a couple of functions run on each generated graph (the diameter, transitivity, and average shortest path length). My output seems to be iterating on the same first generated graph, instead of through each sample graph generated. I am new to programming and believe it has to do with the structure of my loop, but appreciate any advice though I know the answer is likely basic. I am using Python 3.9 and NetworkX 2.5

 def random_networks_generator(n,p,num_networks=1, directed=False):
    Graph_list=[]
    dias=[]
    trans=[]
    avgpath=[]
    for num in range (0,num_networks):
        G=nx.gnp_random_graph(n,p,directed)
        D=nx.diameter(G)
        APL=nx.average_shortest_path_length(G)
        T=nx.transitivity(G)
        Graph_list.append(G)
        dias.append(D)
        trans.append(T)
        avgpath.append(APL)
    return Graph_list, dias, trans, avgpath

random_networks_generator(793,.04,3,directed=False)

OUT:

([<networkx.classes.graph.Graph at 0x7fdc6889dbb0>,
  <networkx.classes.graph.Graph at 0x7fdc6889d0d0>,
  <networkx.classes.graph.Graph at 0x7fdc6889d160>],
 [3, 3, 3],
 [0.039558780162902554, 0.039558780162902554, 0.039558780162902554],
 [2.235259276242883, 2.235259276242883, 2.235259276242883])

A: This is a subtle bug, but the issue is this line:
G=nx.gnp_random_graph(n,p,directed)

The problem is that if you look at the signature for nx.gnp_random_graph, the third argument is the seed for the random number generator, not whether or not the graph is directed:
def gnp_random_graph(n, p, seed=None, directed=False):
    """Returns a $G_{n,p}$ random graph, also known as an Erdős-Rényi graph
    or a binomial graph.

    The $G_{n,p}$ model chooses each of the possible edges with probability $p$.

    Parameters
    ----------
    n : int
        The number of nodes.
    p : float
        Probability for edge creation.
    seed : integer, random_state, or None (default)
        Indicator of random number generation state.
        See :ref:`Randomness<randomness>`.
    directed : bool, optional (default=False)
        If True, this function returns a directed graph.

You are passing False as the seed (which is treated as the integer 0). Given a fixed seed like this, a (pseudo) random number generator will always generate the same sequence of random numbers, so the "random" graph will always be the same.
The fix is quite easy - just pass directed=False as a keyword argument. This is a good idea in general, as it prevents these issues which come from not memorizing the order of positional arguments:
import networkx as nx

def random_networks_generator(n, p, num_networks=1, directed=False):
    Graph_list = []
    dias = []
    trans = []
    avgpath = []
    for _ in range(num_networks):
        G = nx.gnp_random_graph(n, p, directed=directed)
        D = nx.diameter(G)
        APL = nx.average_shortest_path_length(G)
        T = nx.transitivity(G)
        Graph_list.append(G)
        dias.append(D)
        trans.append(T)
        avgpath.append(APL)
    return Graph_list, dias, trans, avgpath

results = random_networks_generator(793, .04, 3, directed=False)
for x in results:
    print(x)

"""
Output:
[<networkx.classes.graph.Graph object at 0x7f61be2a8040>, <networkx.classes.graph.Graph object at 0x7f61be28fd30>, <networkx.classes.graph.Graph object at 0x7f61be1eeaf0>]
[3, 3, 3]
[0.03973988995344184, 0.040121944443041235, 0.03966888841109439]
[2.238010623256525, 2.2307373864750915, 2.22814844536156]
"""

I cleaned up your code a bit as well. Check out a PEP8-compliant linter such as flake8 to develop good Python habits (or use an IDE like PyCharm which comes with built-in linting).


text:
Q: How to Call JavaScript functions by clicking a button and perform operations in looped textboxes? I'm new in javascript and I want to know how to perform some math operations per row in the table by clicking the button.
The textboxes in the column "Variable" are created by a while loop, and I want to iterate the operation over two values one value from the first textbox in the array (variable 1) and the another from  the second one (variable 2) so I need to sum or substract the two numbers depending of the button.
how can I make the javascript functions to call it by clicking the button?

In my example I have a "Case statement" getting the id from my table
  "operations" where if the id is 1 it has to sum, 2 it has to
  substract, 3 it has to make a multiplication.

for example I have three rows:

*

*Indicador 1  = Variable 1 + Variable 2  ---> click the button ----> show the result of the sum.

*Indicador 2  = Variable 3 - Variable 4  ---> click the button ----> show the result of the substraction.

*Indicador 3  = Variable 5 * Variable 6  ---> click the button ----> show the result of the multiplication.

and so on
You can see the table I have.

If I missed something let me know.
This code display the table above.
        <form action="ingreso-datos-exe.php" method="post">
              <input type="hidden" value="<?php echo $iduser;?>"  name="iduser"/>

         Indicador
          Variables
           Result
          Compute Operation

        <?php

        //to get the indicator's name in the first column of the table

        while($r = mysql_fetch_assoc($checkSQL)) {
                $id_indicador= $r['id_indicador'];
                $nombre= $r['nombre_indicador'];
                $id_calculo= $r['id_calculo'];
                echo $id_indicador.$nombre.'
'; ?>

        <?php echo $id_indicador.$nombre;?>

        <?php

            // To get the variable's name in the second column of the table
            while($r2 = mysql_fetch_assoc($checkSQL2)) {
                $nombre_variable= $r2['nombre_variable_medicion'];
                $idvariable= $r2['id_variablemedicion'];
                //  var_dump($r2);
                                             ?>

    <?php echo $nombre_variable;?>
    <input type="text" value="" class="price" name="valor[<?php echo $idvariable; ?>]"/>

    <input type="hidden" value="<?php echo $id_indicador;?>"  name="id_indicador[<?php echo $idvariable; ?>]"/>
   <input type="hidden" value="<?php echo $idvariable;?>"  name="id_variable[<?php echo $idvariable; ?>]"/>

      <?php     } ?>

  <?php switch($id_calculo){

                            case '1':?>
                                <input class="btn btn-success" type="button" name="btnSum" value="Sum"    OnClick="fncSum();">

                           <?php  break; ?>

                          <?php case '2':?>
                          <input class="btn btn-success" type="button" name="btnSum" value="substract" OnClick="fncSum();">

                           <?php  break; ?>

                          <?php case '3':?>
                         <input class="btn btn-success" type="button" name="btnSum" value="multiplication" OnClick="fncSum();">

                          <?php  break;
                           } ?>
                           <?php    echo '	'.'
';
                          }
                                ?>

        </form>

A:

//returns parent row for the button
function getRow(el) {
    var row = el.parentNode.parentNode;
    return row;
}

//returns number from val1
function getVal1(row) {
    return +row.querySelector(".val1").value || 0
}

//returns number from val2
function getVal2(row) {
    return +row.querySelector(".val2").value || 0
}

//sets result
function setResult(row, val) {
    row.querySelector(".result").value = val
}

//do action
//reads action from the data-action attribute
function action() {
    var a = this.getAttribute("data-action");
    var row = getRow(this);
    var val1 = getVal1(row);
    var val2 = getVal2(row);
    var res = 0;
    switch (a) {
        case "sum":
            res = val1 + val2;
            break;
        case "substract":
            res = val1 - val2;
            break;
        case "multiplication":
            res = val1 * val2;
            break;
        default:
            throw new Error("Unknown action '"+a+"'");
    }
    setResult(row, res);
}

//adds click event for each btn-action elements after document loaded
window.addEventListener("load", function () {
    var btns = document.querySelectorAll(".btn-action");
    for (var i=0; i<btns.length; i++) {
        var btn = btns[i];
        btn.addEventListener("click", action);
    }
})

        Item 1
        <input class="val1"/>
        <input class="val2" />
        <input class="result" />
        <input type="button" class="btn-action" value="Sum" data-action="sum"/>

        Item 2
        <input class="val1" />
        <input class="val2" />
        <input class="result" />
        <input type="button" class="btn-action" value="Substract" data-action="substract" />

        Item 3
        <input class="val1" />
        <input class="val2" />
        <input class="result" />
        <input type="button" class="btn-action" value="Multiplication" data-action="multiplication" />