text:
Q: Ionic: proxy servers on android I have a project setup to hit a local server also in development on port 3000. In development I used the following configuration in the proxy settings of ionic.config.json to avoid CORS issues:
"proxies": [
    {
      "path": "/api",
      "proxyUrl": "http://192.168.1.14:3000/api"
    },
    {
      "path": "/auth",
      "proxyUrl": "http://192.168.1.14:3000/auth"
    }
  ]

However when I run this on an android device it seems to insist on ignoring these settings and calling file:///auth/... instead of the real URL. This is fixed with entering the IP address manually. Is there any way to streamline the process and have a fixed set of working URL's on both ionic serve and the native app?

A: I had the same problem and solved it using Platform.is() method. When the device is android, I change the url to contain ip address of my api.
ionic.config.json
"proxies": [
  {
    "path": "/api",
    "proxyUrl": "http://192.168.80.10:3000/api"
  }
]

My example service:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Platform } from 'ionic-angular';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class MemberService {
  private url = 'api/members';

  constructor(
    private http: Http,
    private platform: Platform
  ) {
    if(this.platform.is('android')) {
      this.url = 'http://192.168.80.10:3000/' + this.url;
    }
  }

  getMembers(): Promise<any> {
    return this.http.get(`${this.url}.json`)
      .toPromise()
      .then(result => result.json())
      .catch(error => console.log(error));
  }
}

Probably this.platform.is('mobile') will be also good.


text:
Q: Normal distribution test integer/discrete data I want to conduct ANOVA in R and have to check for normal distribution before. Therefore I could use shapiro.test(y) or ad.test(y). However this is not possible for discrete/integer values. I tested the following:
y <- rnorm(100, 2.5, 1)
ad.test(y) # p-value = 0.864
shapiro.test(y) # p-value = 0.9052

And discrete values:
y <- round(y)
ad.test(y) # p-value = 1.021e-08
shapiro.test(y) # p-value = 3.628e-05

Is there a way to test integer data in R Studio for normal distribution?
Best regards

A: There is no problem using tests for normality on discrete data (although it might be fundamentally misguided to do so, especially if the data is categorical rather than genuinely numerical). As @Dason points out, rounding normal data changes its distribution, in a way that is especially noticeable when the standard deviation is small. To see the effect of the standard deviation, repeat your experiment this way:
y <- rnorm(100, 250, 10)
ad.test(y) # p-value = 0.7949
y <- round(y)
ad.test(y) # p-value = 0.6395

If you run such a test before ANOVA and you get very low p-values, then perhaps ANOVA isn't appropriate. ANOVA is fairly robust, but there is a limit to how far you can depart from the assumptions. See this question for a nice discussion. You might need to run a non-parametric test such as Kruskal-Wallis instead. Perhaps you could post a question which describes your actual use-case on Cross Validated since the question really involves statistical methodology rather than R per se.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Search on multiple columns In my PowerBI App I have a visual tool called 'Text Filter' that provides a text search tool for finding data quickly for a single column of data in the table.  The problem is that I want it to
search on multiple text columns instead of just one.
I created a calculated column that combines all the text columns I want to search:
DAX
srch_data = [Item No] & "~" & [DocumentNo] & "~" & [OrderNo] & "~" & [Description] & "~" & related(Posted_AR_Header[External_Document_No_]) & "~" & RELATED(Posted_AR_Header[No]) & "~" & RELATED(Posted_AR_Header[ShiptoAddress]) & "~" & RELATED(Posted_AR_Header[ShiptoCity] )

Next, I applied the new calculated column (srch_data) to the Text Filter visual tool.
It all works fine but it seems like there should be a better way to highlight/filter row data that meets the search criteria for multiple columns in the table.
Is there a better way to search for text in multiple columns??
9/3 update - Apparently there is not a better way to do this...
https://community.powerbi.com/t5/Desktop/Search-on-multiple-columns/m-p/2054886#M768023

A: After having a similar issue and searchign on multiple forums, I decided to create a hybrid solution that works well for me. Requirement was to be able to search over multiple fields but also have 'smart search' or 'auto fill' featured.
Smart Filter by OKViz is much more powerful than the Microsoft Text filter custom viz. This custom viz allows 'auto fill' but not searching over multiple columns.
The solution on every forum I read was to concatenate the columns into one field to create one long string. This wouldn't work with auto fill. Instead, I pivoted the columns I wanted to search on by the ID of the fact table to create another table, simply containing ID and search_values.
Creating the relationship between the new table and the fact table as a many-to-one relationship and cross-filtering in both directions got it to work.


text:
Q: How do I create a list of objects in c ++ and use its methods? I created this class and I need to use a for (iterator) to enter the values, they will not necessarily be i, any other value, for that I need to use a list:
#include <iostream>
#include <list>

using namespace std;
// 1ra clase base
class Person {
  int e;

 public:
  Person(int);
  void printDates();
};

Person::Person(int x) { e = x; }
void Person::printDates() { cout << e; }
int main() {
  list<Person> persons;
  for (int i = 0; i < 5; i++) {
    Person person(i);
    persons.push_front(person);
  }
  // for(int i = 0; i < 5; i++)
  // {
  //     hombres[i].printDates();
  // }
}

I need to use personDates method, and any other method you can add, either in a list or in another.

A: The problem is that list does not provide an index into the container.
persons[i] // does not work for list (though it does work for vector).

So you need to use an iterator.
Older versions of C++ this is done like this:
for(auto loop = persons.begin(); loop != persons.end(); ++loop) {
    loop->printDates();
}

In modern versions of C++ this is simplified to:
for(auto& item: persons) {
    item.printDates();
}


text:
Q: @SuppressWarnings for the invocation of the varargs with un-cast null What string should I use in @SuppressWarnings("....") to remove the warning I get in this unit test of a method with varargs:
/**
 * Calling {@link #readFiles(String, String...)} with just one arg and a null
 * works, but you have to do a null check on the varargs in case it is null.
 */
@Test
public void callMethodWithOneArgAndNull() {
   readFiles("C:/Temp", null);
}

Eclipse gives the following warning for this:

The argument of type null should explicitly be cast to String[] for
  the invocation of the varargs method readFiles(String, String...) from
  type TestVarArgs. It could alternatively be cast to String for a
  varargs invocation

This is good; it is expected. I am also unit testing what happens when I cast the null.
But for the purposes of this single test, I want to suppress that specific warning, i.e. I don't want to use @SuppressWarnings("all"). I have tried every string mentioned in this answer to What is the list of valid @SuppressWarnings warning names in Java? and none of them seem to catch this warning.

A: To my understanding, this is not a warning you can suppress with a specific annotation. You have to make an explicit cast to make the warning go away - or suppress all warnings.
Also, consider testing both possible casts, i.e. (String[]) {null} and (String) null, to make sure your method doesn't choke on "no files" nor on a "null filename" input.

A: You can use @supresswarnings (unchecked) annotation.


text:
Q: Reflection in optical fiber I took a measure (OTDR) of optical fiber from the headend and I got this :

In 10.7km The optical fiber have a "reflection". This reflection is holding 500 meters. After that reflection down again in 11.2km.(above 11.2km fiber is cut down).
How can this affect the performance in network ? Can I send costumers across that fiber ? Would have I lower error bit ?


text:
Q: Problema al instalar @react-navigation/stack Cuando quiero instalar:
npm install @react-navigation/stack
npm install @react-native-community/masked-view

Me sale este error, no se si sea la versión del react.

Este es mi package.json
  "dependencies": {
"@react-navigation/native": "^5.9.3",
"react": "17.0.1",
"react-native": "0.64.0",
"react-native-gesture-handler": "^1.10.3",
"react-native-reanimated": "^2.0.0",
"react-native-safe-area-context": "^3.2.0",
"react-native-screens": "^2.18.1"

},

A: para instalar paquetes a pesar de los conflictos de peerDependencies, puedes usar el flag --legacy-peer-deps justo después de npm install.
npm install --legacy-peer-deps
También pudieras agregar --force para forzar la instalación, justo como te lo esta diciendo ahí.
Fuente

A: Me ha pasado lo mismo usando expo y la solución fue eliminar node_moudles y volver a ejecutar npm install, luego npm install react-navigation

A: Resolví el problema borrando la carpeta node_modules y el archivo package-lock.json y después ejecutado nuevamente
npm install


text:
Q: Conversion (markdown --> pdf) of \"{e} fails with pandoc I need to put some french e's with a double point above into my text. The LaTeX markup I employ is \"{e} and I use that code in my markdown source, but Pandoc converts this to "{e} in the pdf and "\{e\} in a .tex file.
On the other hand, \c{c} for a cédille works fine, so I suppose this has to do with the way pandoc treats "-signs.
Is there a way to make the conversion work or do I have to first convert to TeX, than edit the tex-file by hand and compile it to pdf?


text:
Q: My ajax loader is giving me problems Please help me someone. I have implemented this ajax loader gif image and it works, but when I click on the link a second time it just loads without ever disappearing. I should add that the links are set up in way that if once loaded whenever I click the same link again nothing happens (speaking for myself, it's a bit pointless to load over an already fetched file). Here is a snippet from my code:
$('.loadtitles').click(function() {
   $("#myDiv").append('<img src="loader.gif" alt="Currently Loading" id="loading" />');
   window.location.hash = $(this).attr("href");
  var href = $(this).attr('href');
  $('#SearchFrame').css('display','none');
  $('#myDiv').css('display','block');

return false;
});

I tried adding something like this:
$('#loading').fadeOut(1000, function() {$(this).remove();});

But it doesn't accomplish what I need. I've been playing with the code for a while but nothing that I managed to do suits the fix that I am after. Any help at all would be greatly appreciated.

A: Because you are using append, a new loading img is created every time you click.
I recommend having the image already in place in the html and just have the jQuery show/hide it as required.

A: Thanks for you help everyone but I fixed it by adding the jqery (stop) on the necessary part of the overall code. But I would still like to see any other way in which someone else would go about this.


text:
Q: How to use latest FFMPEG in Android Studio project? I have a simple task to make a video from multiple images and an audio file, After searching a lot found that its possible with FFMPEG, Unfortunately there are no updated tutorials for FFMPEG, there are few but outdated and most of them are not working.
As I have compiled FFMPEG for Android using NDK android-ndk-r10e and ffmpeg-2.8.6 on my MAC with Android Studio following the tutorial http://www.roman10.net/how-to-build-ffmpeg-with-ndk-r9/
It makes the .so files as

Now I can't understand what should I do to integrate this in my Android project, I have also checked,
How to use Ffmpeg in android studio?
how to use ffmpeg in android?
FFmpeg on Android
and mainly this,
http://www.roman10.net/how-to-build-android-applications-based-on-ffmpeg-by-an-example/
https://github.com/roman10/android-ffmpeg-tutorial
But its not working and having errors with no way to resolve this. Can anyone please mention some steps that should be followed to use FFMPEG .so files as in image attached.

A: There's a very easy solution for this, There's a precompiled library for android, as below https://github.com/WritingMinds/ffmpeg-android-java
Simply include this as a gradle project in your code and add few methods as per their documentation and you are done with FFMPEG commands in android.
This library is not very updated and have some missing features but still its good to use for many simple tasks.


text:
Q: How to safely use Google translate in Selenium I am into a project which requires translating text from different languages to English . In a day , I would have to translate nearly 5000 documents.I have written a small selenium code that would help me translate these documents.
Now my question is that if i use Selenium for translating a huge data from google translate ,will I be blocked by Google . If yes , what is the solution to avoid being blocked by Google Translate ?
I have posted my code below for reference :
public static WebDriver google_translate(WebDriver driver,String filename)
    {

        driver.manage().timeouts().implicitlyWait(5
                , TimeUnit.SECONDS);
        try{
        driver.get("http://translate.google.com/#auto/en");
        String text="";
        text=read_contents.read_from_html(filename);
        if(text.length()<5)
            return driver ;
        // Enter the query string "Cheese"
        System.out.println("file read");
        WebElement query = driver.findElement(By.id("source"));
        query.sendKeys(text);
        WebElement query1 = driver.findElement(By.id("gt-submit"));
        query1.click();
        System.out.println("text entered");
        Date d=new Date();
        long intial=d.getTime();
        WebElement result;
        do{
            result = driver.findElement(By.id("result_box"));
            d=new Date();
        }while(result.getText().length()<20 && (d.getTime()-intial<15000) );
        System.out.println("result fetched");
        String output=Global.prop.get(1).toString()+"/"+new File(filename).getName()+".txt";
        output_writer.txt_writer(result.getText(),output);
        }
        catch(UnhandledAlertException e)
        {
            e.printStackTrace();
        }
        catch(NoSuchElementException e)
        {
            e.printStackTrace();
        }
        catch(UnknownServerException e)
        {
            e.printStackTrace();
        }
        //System.out.println(result.getText());
        return driver ;


text:
Q: Using cJSON to read in a JSON array I am attempting to use the cJSON library, written by Dave Gamble, to read in the following JSON array:
"items":
[
    {
        "name": "command",
        "index": "X",
        "optional": "0"
    },
    {
        "name": "status",
        "index": "X",
        "optional": "0"
    }
]

From reading his documentation, I found ways to read in individual Objects, but nothing regarding Arrays, and I wasn't able to surmise how to do it from the examples given.
Here's what I'm trying:
cJSON* request_json = NULL;
cJSON* items = cJSON_CreateArray();
cJSON* name = NULL;
cJSON* index = NULL;
cJSON* optional = NULL;

request_json = cJSON_Parse(request_body);

items = cJSON_GetObjectItem(request_json, "items");

name = cJSON_GetObjectItem(items, "name");
index = cJSON_GetObjectItem(items, "index");
optional = cJSON_GetObjectItem(items, "optional");

I know this is wrong, and not just because it's not working, but I can't figure out how to make it right.
Obviously I'm going to need to loop the process of reading in all of the entries for each index of the array.  I have no idea how I'm going to do that though, because I don't know where I should be using the indexes in this code, or if it is even the right start.  There is a cJSON_GetArrayItem(), but it takes only a number (presumably an index) and no string to indicate which field it wants.

A: IMHO, this is one example of a case where you should burst the library's encapsulation and work directly with it's object data structure. cJSON.h defines the core object as the following struct:
/* The cJSON structure: */
typedef struct cJSON {
    struct cJSON *next,*prev;   /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
    struct cJSON *child;        /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */

    int type;                   /* The type of the item, as above. */

    char *valuestring;          /* The item's string, if type==cJSON_String */
    int valueint;               /* The item's number, if type==cJSON_Number */
    double valuedouble;         /* The item's number, if type==cJSON_Number */

    char *string;               /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
} cJSON;

(One could quibble with some of the naming choices the author made, of course. But good naming is hard.)
The key thing to note is that both JSON Objects and JSON Arrays have a non-null child field, which points to a doubly-linked list of their children. Children of JSON Objects also have non-null string fields which contains the field name associated with that child.
So, to generically iterate over the JSON Array ja in O(n) time, calling a function for each element, you write something like this:
cJSON_ForEachItem(cJSON *ja, int (*f)(cJSON *ja, int i, cJSON *jchild))
{
    cJSON *jchild;
    int i;
    for (jchild=ja->child, i=0; jchild; jchild=jchild->next, ++i) {
        // do something here with the ith child...
        if (f(ja, i, jchild))
            break;
    }
}

Since Objects and Arrays only differ internally in the presence of names for each child item, that function will also iterate the fields of an object. The callback can tell because ja->type will be either cJSON_Array or cJSON_Object, and jchild->string will be non-null for Objects as well.
Doing the same iteration by calling cJSON_GetArraySize() and using cJSON_GetArrayItem() will be order O(n^2) because it has to traverse the linked list each time to locate the nth item.
Arguably, cJSON should include some generic ForEach functions, but that might represent the beginning of a significant amount of scope-creep away from it's professed original goal of being "the dumbest possible parser that you can get your job done with".

A: If you want to run slightly faster, this is what the code looks like:
void parse_array(cJSON *array)
{
  cJSON *item = array ? array->child : 0;
  while (item)
  {
     cJSON *name = cJSON_GetObjectItem(item, "name");
     cJSON *index = cJSON_GetObjectItem(item, "index");
     cJSON *optional = cJSON_GetObjectItem(item, "optional");

     item=item->next;
  }
}

This avoids the O(n^2) cost that RBerteig correctly points out.
Call with:
parse_array(cJSON_GetObjectItem(cJSON_Parse(request_body),"items"));

A: Document mentions about parse_object().
I think this is what you need to do.
void parse_object(cJSON *root)
{
  cJSON* name = NULL;
  cJSON* index = NULL;
  cJSON* optional = NULL;

  int i;

  cJSON *item = cJSON_GetObjectItem(items,"items");
  for (i = 0 ; i < cJSON_GetArraySize(item) ; i++)
  {
     cJSON * subitem = cJSON_GetArrayItem(item, i);
     name = cJSON_GetObjectItem(subitem, "name");
     index = cJSON_GetObjectItem(subitem, "index");
     optional = cJSON_GetObjectItem(subitem, "optional");
  }
}

Call this function as
request_json = cJSON_Parse(request_body);
parse_object(request_json);

A: My guess (not having read the spec, and being a bit rusty with C):
request_json = cJSON_Parse(request_body);

items = cJSON_GetObjectItem(request_json, "items");
for (int i = 0; i < max; i++) {  // Presumably "max" can be derived from "items" somehow

    cJSON* item = cJSON_GetArrayItem(items, i);

    name = cJSON_GetObjectItem(item, "name");
    index = cJSON_GetObjectItem(item, "index");
    optional = cJSON_GetObjectItem(item, "optional");

    // Stash above info somewhere
}


text:
Q: What method does SpringJDBC uses to get latest key Following YSQL documentation: doc on the last paragraph it is mentioned that:

...that at times, it can be tricky to use the SELECT LAST_INSERT_ID() query, as that function's value is scoped to a connection. So, if some other query happens on the same connection, the value will be overwritten. On the other hand, the getGeneratedKeys() method is scoped by the Statement instance, so it can be used even if other queries happen on the same connection, but not on the same Statement instance.

As I working in a completely distributed environment it is very important to me not to happen to get the wrong key back from the database...
Which of these methods is being used by springJDBC
I am using spring version 3.2.1.RELEASE but i don't mined upgrading to the latest.

A: Well. As suggested, i dug through the code untill i reached this little line.
ResultSet keys = ps.getGeneratedKeys();

which is called from inside a PreparedStatementCallback anonymous class.
So for all intent and purposes the function:
int org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.update(String sql, SqlParameterSource paramSource, KeyHolder generatedKeyHolder) throws DataAccessException
this is a thread/process safe action


text:
Q: Variable Framerate into Constant Avconv I want to change a video with variable framerate into constant. I don't wanna mess up with any other part of the video except making constant the framerate.
I'm using:
avconv -i input.mp4 -codec copy -codec:a mp3 -r 30 output.mp4

At the end, it gives me this command line response:
Non-monotonous DTS in output stream 0:1; previous: 1794, current: 1794; changing to 1795. This may result in incorrect timestamps in the output file.
frame= 1272 fps=196 q=-1.0 Lsize=  378144kB time=42.77 bitrate=72423.5kbits/s
video:287196kB audio:670kB global headers:0kB muxing overhead 31.361036%

I can play the output.mp4 nicely (audio video sync is fine). However, when I checked the mediainfo of the output.mp4 it says framerate is
Frame rate : 90 000.000 fps

What happened? How can I force the output to be in 30 or 25 fps?

A: Okay, I got it fixed via:
avconv -i input.mp4 -c:v h264 -crf 25 -c:a mp3 -r 30 output.mp4

The -crf number part did the work. Choose a number that works for you as the lower it comes, the more bitrates are used.
I tried '5' and got somewhere 250k bitrates.


text:
Q: Function to count hashtags I'm trying to get a function that counts and shows hashtags of a list.
Example input:
["Hey, im in the #pool",
 "beautiful #city",
 "#city is nice",
 "Have a nice #weekend",
 "#weekend <3",
 "Nice #"]

Output:
{"pool" : 1, "city" : 2, "weekend" : 2}

But if there is only a # followed by no words, it should not count as a hashtag.
Same with stuff before the hashtag, something like "%#" is not allowed to count as a hashtag.
Hashtags are defined (a-z,A-Z,0-9) every other char ends the hashtag
My current code:
def analyze(posts):
    tag = {}
    for sentence in posts:
        words = sentence.split(' ')
        for word in words:
            if word.startswith('#'):
                if word[1:] in tag.keys():
                    tag[word[1:]] += 1
                else:
                    tag[word[1:]] = 1
    return(tag)

posts = ["Hey, im in the #pool",
         "beautiful #city",
         "#city is nice",
         "Have a nice #weekend",
         "#weekend <3",
         "Nice #"]
print(analyze(posts))

A: In one pass with case insensitive regex search and collections.Counter object:
from collections import Counter
import re

lst = ["Hey, im in the #pool", "beautiful #city", "#city is nice",
       "Have a nice #weekend", "#weekend <3", "Nice #"]

hash_counts = Counter(re.findall(r'#([a-z0-9]+)', ' '.join(lst), re.I))
print(dict(hash_counts))

The output:
{'pool': 1, 'city': 2, 'weekend': 2}

A: Use re with collections.Counter :
import re
from collections import Counter

data  = [ "Hey, im in the #pool",
  "beautiful #city",
  "#city is nice",
  "Have a nice #weekend",
  "#weekend <3",
  "Nice #" ]

count_hashtag = Counter()
for element in data:
    for hast_tag in re.findall('#(\w+)', element):
        count_hashtag[hast_tag] += 1

print(count_hashtag)
# Counter({'city': 2, 'weekend': 2, 'pool': 1})

If you want #City and #city equal:
  count_hashtag[hast_tag.casefold()] += 1

A: Use this:
a = [ "Hey, im in the #pool",
  "beautiful #city",
  "#city is nice",
  "Have a nice #weekend",
  "#weekend <3",
  "Nice #"]
resdict = {}
for item in a:
    for word in item.split():
        if word.startswith('#') and len(word) != 1:
            if word.replace('#', '') not in resdict:
                resdict[word.replace('#', '')] = 1
            else: resdict[word.replace('#', '')] += 1
print(resdict)

A: l = ["Hey, im in the #pool",
 "beautiful #city",
 "#city is nice",
 "Have a nice #weekend",
 "#weekend <3",
 "Nice #"]

from collections import defaultdict
def func(l):

    dic = defaultdict(int)
    for i in l:
        for j in i.split():
            if j[0]=='#' and len(j)>1:
                dic[j[1:]]+=1
    return dict(dic)

print(func(l))

output
{'pool': 1, 'city': 2, 'weekend': 2}


text:
Q: Login logs in Windows 10 The case is that I need to track my office hours so why not to use my windows login time? Is there any chance that windows hold that information? Should I proceed with a custom script to track my login time?
Any help would be much appreciated.

A: I finally solved my problem using this guide.
Long story short,

*

*presswindows + R enter eventvwr.msc

*navigate to System

*check the provided logs

Hope this helps as it helped me :)


text:
Q: UVa-784 Wrong Answer I am going crazy with this problem!
My solution is in Java - I have tried different inputs and haven't been able to reproduce the alleged wrong answer. Maybe someone here could possibly point to my solutions bottlenecks?
The verdict I am getting from UVa judge is "Wrong Answer".
// FOUND THE SOLUTION - I WAS PRINTING null chars at the end of some lines ('\u0000').
The problem is solved by adding if(maze[j][i] != '\u0000') before calling bufferedWriter.write(maze[j][i]
Thanks to everyone!
The intial code:
import java.io.*;

class Main {
    public static final int MAX_NUMBER_OF_LINES = 31;
    public static final int MAX_NUMBER_OF_CHARACTERS_PER_LINE = 81;

    public static char[][] maze;
    public static boolean[][] visitedLocations;
    public static int numberOfMazes;
    public static int numberOfLines;
    public static int numberOfChars;

    public static BufferedReader bufferedReader;
    public static BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out));

    public static void main(String args[]) throws IOException {
        readFromStandardInput();
        bufferedWriter.flush();
    }

    public static void readFromStandardInput() throws IOException {
        bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        String line;
        numberOfMazes = Integer.parseInt(bufferedReader.readLine());
        int lineCounter = 0;
        while (numberOfMazes > 0) {
            maze = new char[MAX_NUMBER_OF_CHARACTERS_PER_LINE][MAX_NUMBER_OF_LINES];
            visitedLocations = new boolean[MAX_NUMBER_OF_CHARACTERS_PER_LINE][MAX_NUMBER_OF_LINES];
            lineCounter = 0;
            while ((line = bufferedReader.readLine()) != null) {
                if (line.charAt(0) == '_') {
                    break;
                } else {
                    constructArrayLineByLine(line, lineCounter);
                }
                lineCounter++;
            }
            numberOfLines = lineCounter;
            solvePreviousMaze();
            bufferedWriter.write(line);
            numberOfMazes--;
            if (numberOfMazes > 0) {
                bufferedWriter.write("\n");
            }
        }
    }

    public static void solvePreviousMaze() throws IOException {
        for (int i = 1; i < numberOfLines; i++) {
            for (int j = 1; j < numberOfChars; j++) {
                if (maze[j][i] == '*') {
                    floodTheMaze(i, j);
                    solutionToStandardOutput();
                    return;
                }
            }
        }
    }

    public static void solutionToStandardOutput() throws IOException {
        for (int i = 0; i < numberOfLines; i++) {
            for (int j = 0; j < numberOfChars; j++) {
                bufferedWriter.write(maze[j][i]);
            }
            bufferedWriter.write("\n");
        }
    }

    public static void floodTheMaze(int i, int j) {
        if (visitedLocations[j][i]) {
            return;
        } else {
            visitedLocations[j][i] = true;
        }
        if (maze[j][i] == ' ' || maze[j][i] == '*') {
            maze[j][i] = '#';
            floodTheMaze(i, j - 1);
            floodTheMaze(i - 1, j);
            floodTheMaze(i + 1, j);
            floodTheMaze(i, j + 1);
        }
    }

    public static void constructArrayLineByLine(String line, int numberOfLine) {
        numberOfChars = Math.max(numberOfChars, line.length());
        for (int i = 0; i < line.length(); i++) {
            maze[i][numberOfLine] = line.charAt(i);
        }
    }

}

A: One very clear bug in your solution is that you are printing extra 'space characters' in your solution which is probably not what the question asked. For example, in the first sample output, you are printing extra spaces in the lower 5 lines. You can solve this problem by using an arraylist of array to store the input and then output that arraylist.
Also, you should probably output a new line after every line of output. (You are not doing so for the last line of output.)
Here is a link to my accepted solution for this problem.
import java.io.*;
import java.math.*;
import java.util.*;
import java.lang.*;

public class Main{

    public static InputStream inputStream = System.in;
    public static OutputStream outputStream = System.out;
    public static FastReader in = new FastReader(inputStream);
    public static PrintWriter out = new PrintWriter(outputStream);

    public static void main(String[] args)throws java.lang.Exception{
        new Main().run();
        out.close();
    }

    int N;
    int M;
    boolean[][] dfsNode;
    StringTokenizer tk;
    char[][] grid;
    char[][] filled;
    String[] sep;

    void run()throws java.lang.Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        N = Integer.parseInt(br.readLine().trim());
        sep = new String[N];
        for(int i=0; i<N; i++){
            ArrayList<char[]> al = new ArrayList<char[]>();
            while(true){
                String s = br.readLine();
                if(s.contains("_")){
                    sep[i] = s;
                    break;
                }
                char[] arr = s.toCharArray();
                al.add(arr);
            }
            grid = new char[al.size()][];
            for(int j=0; j<al.size(); j++){
                grid[j] = al.get(j);
            }
            //           ArrayUtils.printGrid(grid);
            int stari = -1;
            int starj = -1;
            for(int j=0; j<grid.length; j++){
                for(int k=0; k<grid[j].length; k++){
                    if(grid[j][k] == '*'){
                        stari = j;
                        starj = k;
                        break;
                    }
                }
            }
            dfsNode = new boolean[grid.length][];
            filled = new char[grid.length][];
            for(int j=0; j<grid.length; j++){
                char[] arr = new char[grid[j].length];
                for(int k=0; k<grid[j].length; k++){
                    arr[k] = grid[j][k];
                }
                filled[j] = arr;
                dfsNode[j] = new boolean[grid[j].length];
            }
            fillColour(stari, starj);
            for(int j=0; j<filled.length; j++){
                for(int k=0; k<filled[j].length; k++){
                    if(filled[j][k] == '*'){
                        out.print(' ');
                    }else{
                        out.print(filled[j][k]);
                    }
                }
                out.println();
            }
            out.println(sep[i]);
        }
    }

    void fillColour(int row, int col){
        if(row<0 || row>=grid.length || col<0 || col>=grid[row].length){
            return;
        }
        if(dfsNode[row][col]){
            return;
        }

        // fill on border?
        if(grid[row][col]!=' ' && grid[row][col]!='*'){
            return;
        }

        filled[row][col] = '#';
        dfsNode[row][col] = true;
        fillColour(row-1, col);
        fillColour(row+1, col);
        fillColour(row, col-1);
        fillColour(row, col+1);
    }
}

class FastReader{
    private boolean finished = false;

    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;
    private SpaceCharFilter filter;

    public FastReader(InputStream stream){
        this.stream = stream;
    }

    public int read(){
        if (numChars == -1){
            throw new InputMismatchException ();
        }
        if (curChar >= numChars){
            curChar = 0;
            try{
                numChars = stream.read (buf);
            } catch (IOException e){
                throw new InputMismatchException ();
            }
            if (numChars <= 0){
                return -1;
            }
        }
        return buf[curChar++];
    }

    public int peek(){
        if (numChars == -1){
            return -1;
        }
        if (curChar >= numChars){
            curChar = 0;
            try{
                numChars = stream.read (buf);
            } catch (IOException e){
                return -1;
            }
            if (numChars <= 0){
                return -1;
            }
        }
        return buf[curChar];
    }

    public int nextInt(){
        int c = read ();
        while (isSpaceChar (c))
            c = read ();
        int sgn = 1;
        if (c == '-'){
            sgn = -1;
            c = read ();
        }
        int res = 0;
        do{
            if(c==','){
                c = read();
            }
            if (c < '0' || c > '9'){
                throw new InputMismatchException ();
            }
            res *= 10;
            res += c - '0';
            c = read ();
        } while (!isSpaceChar (c));
        return res * sgn;
    }

    public long nextLong(){
        int c = read ();
        while (isSpaceChar (c))
            c = read ();
        int sgn = 1;
        if (c == '-'){
            sgn = -1;
            c = read ();
        }
        long res = 0;
        do{
            if (c < '0' || c > '9'){
                throw new InputMismatchException ();
            }
            res *= 10;
            res += c - '0';
            c = read ();
        } while (!isSpaceChar (c));
        return res * sgn;
    }

    public String nextString(){
        int c = read ();
        while (isSpaceChar (c))
            c = read ();
        StringBuilder res = new StringBuilder ();
        do{
            res.appendCodePoint (c);
            c = read ();
        } while (!isSpaceChar (c));
        return res.toString ();
    }

    public boolean isSpaceChar(int c){
        if (filter != null){
            return filter.isSpaceChar (c);
        }
        return isWhitespace (c);
    }

    public static boolean isWhitespace(int c){
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    private String readLine0(){
        StringBuilder buf = new StringBuilder ();
        int c = read ();
        while (c != '\n' && c != -1){
            if (c != '\r'){
                buf.appendCodePoint (c);
            }
            c = read ();
        }
        return buf.toString ();
    }

    public String nextLine(){
        String s = readLine0 ();
        while (s.trim ().length () == 0)
            s = readLine0 ();
        return s;
    }

    public String nextLine(boolean ignoreEmptyLines){
        if (ignoreEmptyLines){
            return nextLine ();
        }else{
            return readLine0 ();
        }
    }

    public BigInteger nextBigInteger(){
        try{
            return new BigInteger (nextString ());
        } catch (NumberFormatException e){
            throw new InputMismatchException ();
        }
    }

    public char nextCharacter(){
        int c = read ();
        while (isSpaceChar (c))
            c = read ();
        return (char) c;
    }

    public double nextDouble(){
        int c = read ();
        while (isSpaceChar (c))
            c = read ();
        int sgn = 1;
        if (c == '-'){
            sgn = -1;
            c = read ();
        }
        double res = 0;
        while (!isSpaceChar (c) && c != '.'){
            if (c == 'e' || c == 'E'){
                return res * Math.pow (10, nextInt ());
            }
            if (c < '0' || c > '9'){
                throw new InputMismatchException ();
            }
            res *= 10;
            res += c - '0';
            c = read ();
        }
        if (c == '.'){
            c = read ();
            double m = 1;
            while (!isSpaceChar (c)){
                if (c == 'e' || c == 'E'){
                    return res * Math.pow (10, nextInt ());
                }
                if (c < '0' || c > '9'){
                    throw new InputMismatchException ();
                }
                m /= 10;
                res += (c - '0') * m;
                c = read ();
            }
        }
        return res * sgn;
    }

    public boolean isExhausted(){
        int value;
        while (isSpaceChar (value = peek ()) && value != -1)
            read ();
        return value == -1;
    }

    public String next(){
        return nextString ();
    }

    public SpaceCharFilter getFilter(){
        return filter;
    }

    public void setFilter(SpaceCharFilter filter){
        this.filter = filter;
    }

    public interface SpaceCharFilter{
        public boolean isSpaceChar(int ch);
    }
}


text:
Q: OpenCV createsamples example I am trying to run the createsamples example from the OpenCV library. I can load in one image at a time and it seems to work fine. However, when I try to load in a collection of images I get a parse error. I am not sure if it is something in my collection file that is invalid or if I am missing something elsewhere. Below is the exact format of my text document.
Text document details:
Target1.JPG 1 0 0 1296 1152
Target2.jpg 1 0 0 1890 709

Command line call:
-info "C:\Users\seb\Desktop\Learning Samples\Target\Target.txt" -num 10 -vec "C:\Users\seb\Desktop\Learning Samples\Target\Target.vec" -maxxangle 0.6 -maxyangle 0 -maxzangle 0.3 -maxidev 100 -bgcolor 0 -bgthresh 0 -w 20 -h 20

Any help is greatly appreciated.

A: The parse error is because when you do not specify the number of pos image samples you want to generate, the createsamples will use the default value which is 1000. But if your annotation text document contains less than 1000 bounding boxes of objects, you will get the parse error. You can still use the .vec file for training cascade. The only problem is that the information of number is incorrect. There are two ways to fix it.

*

*You manually count the number of object bounding boxes in the text document. And specify the value less or equal to the number for the option "-num"
e.g. createsamples -info xxxxx.txt -vec pos.vec -num [value]

*You can revise the OPENCV_ROOT_DIR/modules/haartraining/createsamples.cpp. When the -num is not specified, set the number of pos samples as the number of object bounding boxes in the text document
code snippet:
In createsamples.cpp
int num = 0;
In cvsamples.cpp
void icvWriteVecHeader( FILE* file, int count, int width, int height )
{
    int vecsize;
    short tmp;

    fseek ( file , 0 , SEEK_SET );

    /* number of samples */
    fwrite( &count, sizeof( count ), 1, file );
    /* vector size */
    vecsize = width * height;
    fwrite( &vecsize, sizeof( vecsize ), 1, file );
    /* min/max values */
    tmp = 0;
    fwrite( &tmp, sizeof( tmp ), 1, file );
    fwrite( &tmp, sizeof( tmp ), 1, file );

    fseek ( file , 0 , SEEK_END );
}

int cvCreateTrainingSamplesFromInfo( const char* infoname, const char* vecfilename,
                                     int num,
                                     int showsamples,
                                     int winwidth, int winheight )
{
    char fullname[PATH_MAX];
    char* filename;

    FILE* info;
    FILE* vec;
    IplImage* src=0;
    IplImage* sample;
    int line;
    int error;
    int i;
    int x, y, width, height;
    int total;

    assert( infoname != NULL );
    assert( vecfilename != NULL );

    total = 0;
    if( !icvMkDir( vecfilename ) )
    {

#if CV_VERBOSE
        fprintf( stderr, "Unable to create directory hierarchy: %s\n", vecfilename );
#endif /* CV_VERBOSE */

        return total;
    }

    info = fopen( infoname, "r" );
    if( info == NULL )
    {

#if CV_VERBOSE
        fprintf( stderr, "Unable to open file: %s\n", infoname );
#endif /* CV_VERBOSE */

        return total;
    }

    vec = fopen( vecfilename, "wb" );
    if( vec == NULL )
    {

#if CV_VERBOSE
        fprintf( stderr, "Unable to open file: %s\n", vecfilename );
#endif /* CV_VERBOSE */

        fclose( info );

        return total;
    }

    sample = cvCreateImage( cvSize( winwidth, winheight ), IPL_DEPTH_8U, 1 );

    icvWriteVecHeader( vec, num, sample->width, sample->height );

    if( showsamples )
    {
        cvNamedWindow( "Sample", CV_WINDOW_AUTOSIZE );
    }

    strcpy( fullname, infoname );
    filename = strrchr( fullname, '\\' );
    if( filename == NULL )
    {
        filename = strrchr( fullname, '/' );
    }
    if( filename == NULL )
    {
        filename = fullname;
    }
    else
    {
        filename++;
    }

    while ( num<=0 || total<num )
    {
        int count;

        error = ( fscanf( info, "%s %d", filename, &count ) != 2 );
        if( !error )
        {
            src = cvLoadImage( fullname, 0 );
            error = ( src == NULL );
            if( error )
            {

#if CV_VERBOSE
                fprintf( stderr, "Unable to open image: %s\n", fullname );
#endif /* CV_VERBOSE */
            }
        }
        else
            if ( num <= 0 ) break;

        for( i = 0; i < count; i++, total++ )
        {
            error = ( fscanf( info, "%d %d %d %d", &x, &y, &width, &height ) != 4 );
            if( error ) break;
            cvSetImageROI( src, cvRect( x, y, width, height ) );
            cvResize( src, sample, width >= sample->width &&
                      height >= sample->height ? CV_INTER_AREA : CV_INTER_LINEAR );

            if( showsamples )
            {
                cvShowImage( "Sample", sample );
                if( cvWaitKey( 0 ) == 27 )
                {
                    showsamples = 0;
                }
            }
            icvWriteVecSample( vec, sample );

                        if ( num > 0 && total >= num ) break;
        }

        if ( num<=0 )
            icvWriteVecHeader( vec, total, sample->width, sample->height );

        if( src )
        {
            cvReleaseImage( &src );
        }

        if( error )
        {

#if CV_VERBOSE
            fprintf( stderr, "%s(%d) : parse error", infoname, line );
#endif /* CV_VERBOSE */

            break;
        }

        }

    if( sample )
    {
        cvReleaseImage( &sample );
    }

    fclose( vec );
    fclose( info );

    return total;
}

A: I struggled to get opencv_createsamples to work on my windows machine, and it just worked successfully.  I thought I would post the details to help someone else.  I am using opencv 2.4.8 on Windows 7.
First, I found I needed to use the opencv_createsamples.exe file in the directory that is listed in my path variable as OPENCV_DIR.  I could not copy the exe file to some more convenient place.
I set up a sub directory text_classifier in this directory for my images and my text files. I used this command on the command line:

F:\Apps\opencv\build\x64\vc10\bin>opencv_createsamples.exe -vec
  text_classifier\text_binary_desc -info
  text_classifier\positive_examples.txt -num 146 -w 1350 -h 900 -bg
  text_classifier\negative_samples.txt

Notice that I had to list the number of selected areas in the images (-num 146).  I also listed the width and height of the positive samples.
Inside the file positive_examples.txt, I needed to have the files listed so:

text_positives_clean\1839_Boettiger_001.JPG 1 708 35 471 793

In other words, the files had to be listed relative to the file positive_examples.txt, and not relative to the exe file (opencv_createsamples.exe).  When I tried listing the files relative to the exe, such as:

text_classifier\text_positives_clean\1839_Boettiger_001.JPG 1 708 35 471 793
then I got the error: Unable to open image:
  text_classifier\text_classifier\text_positives_clean\1839_Boettiger_001.JPG

Then I noticed that my special automated system of creating this file somehow had missed loading some files into the directory, so there were files listed in positive_examples.txt that were not in the directory.  The exe simply fell over if it found something listed in positive_examples.txt that was not in the directory.  I filled the gaps in the image directory.
Then I got a strange error: Unable to open image: 129
I discovered that I had made this mistake:

text_positives_clean\1862_Streckfuss_0006.JPG 1 813 502 382 353 129 46
  526 798 682 780 117 67

Do you notice that the number of selected areas stated here is 1 (the number just following 'JPG'), while the number of selected areas is really 3?  So opencv_createsamples.exe tried to open the next thing it found as an image, i.e. '129', after getting the single selected area.  And it fell over again.
So I changed the 1 to a 3.  Then I got a parse error that actually gave me a line number in my positive_examples.txt file.  I went to that line, and found that one of my entries did not have a space between the selected areas, such as:

949 315 157 67131 30 513 806

I fixed this, adding the space, and finally the exe did all my 146 samples.  Yoohoo!
Hope this helps someone.  :-)

A: One of the reason might be because of info file.
/home/mine/face detector image/positives/*.jpg
Make sure that any of the folder name should not have space in its name. like shown above "face detector image", this should be some other name like "images" or any thing without space in it.
Rename the folder at its original path as-well as in .info file.
Cheers!!

A: Target1.JPG - it must be relative path to createsamples.exe. Not to Target.txt.
I've tested it on my machine and got such results:
d:\Programs\OpenCV-2.2.0\msvs-build\bin\Release>opencv_createsamples.exe -info "d:\Programs\OpenCV-2.2.0\msvs-build\bin\Release\Target.dat" -num 10 -vec "d:\Programs\OpenCV-2.2.0\msvs-build\bin\Release\Target.vec" -maxxangle 0.6 -maxyangle 0 -maxzangle 0.3 -maxidev 100 -bgcolor 0 -bgthresh 0 -w 20 -h 20
Info file name: d:\Programs\OpenCV-2.2.0\msvs-build\bin\Release\Target.dat
Img file name: (NULL)
Vec file name: d:\Programs\OpenCV-2.2.0\msvs-build\bin\Release\Target.vec
BG  file name: (NULL)
Num: 10
BG color: 0
BG threshold: 0
Invert: FALSE
Max intensity deviation: 100
Max x angle: 0.6
Max y angle: 0
Max z angle: 0.3
Show samples: FALSE
Width: 20
Height: 20
Create training samples from images collection...
d:\Programs\OpenCV-2.2.0\msvs-build\bin\Release\Target.dat(3) : parse errorDone. **Created 2 samples**


text:
Q: StatefullSession repeat load classes - causes performance issuses I have a server that gets request and use DROOLS to evaluate the request.
For each incoming request I create a new statefull session, insert facts (can be more than 100 facts), fire all the rules and dispose of the session.
I find that every insert of a fact causes drools to go to ProjectClassLoader.loadClasss() which is synchronized and blocks my threads (I'm running up to available processor threads with service executor, and this causes performance issues).
It is important to illustrate that all the fact in question are identical. we use multiple threads to evaluate several different request that have the same code as the facts. We would expect Drools to not have to reload the classes over and over again.
Any idea how we can avoid having drools go to the synchronized loadClass() code for every single insert?


text:
Q: Sphinx 2.0.2 Filtering sql_attr_string Attributes Firstly, let me say that I know that http://sphinxsearch.com/docs/current.html#conf-sql-attr-string says "strings can only be used for storage and retrieval" and that "They can not participate in expressions, be used for filtering, sorting, or grouping"...
Having said that, using Sphinx 2.0.2, accessing the index via both the SQL interface (on port 9306) as well as via SphinxSE I am able to sort, at least, on a string attribute I have.
So although that doesn't necessarily mean that the documentation is completely wrong, it does leave me with a small amount of hope that I can filter by that string attribute, too.
Unfortunately I don't know if I can, and if I can, I don't know how.
Can someone here please put me out of my misery?
[EDIT]
The attribute is 'mail_street_name' and I've tried filtering it a number of ways. Trying to filter on 'box', for example, in the SphinxSE query string I've tried filter=mail_street_name,box, filter=mail_street_name,"box" and filter=mail_street_name,\'box\' (escaped because it sits inside a string). These queries result in no change to the result set (as if I didn't try and filter on that attribute at all).
With the MySQL connection on port 9306 I've tried WHERE mail_street_name='box', WHERE mail_street_name="box", WHERE mail_street_name=box and using LIKE instead of =, all to be given a syntax error (Error 1064 (42000)) from SphinxQL.
Many thanks.

A: As I stated in my last comment, you could try defining a field (http://sphinxsearch.com/docs/current.html#conf-sql-field-string).
You could do a WHERE MATCH((@mail_street_name '*box*'))
And according to the documentation, you are still able to sort on it also


text:
Q: Homomorphism or derivation conserving irreducibility Let $R$ be a integral domain and $\phi$ be an automorphism of $R$. For a given element $x \in R$, we consider a sequence $(\phi^n(x))_{n=0}^{\infty}$.
I wonder if there is any related theory to determine when $\phi^n(x)$ is irreducible for all $n \in \mathbb Z_{\geq 0}$. It depends on $x$ and $\phi$ of course.
More precisely, I want to know about a specific case, not so general: $R=k[x_1,\ldots,x_n]$, where $k$ is a field.
Any suggestions and comments are welcome.
--
I want to know about the derivation, so I edit the question.
Let $R$ be an algebra not just a ring. In fact I wonder only when $R$ is a polynomial ring, which is an $k$-algebra, and $\phi$ is not a ring homomorphism, but just a derivation. (Which is an $k$-module homomorphism).
Or more generally, $R$:integral domain, and $\phi$ is a derivation (satisfying Leibniz rule and group homomorphism).


text:
Q: How to get the order of texts in grid layout after drag and drop operation is done in android I have a grid layout with texts where I can perform drag and drop. Everything is working fine but I want to record the order of the grid layout or text after some DRAG AND DROP OPERATION is done. I tried getting the texts after the drag is performed but its not giving me updated position.
Here is my code where I generate 'n' number of text views dynamically and add it to GRID LAYOUT
    text = new TextView[sizeofgrid];
    for (int i = 0; i < sizeofgrid; i++) {
        text[i] = new TextView(MainActivity.this); // create the txt view
        first = new GridLayout.LayoutParams();
        first.width = pergrid;
        text[i].setLayoutParams(first);
        text[i].setGravity(Gravity.CENTER);
        first.height = LinearLayout.LayoutParams.MATCH_PARENT;
        text[i].setText(String.valueOf(finallist.get(i)));

        text[i].setTextSize(20);
        text[i].setBackgroundResource(R.drawable.back);
        text[i].setTextColor((Color.parseColor("#0B0B0B")));
        //  text[i].setPadding(5, 25, 10, 25);
        text[i].setPadding(5, 10, 0, 25);
         first.setMargins(0, 10, 5, 20);// margin can be set nly to layout and cant be set directly to textview
        text[i].setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                final ClipData data = ClipData.newPlainText("", "");
                View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
                view.startDrag(data, shadowBuilder, view, 0);
                view.setVisibility(View.VISIBLE);
                Log.d(tag, "calleddd");
                return true;
            }
        });

Here is the code which performs drag
   class DragListener implements View.OnDragListener {
    @Override
    public boolean onDrag(View v, DragEvent event) { // the view which we are dragging and the events whcih gets triggred

       final View view = (View) event.getLocalState();
        switch (event.getAction()) {
            case DragEvent.ACTION_DRAG_LOCATION: // if the shadow of the view is within the bounds for a long amt of time , it will get triggred
                // do nothing if hovering above own position
                dragflag = true;
                if (view == v) return true; // can or cant be thr..makes no diff
                // get the new list index
                final int index = calculateNewIndex(event.getX(), event.getY()); // as soon as we start moving from current pos, it will start
                //calculating new value and will get relocated
                // remove the view from the old position
                gl.removeView(view); //remove the view from original pos
                // and push to the new
                gl.addView(view, index); // add the view to newly cal pos
                break;
            case DragEvent.ACTION_DROP:
                view.setVisibility(View.VISIBLE);
                //tested by retrieving the text of textview after dropping but it hasn't got updated.

                for(int i = 0; i < sizeofgrid; i++)
                {
                    Log.d(tag,"thetexssis"+text[i].getText().toString());
                }
                break;
            case DragEvent.ACTION_DRAG_ENDED:
                if (!event.getResult()) {
                    view.setVisibility(View.VISIBLE);

                }
                break;
        }
        return true;
    }
}

I tested by retrieving the text of the text view but it gives me the same order of text before drag and drop is performed. I don't know how to get the order of the current text view in grid layout.
Any help would be great !! Thanks

A: I have resolved by the following code,
    for (int k = 0; k < sizeofgrid; k++) {
        View view = gl.getChildAt(k);
        Log.d(tag,"droppedis");
        // Do something with v.
        if (view instanceof TextView) {
            TextView editText = (TextView) view;
            arr.add(editText.getText().toString());
            Log.d(tag, "thelistis" + arr);
        }

    }

I am getting all the views from the parent and checking if its an instance of textview. If so, then I am getting the text from the textview and storing in a list.


text:
Q: iPod Touch on device debugging crashes (EXC_BAD_INSTRUCTION, EXC_BAD_ACCESS) I'm using iPod Touch 2G as a developement device with Xcode 3.1.3. When I try to trace the execution on the device from a breakpoint in the debugger I get EXC_BAD_INSTRUCTION, EXC_BAD_ACCESS or some error with debugger not being able do disassemble something. The same thing will work properly on iPhone Simulator. Previously I've been able to trace the execution from a breakpoint on some other iPod Touch 2G and iPhone 3G devices.
If not interrupted with a breakpoint the app will work properly. Also before any "stepping" I can investigate variables currently on the stack and their values seem to be correct.
Is it possible that the device is somehow flawed or should I look into my project configuration more closely (and what should I look for)?
EDIT: After playing with project configuration I've found that debugger starts to act normally after disabling "Compile for Thumb" option. The question now is why is it so?

A: Check your build setting, whether it was in iOS 3.2 or lower than latest. This issue I have solved by changing the Base SDK to the latest iOS 4.0 in my project settings.
Good luck

A: This post saved me hours.  It should be all you need to dig deep enough to see just what the root issue is.  http://www.codza.com/how-to-debug-exc_bad_access-on-iphone
Good Luck!


text:
Q: Laravel whereRaw with a few parameters Using Laravel 5.4 I am trying to run this query that gets me results on phpMyAdmin:
select * from `orders`
inner join `users` on `user_id` = `users`.`id`
where `status` = ?
and (`orders`.`id` LIKE ? or `first_name` LIKE ? or `last_name` LIKE ? or `company` LIKE ?

The problem is, although I get results in phpMyAdmin I get an empty result in the code.
I tried two ways:
    $orders =  Order::join('users', 'user_id', '=', 'users.id')
    ->whereRaw("status = ? and (orders.id LIKE '%?%' or first_name LIKE '%?%' or last_name LIKE '%?%' or company LIKE '%?%')",
[$status, $search, $search, $search, $search])->get();

And
    $orders =  Order::join('users', 'user_id', '=', 'users.id')
    ->whereRaw("status = :status and
(orders.id LIKE :search_id or first_name LIKE :search_first or last_name LIKE :search_last or company LIKE :search_company)",
    ['status'=>$status, 'search_id'=>$search, 'search_first'=>$search, 'search_last'=>$search, 'search_company'=>$search])
    ->get();

What am I doing wrong?

A: I solved this like this:
$search = '%' . $request->input('search.value') . '%';

        $orders =  Order::join('users', 'users.id', '=', 'orders.user_id')
                ->whereRaw("status = ? and (orders.id LIKE ? or first_name LIKE ? or last_name LIKE ? or company LIKE ?)",[$status, $search, $search, $search, $search])


text:
Q: How can I display different icons for same file extension Visual Studio has *.SLN files for 2008, and 2010.
In explorer, the icon associated with the file is based on the version somehow. I was always under the impression that the associated icon just looked at the extension, but obviously there is more going on.
I'm asking on stack overflow as a developer - for my application, but if you feel this belongs on another forum, I'm happy to move the discussion elsewhere.
Thank you!

A: Have a look at HKEY_CLASSES_ROOT\VisualStudio.Launcher.sln\ShellEx\IconHandler. The icon is handled by a shell extension, not the usual way with a DefaultIcon.
MSDN's Creating Icon Handlers page shows you how to create the shell extension DLL that provides the icons.

A: I found some Delphi code at http://www.delphi3000.com/articles/article_3285.asp that seems to do the job.  Maybe this can give you some inspiration.
EDIT: site does not exist anymore, using web.archive.org provided by @samir105


text:
Q: Kali linux update and package installation error i installed anonsurf on Kali Linux in VMware and now i can't use apt-get install  or apt-get update
and i can't uninstall it or stop it i don't know why

You might want to run 'apt --fix-broken install' to correct these.
The following packages have unmet dependencies:
beef : Depends: libcattle-1.0-0 (>= 1.2.0) but it is not going to be installed
kali-anonsurf : Depends: i2p but it is not going to be installed
Recommends: gtkdialog but it is not installable
Recommends: gufw but it is not going to be installed
E: Unmet dependencies. Try 'apt --fix-broken install' with no packages (or specify a solution).

this is the error of tring to install a package

Err:1 https://http.kali.org/kali kali-rolling InRelease
Temporary failure resolving 'http.kali.org'
Err:2 http://deb.i2p2.no unstable InRelease
Temporary failure resolving 'deb.i2p2.no'
Reading package lists... Done
W: Failed to fetch https://http.kali.org/kali/dists/kali-rolling/InRelease  Temporary failure resolving 'http.kali.org'
W: Failed to fetch http://deb.i2p2.no/dists/unstable/InRelease  Temporary failure resolving 'deb.i2p2.no'
W: Some index files failed to download. They have been ignored, or old ones used instead.

and this is the error of apt-get update
i tried apt-get remove anonsurf but it says unable to locate package anonsurf
also, anonsurf works when i use anonsurf -h or any anonsurf command
i deleted the anonsurf directory from root and nothing happened and i tried anonsurf stop and anonsurf stopi2p didn't work so how to fix this
                                                                                Thanks in advance.

A: The issue is in the Kali repository. It can be fixed by adding following lines to /etc/apt/sources.list.d/i2p.list
deb https://deb.i2p2.de/ buster main
deb-src https://deb.i2p2.de/ buster main
Then, run apt update


text:
Q: Backbone Client Side Collection Filtering Consider a backbone app that has a select list of categories, and a table of files underneath it. All files, regardless of the category they belong to are in the App.collection.files collection. When a user selects a new category, I'd like to filter the table to only show those matching files.
I'd like to do this completely on the client side. I do NOT want to fetch a new list of files from the server each time a new category is picked.
I plan to to a App.collection.files.where({category_id: xx}) within App.View.Files.render() to accomplish the filtering itself.
What is the best Backbone-y way to trigger/respond to an event to get this working?
One idea I am playing with is another collection, that contains the filtered files, but not sure if this is the best approach.
App.View.FilesPage = Backbone.View.extend({
    template: App.utils.template('files-page'),
    className: 'container-fluid',
    initialize: function(){
        this.render();
    },
    render: function(){
        this.$el.html(this.template());

        this.$el.find('.categories').append(
            new App.View.Categories({collection:App.collection.categories}).el
        );

        this.$el.find('.files table').append(
            new App.View.Files({collection:App.collection.files}).el
        );

        return this;
    }
});

App.View.Categories = Backbone.View.extend({
    tagName: 'select',
    events: {
        'change': 'onChange'
    },
    initialize: function(){
        this.$el.attr('size', this.collection.length + 1);

        this.render();
    },
    render: function(){
        var option = function(value, text, isSelected){
            return $('<option></option>', {'value':value, 'text':text});
        };

        this.$el.html(option(0, 'All Documents'));

        this.$el.append(
            this.collection.invoke(function(){
                return option(this.get('category_id'), this.get('title'));
            })
        ).val(0);

        return this;
    },
    onChange: function(event){

    }
});

App.View.Files = Backbone.View.extend({
    tagName: 'tbody',
    initialize: function(){
        this.render();
    },
    render: function(){
        this.$el.html(
            this.collection.invoke(function(){
                return new App.View.File({model:this}).el;
            })
        );

        return this;
    }
});

A: Here is one solution I came up with, that seems fine and dandy on the surface.
Code changes are called out within comments.
Thoughts on this solution, and completely different solutions are welcome.
App.View.FilesPage = Backbone.View.extend({
    template: App.utils.template('files-page'),
    className: 'container-fluid',
    initialize: function(){
        // CHANGE: Store application wide reference to 'Categories' model
        App.model.categories = new App.Model.Categories();

        this.render();
    },
    render: function(){
        this.$el.html(this.template());

        this.$el.find('.categories').append(
            new App.View.Categories({
                // CHANGE: Pass model into 'Categories' view
                model: App.model.categories,
                collection: App.collection.categories
            }).el
        );

        this.$el.find('.files table').append(
            new App.View.Files({collection:App.collection.files}).el
        );

        return this;
    }
});

App.View.Categories = Backbone.View.extend({
    tagName: 'select',
    events: {
        'change': 'onChange'
    },
    initialize: function(){
        this.$el.attr('size', this.collection.length + 1);

        this.render();
    },
    render: function(){
        var option = function(value, text, isSelected){
            return $('<option></option>', {'value':value, 'text':text});
        };

        this.$el.html(option(0, 'All Documents'));

        this.$el.append(
            this.collection.invoke(function(){
                return option(this.get('category_id'), this.get('title'));
            })
        ).val(0);

        return this;
    },
    onChange: function(){
        // CHANGE: Update attribute within 'Categories' model
        this.model.set('category_id', this.$el.val());
    }
});

App.View.Files = Backbone.View.extend({
    tagName: 'tbody',
    initialize: function(){
        this.collection.on('reset', this.render, this);
        // CHANGE: Listen for change on 'Categories' model, and re-render this view
        App.model.categories.on('change:category_id', this.render, this);

        this.render();
    },
    render: function(){
        this.$el.html(
            _.invoke(this.getFilteredFiles(), function(){
                return new App.View.File({model:this}).el;
            })
        );

        return this;
    },
    // CHANGE: Return a filtered set of models from collection, based on 'Categories' model attributes
    getFilteredFiles: function(){
        var categoryId = App.model.categories.get('category_id');

        if (categoryId!=0){
            return this.collection.where({'category_id': categoryId});
        }
        else{
            return this.collection.models;
        }
    }
});


text:
Q: Scrolling a patterned background on UIView I have a simple UIView which I'm filling with a patterned background, like this
    self.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"backgroundPattern"]];

I want to be able to manipulate the origin of the view by modifying its bounds property and have the background move with the change in origin (as if the background is fixed to the content, not floating behind it).  Is this possible?  Currently the background seems fixed to the view's frame instead of its bounds and the pattern doesn't scroll when the content scrolls.
To change the origin I'm using a block animation like this
self.bounds = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
[UIView animateWithDuration:1. delay:0. options:UIViewAnimationOptionRepeat animations:^{
    self.bounds = CGRectMake(0, 100, self.bounds.size.width, self.bounds.size.height);
} completion:nil];

With that code, my child views repeatedly scroll and reset, but the background stays fixed in place. Is it possible to specify a background which scrolls with the view instead?

A: I haven't been able to find anything on making a background pattern "stick" to the view's origin system.  My solution for my app has been to make a child view and set the background pattern on that.  Then the child view will move with the origin change and the background pattern will follow it.  The problem with that solution is that the child view has to be large enough to cover the range of potential origins, which can be difficult to handle if the content area might be arbitrarily large.

A: You could generate an instance of your view again in the direction the user pans  and add it to an NSMutableArray to be accessed and moved based on the offset of the world.


text:
Q: Angular material data table Scenario:

*

*I used angular material data table to show user data.

*I need to label those data with red color which will come under this
criteria:

*

*100 minutes of outdoor games, or

*50 minutes of indoor games, or

*a proportionate mix of both, e.g. 75 minutes of indoor and 120 minutes of
outdoor games.

I am able to show whole data through json.
I need how to show those user data red who come under above criteria.

A: Try to add something like this:
[style.background-color]="isCondition ? 'green' : 'red'"


text:
Q: MySQL Audit for particular database How to get audit log file for particular database in MySQL. Since databases is in server i am not having any authority for admin permission.But I need Audit Log file.Is there query or method to get all the audit files

A: Afaik there's no way to retrieve the audit log via sql... however you can find some settings regarding it :
SHOW VARIABLES LIKE 'audit_log%';

You can read more here. Bottom line is you need shell access in order to retrieve it.


text:
Q: Manage Consumable IAP promo code I would like to know how to manage an In-App Purchase bought using a promo code.
In particular in my app I have a consumable that enables a feature, so I was wondering how to get the event that someone has bought that iap using a promo code, so that a can enable the feature.
Thanks


text:
Q: NetBeans with Connector/J Well I'm working on a GNU/Linux machine and I'm still learning how to connect to my database
 I've got the Connector/J File downloaded and edited my CLASSPATH, here's the reusult of echoing the path
/home/user/Connector-J/mysql-connector-java-5.1.30/mysql-connector-java-ver-bin.jar:

I also have my SQL File.. let's say: sqlfile.sql
Threw the documentation and while searching I found how I should connect to the Connector.. My question is: where should I put my SQL file?
Also, Here's a piece of code I found that is used to connect, is it right?
           String userName = "root";
           String password = "password";
           String url = "jdbc:mysql://localhost/somefile";
           Class.forName ("com.mysql.jdbc.Driver");
           conn = DriverManager.getConnection (url, userName, password);
           System.out.println ("Database connection established");

A: To build an application that connects to a database, you will need:

*

*A database engine (e.g. MySQL, SQL Server, Oracle, etc)

*A JDBC driver library (e.g. Connector/J for MySQL, jTDS for SQL Server, ojdbc for Oracle, etc)

*Java application itself.

Your code is only creating connection. Even that, the url looks incorrect. The "somefile" should be replaced with the name of database schema you want to connect to.
To interact with database, creating connection is still far from done.
To read, insert, update, delete, etc records from/to database, you need to create statement object by passing your SQL query.
The SQL queries should not be put in a file, but written in your code instead.
Complete JDBC tutorial is here: http://docs.oracle.com/javase/tutorial/jdbc/


text:
Q: Which Dimensions and Metrics of Google Ad Manager account should be selected? I am trying to create a report in Google Ad Manager account which can record all the ads of all the advertisers in a given website
I am not sure which dimensions and metrics should be selected in the Ad Manager account for generating this type of report
Taken help from this but didn't find anything relevant https://support.google.com/admanager/table/7531695?hl=en
Any help/suggestion will be highly appreciated.TIA

A: here are the steps that will help you generate a report in the Google Ad Manager:

*

*Go to the Home page and select Reporting. Click on New report.

*Name the report and scroll down to Dimensions. Here, select Delivery and then Advertisers.

*Then, scroll down to Metrics, and select the metrics you want to view. You can select multiple metrics at once such as Impressions, Revenue, Clicks, etc.

A: In order to list all the ads of all the advertisers in a given website, you can select :

*

*DIMENSIONS

*

*ad units

*advertisers

*orders

*line items

*STATISTICS

*

*Impressions

You can also add filters on ad units if you need to get data for a specific site.
Hope this helps.


text:
Q: is there any trick or extension tool for play MP4 H.263 format on JwPlayer6? I know Jwplayer6 can not support from MP4 H.263 format. (+)
Is there any trick or extension tool for play MP4 H.263 format on JwPlayer6?


text:
Q: Is it possible to use command listed in GlassVoice.apk but not enumerated in VoiceTriggers.Command? I see a lot of commands in GlassVoice.apk from http://pastebin.com/PmiJjbHU on http://www.reddit.com/r/googleglass/comments/235oe5/google_glass_next_target_japan/.
If so can I use them? Should I use "com.google.android.glass.permission.DEVELOPMENT" permission?
The reason why I ask this question is that in Distribute page, I see "Glassware uses approved voice commands". I already see my approved command I committed months ago in that list. But not in VoiceTriggers.Command.
Thanks

A:
When you want to start Glassware and have it appear in MyGlass, you must use one of the existing commands defined in the VoiceTriggers.Command enum (this also means a Glass system update must happen for new voice commands to work).

The answer I believe, is no.


text:
Q: How to detect if file in IDE is being edited using Open Tools API I made a small IDE plug-in using Open Tools API that accesses ClearCase. It has menu items "Check In", "Check Out", etc. It works OK but I want it to check out a read-only file automatically if I start typing in IDE editor or if I attempt to save the file. Do you think this is possible?
I tried a few things but gave up eventually. IOTAEditorServices.KeyboardServices has AddKeyboardBinding method which looked promising. Using it I added a notifier with binding type btPartial (and later tried btComplete) and the plug-in started detecting some shortcut key presses but not all keyboard events, far from it... Any ideas would be much appreciated!

A: I think a "cleaner" way is to hook up a IOTAEditorNotifier to each editor and have your IOTAEditor.Modified method called by the IDE whenever the contents of the editor is modified, whether by keyboard, mouse or programmatically from another plugin.
Here's an example which registers an IOTAIDENotifier to be notified of files being opened in the IDE so it can register its IOTAEditorNotifier instances.

A: I must be possible somehow: we use SourceConexion (http://www.epocalipse.com/scx.htm) here, which auto checks-out the file before you edit the source or change the form.
JVCS has IDE integration support, it is open source, maybe they have implemented this too:
http://jedivcs.sourceforge.net/


text:
Q: increasing security in an ASP.NET automation web site I've created a medium-sized web-based automation project for a university (VS2010,C#,ASP.NET,SQL Server 2008), now they have asked me to give some proposals in order to increase site security, what can I tell them? what are my options? encrypting the data? changing the passwords periodically? what else can I do? of course I know security is not a couple of codes that can simply be added to a huge program, but I'm searching for general approaches that can be pursued in order to increase security, any suggestion would be highly appreciated
thanks

A: Here is a good set of articles that you may want to take a look at that may start you off in the right direction.

A: Please also have a look into this MSDN Magazine article on ASP.NET Security: http://msdn.microsoft.com/en-us/magazine/hh580736.aspx.


text:
Q: can a windows 8 application listen for events / external web service calls - web hooks I am looking to build a windows 8 RT application which needs to be activated by events that happen out side of the windows 8 application.
I have seen lots of potential ways this MGIHT be able to be accomplished, but nothing that seems to cover all "events" :-)
The scenario I am hopg to deal with is as follows
Windows 8 surface app sits in a "listening" mode. PC on the network carries out an action. The action could probably result in a web service call. The windows 8 app listens for the call and then opens a screen.
The std method seems to be to reccomend using Windows Notification Services, but this seems over kill and there might not be access from an internal network to an external WNS.
I have seen blogs on local notifications, where the app listens ( in this case the app will be listening in full screen mode ) and reacts.
I have also seen blogs on creating a local windows service on the application.
This seems to suggest that an windows service could expose an endpoint, which when hit with a call could raise some event to the app to make it respond e.g. open / close a form etc.
Is this a common pattern, or is there a better way to do this ?
I would be keen to hear what if anything others have used to solve this issue ?
I really want to avoid the app having to poll somewhere every second or two.
The other last resort is to use a fileMonitor type actvity and get the service to write a file or for the external PC to write a file into a shared dir ?
B...


text:
Q: Why is device.uuid returning as null in phonegap build? I am developing an app through PhoneGap Build and have included the following plugins in my config.xml:
<gap:plugin name="org.apache.cordova.device" version="0.2.8"/>
<gap:plugin name="org.apache.cordova.dialogs" version="0.2.6"/>
<gap:plugin name="org.apache.cordova.vibration" version="0.3.7" />

I copy/pasted code from the documentation and created a test page within the app itself and all values returned for device are being returned as null.  I'm not sure what I'm doing wrong, but I would like to know if I'm missing something or if there's any additional steps I need to take.  The code I used to test within the app is the following:
<!DOCTYPE html>

    <title>Device Properties Example</title>

Loading device properties...


text:
Q: Как в Python отсортировать список? У меня есть список a = [6, 3, 7, 3, 6 , 0, 8] для примера. Как сделать так, чтобы было a = [0, 3, 3, 6, 6, 7, 8]
То есть, потом я переберу этот список:
i = 0
while i < len(a):
    print(a[i])
    a += 1

Как это сделать?

A: Если надо не менять исходный список, а получить новый то лучше использовать sorted
a = [6, 3, 7, 3, 6 , 0, 8]
new_a = sorted(a)

также у вас неправильно сделан цикл while. Он должен быть таким:
i = 0
while i < len(a):
    print(a[i])
    i += 1

Но лучше использовать цикл for
for el in sorted(a):
    print(el)

Если вам нужен индекс элемента, то так:
a = sorted(a)
for i in range(len(a)):
    print(i, a[i])

также можно использовать enumerate
for i, el in enumerate(sorted(a)):
    print(i, el)

A: Пусть:
a = [6, 3, 7, 3, 6 , 0, 8]

Тогда его можно отсортировать 2 способами:
a = sorted(a)

Или:
a.sort()

Получиться:
print(' '.join(map(str,a)))

Вывод:
0 3 3 6 6 7 8

A: Массив сортируется при помощи a.sort() и запомните print(a.sort()) будет None, то есть .sort() ничего не возращает
И ещё вы перебираете при помощи цикла while, хотя можно и при помощи for:
for i in a:
    print(i)

A: Что бы отсортировать список достаточно использовать
sort(a)


text:
Q: Efficiently sum a small numpy array, broadcast across a ginormous numpy array? I want to calculate an indexed weight sum across a large (1,000,000 x
3,000) boolean numpy array.  The large boolean array changes
infrequently, but the weights come at query time, and I need answers
very fast, without copying the whole large array, or expanding the
small weight array to the size of the large array.
The result should be an array with 1,000,000 entries, each having the
sum of the weights array entries corresponding to that row's True
values.
I looked into using masked arrays, but they seem to require building a
weights array the size of my large boolean array.
The code below gives the correct results, but I can't afford that copy
during the multiply step.  The multiply isn't even necessary, since
the values array is boolean, but at least it handles the broadcasting
properly.
I'm new to numpy, and loving it, but I'm about to give up on it for
this particular problem.  I've learned enough numpy to know to stay
away from anything that loops in python.
My next step will be to write this routine in C (which has the added
benefit of letting me save memory by using bits instead of bytes, by
the way.)
Unless one of you numpy gurus can save me from cython?
from numpy import array, multiply, sum

# Construct an example values array, alternating True and False.
# This represents four records of three attributes each:
#    array([[False,  True, False],
#           [ True, False,  True],
#           [False,  True, False],
#           [ True, False,  True]], dtype=bool)
values = array([(x % 2) for x in range(12)], dtype=bool).reshape((4,3))

# Construct example weights, one for each attribute:
#    array([1, 2, 3])
weights = array(range(1, 4))

# Create expensive NEW array with the weights for the True attributes.
# Broadcast the weights array into the values array.
#    array([[0, 2, 0],
#           [1, 0, 3],
#           [0, 2, 0],
#           [1, 0, 3]])
weighted = multiply(values, weights)

# Add up the weights:
#    array([2, 4, 2, 4])
answers = sum(weighted, axis=1)

print answers

# Rejected masked_array solution is too expensive (and oddly inverts
# the results):
masked = numpy.ma.array([[1,2,3]] * 4, mask=values)

A: The dot product (or inner product) is what you want. It allows you to take a matrix of size m×n and a vector of length n and multiply them together yielding a vector of length m, where each entry is the weighted sum of a row of the matrix with the entries of the vector of as weights.
Numpy implements this as array1.dot(array2) (or numpy.dot(array1, array2) in older versions). e.g.:
from numpy import array

values = array([(x % 2) for x in range(12)], dtype=bool).reshape((4,3))

weights = array(range(1, 4))

answers = values.dot(weights)
print answers
# output: [ 2 4 2 4 ]

(You should benchmark this though, using the timeit module.)

A: It seems likely that dbaupp's answer is the correct one. But just for the sake of diversity, here's another solution that saves memory. This will work even for operations that don't have a built-in numpy equivalent.
>>> values = numpy.array([(x % 2) for x in range(12)], dtype=bool).reshape((4,3))
>>> weights = numpy.array(range(1, 4))
>>> weights_stretched = numpy.lib.stride_tricks.as_strided(weights, (4, 3), (0, 8))

numpy.lib.stride_tricks.as_strided is a wonderful little function! It allows you to specify shape and strides values that allow a small array to mimic a much larger array.  Observe -- there aren't really four rows here; it just looks that way:
>>> weights_stretched[0][0] = 4
>>> weights_stretched
array([[4, 2, 3],
       [4, 2, 3],
       [4, 2, 3],
       [4, 2, 3]])

So instead of passing a huge array to MaskedArray, you can pass a smaller one. (But as you've already noticed, numpy masking works in the opposite way you might expect; truth masks, rather than revealing, so you'll have to store your values inverted.) As you can see, MaskedArray doesn't copy any data; it just reflects whatever is in weights_stretched:
>>> masked = numpy.ma.MaskedArray(weights_stretched, numpy.logical_not(values))
>>> weights_stretched[0][0] = 1
>>> masked
masked_array(data =
 [[-- 2 --]
 [1 -- 3]
 [-- 2 --]
 [1 -- 3]],
      mask =
 [[ True False  True]
 [False  True False]
 [ True False  True]
 [False  True False]],
      fill_value=999999)

Now we can just pass it to sum:
>>> sum(masked, axis=1)
masked_array(data = [2 4 2 4],
      mask = [False False False False],
      fill_value=999999)

I benchmarked numpy.dot and the above against a 1,000,000 x 30 array. This is the result on a relatively modern MacBook Pro (numpy.dot is dot1; mine is dot2):
>>> %timeit dot1(values, weights)
1 loops, best of 3: 194 ms per loop
>>> %timeit dot2(values, weights)
1 loops, best of 3: 459 ms per loop

As you can see, the built-in numpy solution is faster. But stride_tricks is worth knowing about regardless, so I'm leaving this.

A: Would this work for you?
a = np.array([sum(row * weights) for row in values])

This uses sum() to immediately sum the row * weights values, so you don't need the memory to store all the intermediate values.  Then the list comprehension collects all the values.
You said you want to avoid anything that "loops in Python".  This at least does the looping with the C guts of Python, rather than an explicit Python loop, but it can't be as fast as a NumPy solution because that uses compiled C or Fortran.

A: I don't think you need numpy for something like that. And 1000000 by 3000 is a huge array; this will not fit in your RAM, most likely.
I would do it this way:
Let's say that you data is originally in a text file:
False,True,False
True,False,True
False,True,False
True,False,True

My code:
weight = range(1,4)
dicto = {'True':1, 'False':0}

with open ('my_data.txt') as fin:

    a = sum(sum(dicto[ele]*w for ele,w in zip(line.strip().split(','),weight)) for line in fin)

Result:
>>> a
12

EDIT:
I think I slightly misread the question first time around, and summed up the everything together. Here is the solution that gives the exact solution that OP is after:
weight = range(1,4)
dicto = {'True':1, 'False':0}

with open ('my_data.txt') as fin:

    a = [sum(dicto[ele]*w for ele,w in zip(line.strip().split(','),weight)) for line in fin]

Result:
>>> a
[2, 4, 2, 4]


text:
Q: what's the fastest way to copy a folder over the network to multiple servers(Python) As the title says, what I would like to accomplish is given a package(usually the size may vary between 500Mb and 1Gb), I would like to copy over something around 40 servers at the same time(concurrently), I've been using a script that run a copy at the time, therefore I'm considering these possibilities:
1- Multiprocess library and create a single process for each copy function so that, they can       run concurrently;
-although I think I might end up having an I/O bottleneck, and process cannot share the            same data.
2-I m not using a single internet connection, but a huge corporate WAN.
Can anyone tell me whether is there any other more effective way(faster) to achieve the same thing? Or some other way to solve it?(I can run this task from a 2 core workstation).

A: 1) I have no experience with this, but it looks like a fit for your use case:

*

*http://code.google.com/p/pysendfile/

sendfile(2) is a system call which provides a "zero-copy" way of copying data from one file descriptor to another (a socket). The phrase "zero-copy" refers to the fact that all of the copying of data between the two descriptors is done entirely by the kernel, with no copying of data into userspace buffers. This is particularly useful when sending a file over a socket (e.g. FTP).

and

When do you want to use it?
  Basically any application sending files over the network can take advantage of sendfile(2).

2) Another option would be to use some torrent library. I recently learned (skip to 31:00 for the torrent stuff) that facebook distribute their daily software updates via torrent (and update 1000s of servers with 1.5GB binaries within 15min or so).

A: Assume your machines have 1Gbit connections.  You'll get 800Mbit/s if you're lucky/work at it, and it'll take ~10s to copy each 1GByte and 6-7 minutes to update those machines.  If that's good enough, the only thing you need to do is work on using the 1Gbit efficiently to hit that target (what are you seeing from your current scripts ? OK 1Gbit may be ambitous on WAN, but you can do a similar analysis).  Multiprocessing might or might not help here... but it's not going to magically get you more bandwidth.
If it's not good enough, I'd either consider:

*

*go P2P (see miku;s answer), so as soon as one machine has a bit of
the data it can share it with other machines using it's own
bandwidth.  How much this helps depends to some extent on your
network topology (existence of other bottleneck points).

*Look into multicast, if the network is enough under your control that you can get the stuff routed appropriately (this seems pretty
unlikely for WAN, but maybe one day in an IPv6 wonderland...).
Instead of copying the same data 40 times (assuming it is the same
each time), you just broadcast it once and all the receivers pick it
up simultaneously.  Multicast UDP isn't reliable (intended more for
IPTV I think) but there have been attempts to build reliable file
transfer tools using multicast tech e.g OpenPGM and MS's
own implementation.


text:
Q: Installing Python Package .whl from a specific directory I am trying to install the Python package numpy from the a .whl file. This answer provides the syntax for using pip/wheel to install a package:
pip install --use-wheel --no-index --find-links=/where/its/downloaded package_name

So after downloading the .whl file and renaming it numpy.whl I followed this syntax accordingly:
cd C:\Python27\Scripts
pip install --use-wheel --no-index --find-links=C:\Users\User Name\Downloads numpy

When I do this I get
Ignoring indexes: https://pypi.python.org/simple
Exception:
Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\pip\basecommand.py", line 232, in main
    status = self.run(options, args)
  File "C:\Python27\lib\site-packages\pip\commands\install.py", line 305, in run

    name, None, isolated=options.isolated_mode,
  File "C:\Python27\lib\site-packages\pip\req\req_install.py", line 181, in from
_line
    isolated=isolated)
  File "C:\Python27\lib\site-packages\pip\req\req_install.py", line 54, in __ini
t__
    req = pkg_resources.Requirement.parse(req)
  File "C:\Python27\lib\site-packages\pip\_vendor\pkg_resources\__init__.py", li
ne 2873, in parse
    reqs = list(parse_requirements(s))
  File "C:\Python27\lib\site-packages\pip\_vendor\pkg_resources\__init__.py", li
ne 2820, in parse_requirements
    "version spec")
  File "C:\Python27\lib\site-packages\pip\_vendor\pkg_resources\__init__.py", li
ne 2785, in scan_list
    raise ValueError(msg, line, "at", line[p:])
ValueError: ('Expected version spec in', 'Name\\Downloads', 'at', '\\Downloads
')

I downloaded the numpy‑1.9.2+mkl‑cp27‑none‑win_amd64.whl file and am running Python 2.7 on 64bit architecture so I don't think the version I downloaded is the problem. The other issue I can think of is that the syntax in the original answer is written linux and I cannot find an example that deals with Windows directories. The other issue could be that my User Name is two words with a space in it that Wheel is not set up to handle. I tried adding / in front of the space in case that was the problem, but no dice. How can I install a Python package on Windows using a .whl file?


text:
Q: Regular expression with C# I'm attempting to find a regular expression that will match the following strings:
##Content##
##AnotherArea##

So far I've tried
@"\\#\\#(.*?)\\#\\#"
@"\\#\\#(*?)\\#\\#"

But neither seem to find anything when running:
foreach (var match in Regex.Matches(txtPageContent.Text, expressionMatch))

Where expression match is a string containing the expressions.
Can anyone help me out on this?

A: no need to escape #.
##.*?##

simple explanation
Options: ^ and $ match at line breaks

Match the characters "##" literally «##»
Match any single character that is not a line break character «.*?»
   Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Match the characters "##" literally «##»


text:
Q: The containing arrow function captures the global value of 'this' with typescript I am converting my JavaScript code to Typescript. Before I had a builder but now he is returning this error to me and I can't figure out how to solve it.
Here is my file screen.tsx
Error:
"The containing arrow function captures the global value of 'this'"
const styles = StyleSheet.create({
    //----My styles----
});

const SignIn: React.FC = () => {
    const { signed, signIn, user } = useContext(AuthContext);

    console.log(signed);
    console.log(user);

    function handleSign() {
        signIn();
    }

    return (
        <ScrollView contentContainer={{ flex: 1 }} showsVerticalScrollIndicator={false}>
            <View style={styles.container}>
                <StatusBar barStyle="light-content" />
                <View style={styles.header}>
                    <Text style={styles.text_header}>Sign in</Text>
                    <Text style={styles.text_header_bottom}>Enter</Text>
                </View>

                <Animatable.View
                    animation="fadeInUpBig"
                    style={styles.footer}>
                    <Text style={styles.text_footer}>User</Text>
                        <View style={styles.action}>
                            <FontAwesome
                                name="user-o"
                                color="#000"
                                size={20} />
                            <TextInput
                                placeholder="username"
                                style={styles.textInput}
                                onChangeText={(text) => this.textInputChange(text)}
                            />
                            {this.state.check_textInputChange ?
                                <Animatable.View
                                    animation="bounceIn">
                                    <Feather
                                        name="check-circle"
                                        color="green"
                                        size={20}
                                    />
                                </Animatable.View>
                                : null}
                        </View>

                </Animatable.View>
            </View>
        </ScrollView>
    );
};

export default SignIn;

A: TLDR

In Functional Component, There is no this. At Functional Component this is global this

Answer
In Class Component there is this, But Functional Component hasn't this.
You can search different between both.
I mean this <- is class componeny syntax and if you use it in Functional Component this mean global this(like global in node, window in browser).
In javascript there is no type error checker, So you can't see this error. But in typescript there is type checker. So type checker occur this in Functional Component is unsuitable
And if you want to use state in functional component, just use useState
Example
const SignIn: React.FC = () => {
    const { signed, signIn, user } = useContext(AuthContext);
    const [state, setState] = useState(SomeState)              //  <- here!

    function handleSign() {
        signIn();
    }

    return (
        <ScrollView contentContainer={{ flex: 1 }} showsVerticalScrollIndicator={false}>
            <View style={styles.container}>
                <StatusBar barStyle="light-content" />
                <View style={styles.header}>
                    <Text style={styles.text_header}>Sign in</Text>
                    <Text style={styles.text_header_bottom}>Enter</Text>
                </View>

                <Animatable.View
                    animation="fadeInUpBig"
                    style={styles.footer}>
                    <Text style={styles.text_footer}>User</Text>
                        <View style={styles.action}>
                            <FontAwesome
                                name="user-o"
                                color="#000"
                                size={20} />
                            <TextInput
                                placeholder="username"
                                style={styles.textInput}
                                onChangeText={(text) => this.textInputChange(text)}
                            />
                            {state.check_textInputChange ?         // <- here
                                <Animatable.View
                                    animation="bounceIn">
                                    <Feather
                                        name="check-circle"
                                        color="green"
                                        size={20}
                                    />
                                </Animatable.View>
                                : null}
                        </View>

                </Animatable.View>
            </View>
        </ScrollView>
    );
};

export default SignIn;

Reference

*

*About this in javascript - MDN

*About Functional and Class Component - React Document


text:
Q: Unhandled Rejection .every(...) is not a function I am getting the following error in react 'Unhandled Rejection (TypeError): slots.every(...) is not a function' and I can't seem to solve it.
componentWillMount() {
  axios.get(API_BASE + `api/retrieveSlots`).then(response => {
    console.log("response via db: ", response.data);
    this.handleDBReponse(response.data);
  });
}

for (let day in schedule) {
  let slots = schedule[day];
  if (slots.length) slots.every(slot => slot === true)(schedule[day] = true)
}


text:
Q: Why does ajax accordian change the ID of dynamic controls? I create an accordian with a panel that looks like this.
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
        </asp:ToolkitScriptManager>
        <asp:Accordion ID="Accordion1" runat="server" HeaderCssClass="spitter_"
            HeaderSelectedCssClass="accordionHeaderSelected"
            ContentCssClass="accordionContent" runat="server"
            SelectedIndex="0" FadeTransitions="false"
             TransitionDuration="250"
            FramesPerSecond="30"
            RequireOpenedPane="false" AutoSize="None">
            <Panes>
                <asp:AccordionPane ID="AccPane1" runat="server">
                    <Header>
                        My header
                    </Header>
                    <Content>
                        <asp:Panel ID="panel1" runat="server"></asp:Panel>
                    </Content>
                </asp:AccordionPane>

which works perfectly. Although, the controls i make inside the accordian obtain an ID different to what i specify.Please note that the controls get made perfectly.
I give it the ID of
check_box.ID = "check_box" + i.ToString();

where i is a value in a loop.
Instead of having an ID of "check_box1" or "check_box2" i get an ID of "AccordianPane_check_box1"
Heres where i initiate the checkboxes..
     for (int i = 0; i < depts.Count; i++)
        {
            TableRow row = new TableRow();
            TableCell dept_ = new TableCell();
            TableCell check_row = new TableCell();
            row.ID = "row_" + i.ToString();
            CheckBox mark_row = new CheckBox();
            mark_row.ID = "check_box" + i.ToString();
            check_row.Controls.Add(mark_row);

            row.Cells.Add(check_row);
            row.Cells.Add(dept_);
            table.Rows.Add(row);
        }
panel1.Controls.Add(table);

Any help with this would be great.