问:
SQL Server Pivoting like HBase
I have a big historized key-value store in the following form:

```<code>╔════════════╦═══════════════╦════════╦════════════╗
║ Product_ID ║ Key           ║ Value  ║    Date    ║
╠════════════╬═══════════════╬════════╬════════════╣
║          1 ║ Brand         ║ Foo    ║ 01.11.2017 ║
║          1 ║ Product Group ║ Health ║ 02.11.2017 ║
║          1 ║ Brand         ║ Bar    ║ 07.11.2017 ║
╚════════════╩═══════════════╩════════╩════════════╝
</code>```

Now I need to transpose that table into a pivot like structure with Product_ID and Date as rows and the keys as columns. But... preserving any old data if they are not updated.

This is perfectly done in HBase where someone can store billions of rows and millions of columns. It just shows the last valid data for a specific date in the past, although they are not updated at that time.

So the result should look something like the following.

```<code>╔════════════╦════════════╦═══════╦═══════════════╗
║ Product_ID ║    Date    ║ Brand ║ Product Group ║
╠════════════╬════════════╬═══════╬═══════════════╣
║          1 ║ 01.11.2017 ║ Foo   ║ NULL          ║
║          1 ║ 02.11.2017 ║ Foo   ║ Health        ║
║          1 ║ 07.11.2017 ║ Bar   ║ Health        ║
╚════════════╩════════════╩═══════╩═══════════════╝
</code>```

As you can see, for the 02.11.2017 the Brand and for the 07.11.2017 Health is taken from the previous row. Persisting data over time.

Did somebody came across such a request or is heavily working with key-value stores and have a pointer how it might work?

答:
Here is one approach by using case expression if you don't want to go pivot

```<code>;with cte as
(SELECT Product_ID,
       [Date],
      CASE ([Key]) when 'Brand' then Value END      [Brand],
      CASE ([Key]) when 'Product Group' then Value END      [Product Group],
      row_number() over (order by (select 1)) rn FROM <table_name>),
      cte1 as
      (
       SELECT Product_ID, [Date],
        CASE ([Key]) when 'Brand' then Value END      [Brand],
        CASE ([Key]) when 'Product Group' then Value END      [Product Group],
      row_number() over (order by (select 1)) rn
       FROM <table_name>
      )
SELECT
       T.Product_ID,
       T.[Date]
  ,CASE WHEN
    T.Brand IS NULL THEN
        (SELECT TOP 1 Brand FROM cte1 WHERE rn<T.rn AND Brand IS NOT NULL ORDER BY rn DESC)
    ELSE T.Brand
END AS Brand
,CASE WHEN
    T.[Product Grou] IS NULL THEN
        (SELECT TOP 1 [Product Group] FROM cte1 WHERE rn<T.rn AND [Product Group] IS NOT NULL ORDER BY rn DESC)
    ELSE T.[Product Grou]
END AS [Product Group]
FROM cte T
</code>```

Result :

```<code>Product_ID  Date        Brand   Product Group
1           01.11.2017  Foo     NULL
1           02.11.2017  Foo     Health
1           07.11.2017  Bar     Health
</code>```

Title: SQL Server Pivoting like HBase

Body:
I have a big historized key-value store in the following form:

╔════════════╦═══════════════╦════════╦════════════╗
║ Product_ID ║ Key           ║ Value  ║    Date    ║
╠════════════╬═══════════════╬════════╬════════════╣
║          1 ║ Brand         ║ Foo    ║ 01.11.2017 ║
║          1 ║ Product Group ║ Health ║ 02.11.2017 ║
║          1 ║ Brand         ║ Bar    ║ 07.11.2017 ║
╚════════════╩═══════════════╩════════╩════════════╝

Now I need to transpose that table into a pivot like structure with Product_ID and Date as rows and the keys as columns. But... preserving any old data if they are not updated.

This is perfectly done in HBase where someone can store billions of rows and millions of columns. It just shows the last valid data for a specific date in the past, although they are not updated at that time.

So the result should look something like the following.

╔════════════╦════════════╦═══════╦═══════════════╗
║ Product_ID ║    Date    ║ Brand ║ Product Group ║
╠════════════╬════════════╬═══════╬═══════════════╣
║          1 ║ 01.11.2017 ║ Foo   ║ NULL          ║
║          1 ║ 02.11.2017 ║ Foo   ║ Health        ║
║          1 ║ 07.11.2017 ║ Bar   ║ Health        ║
╚════════════╩════════════╩═══════╩═══════════════╝

As you can see, for the 02.11.2017 the Brand and for the 07.11.2017 Health is taken from the previous row. Persisting data over time.

Did somebody came across such a request or is heavily working with key-value stores and have a pointer how it might work?

Body:
Here is one approach by using case expression if you don't want to go pivot

;with cte as
(SELECT Product_ID,
       [Date],
      CASE ([Key]) when 'Brand' then Value END      [Brand],
      CASE ([Key]) when 'Product Group' then Value END      [Product Group],
      row_number() over (order by (select 1)) rn FROM <table_name>),
      cte1 as
      (
       SELECT Product_ID, [Date],
        CASE ([Key]) when 'Brand' then Value END      [Brand],
        CASE ([Key]) when 'Product Group' then Value END      [Product Group],
      row_number() over (order by (select 1)) rn
       FROM <table_name>
      )
SELECT
       T.Product_ID,
       T.[Date]
  ,CASE WHEN
    T.Brand IS NULL THEN
        (SELECT TOP 1 Brand FROM cte1 WHERE rn<T.rn AND Brand IS NOT NULL ORDER BY rn DESC)
    ELSE T.Brand
END AS Brand
,CASE WHEN
    T.[Product Grou] IS NULL THEN
        (SELECT TOP 1 [Product Group] FROM cte1 WHERE rn<T.rn AND [Product Group] IS NOT NULL ORDER BY rn DESC)
    ELSE T.[Product Grou]
END AS [Product Group]
FROM cte T

Result :

Product_ID  Date        Brand   Product Group
1           01.11.2017  Foo     NULL
1           02.11.2017  Foo     Health
1           07.11.2017  Bar     Health


来源: stackexchange

问:
Why GCC does not report uninitialized variable?
```<code>#include <ios>
#include <iostream>
#include <map>

using namespace std;

int main() {
  ios_base::sync_with_stdio(false);
  map<int, int> v;
  int i;
  int t;
  while (cin >> i) {
    v[i] = t++;
  }
  auto mi = i;
  auto mt = t;
  for (const auto p : v) {
    if (p.second < mt) {
      mi = p.first;
      mt = p.second;
    }
  }
  cout << mi << '\n';
  return 0;
}
</code>```

The abovementioned program makes heavy use of an uninitialized variable t, but GCC does not report it with -Wall or -Wuninitialized. Why is it so?

It is worth noting that Clang catches it:

```<code>main.cpp:13:12: warning: variable 't' is uninitialized when used here [-Wuninitialized]
    v[i] = t++;
           ^
</code>```

Used g++ (GCC) 7.2.1 20170915 (Red Hat 7.2.1-2).

Used clang version 4.0.1 (tags/RELEASE_401/final).

As you can see in https://godbolt.org/g/kmYMC1 GCC 7.2 does not report it even when it should. I will create a ticket in GCC's issue tracker.

答:
g++'s warning flag is not called -Wuninitialized: it is called -Wmaybe-uninitialized.

Also, as Jonathan Wakely noted in his answer, g++ is able to detect usage of uninitialized variables only when optimizations are enabled.

Enabling both -Wmaybe-initalized and optimizations produces the expected warning: https://godbolt.org/g/3CZ6kT

Note that -Wmaybe-initalized is enabled by default with both -Wall and -Wextra.

ContentLicense: CC BY-SA 3.0

Body:
#include <ios>
#include <iostream>
#include <map>

using namespace std;

int main() {
  ios_base::sync_with_stdio(false);
  map<int, int> v;
  int i;
  int t;
  while (cin >> i) {
    v[i] = t++;
  }
  auto mi = i;
  auto mt = t;
  for (const auto p : v) {
    if (p.second < mt) {
      mi = p.first;
      mt = p.second;
    }
  }
  cout << mi << '\n';
  return 0;
}

The abovementioned program makes heavy use of an uninitialized variable t, but GCC does not report it with -Wall or -Wuninitialized. Why is it so?

It is worth noting that Clang catches it:

main.cpp:13:12: warning: variable 't' is uninitialized when used here [-Wuninitialized]
    v[i] = t++;
           ^

Used g++ (GCC) 7.2.1 20170915 (Red Hat 7.2.1-2).

Used clang version 4.0.1 (tags/RELEASE_401/final).

As you can see in https://godbolt.org/g/kmYMC1 GCC 7.2 does not report it even when it should. I will create a ticket in GCC's issue tracker.


问:
REST and spring-mvc
Since REST based controller methods only return objects ( not views ) to the client based on the request, how can I show view to my user ? Or maybe better question what is a good way to combine spring-mvc web app with REST, so my user always get the answer, not in just ( for example ) JSON format, but also with the view ?

So far as I understood, REST based controller would be perfectly fitting to the mobile app ( for example twitter ), where views are handled inside the app and the only thing server has to worry about is to pass the right object to the right request. But what about the web app ?

I might be wrong in several things ( correct me if I am ), since I am trying to understand REST and I am still learning.

答:
If you annotate a method with @ResponseBody, Spring will use a json mapper to generate the response. Instead of annotating every method with @ResponseBody you can annotate your class with @RestController.

If you want to return a view, you need to annotate the class with @Controller instead of @RestController and configure a viewresolver. Bij default spring will use thymeleaf as a viewresolver if you have spring-web as a dependency on the classpath. The return type of the method is a String that references the template to be rendered. The templates are stored in src/main/resources/templates.

You can find a guide on the spring website: https://spring.io/guides/gs/serving-web-content/

Title: REST and spring-mvc


问:
Add an array to a SQL database (java)
I want to add a list of values of a variable size in a row of a single SQL database. As i understood from the following topic, it's not possible with a List<> object:

How to add a list to a SQL database (using java)

But it works with a String, which is basically an object containing an array of char:

```<code>ContentValues values = new ContentValues();
values.put(MyDB.COLUMN_NAME, contact.getName());
mDb.insert(MyDB.TABLE_CONTACTS, null, values);
</code>```

So is it possible to add an array of an other type (like double[] myList , possibly contained in an object) in the database, the same way as we added TEXT?

I am using java on Android Studio.

答: One option would be to convert your array/list to a JSON string and insert in the database. While reading the data, you can then parse it and create an array or a list.</p>

Title: Add an array to a SQL database (java)

Body:
I want to add a list of values of a variable size in a row of a single SQL database. As i understood from the following topic, it's not possible with a List<> object:

How to add a list to a SQL database (using java)

But it works with a String, which is basically an object containing an array of char:

ContentValues values = new ContentValues();
values.put(MyDB.COLUMN_NAME, contact.getName());
mDb.insert(MyDB.TABLE_CONTACTS, null, values);

So is it possible to add an array of an other type (like double[] myList , possibly contained in an object) in the database, the same way as we added TEXT?

I am using java on Android Studio.


问:
Count the number of Occurrences of a Word in a String
I am new to Java Strings the problem is that I want to count the Occurrences of a specific word in a String. Suppose that my String is:

```<code>i have a male cat. the color of male cat is Black
</code>```

Now I dont want to split it as well so I want to search for a word that is "male cat". it occurs two times in my string!

What I am trying is:

```<code>int c = 0;
for (int j = 0; j < text.length(); j++) {
    if (text.contains("male cat")) {
        c += 1;
    }
}

System.out.println("counter=" + c);
</code>```

it gives me 46 counter value! So whats the solution?

答:
I've got another approach here:</p>

```<code>String description = "hello india hello india hello hello india hello";
String textToBeCounted = "hello";

// Split description using "hello", which will return
//string array of words other than hello
String[] words = description.split("hello");

// Get number of characters words other than "hello"
int lengthOfNonMatchingWords = 0;
for (String word : words) {
    lengthOfNonMatchingWords += word.length();
}

// Following code gets length of `description` - length of all non-matching
// words and divide it by length of word to be counted
System.out.println("Number of matching words are " +
(description.length() - lengthOfNonMatchingWords) / textToBeCounted.length());
</code>```

Body:
I am new to Java Strings the problem is that I want to count the Occurrences of a specific word in a String. Suppose that my String is:

i have a male cat. the color of male cat is Black

Now I dont want to split it as well so I want to search for a word that is "male cat". it occurs two times in my string!

What I am trying is:

int c = 0;
for (int j = 0; j < text.length(); j++) {
    if (text.contains("male cat")) {
        c += 1;
    }
}

System.out.println("counter=" + c);

it gives me 46 counter value! So whats the solution?

Body:
I've got another approach here:

String description = "hello india hello india hello hello india hello";
String textToBeCounted = "hello";

// Split description using "hello", which will return
//string array of words other than hello
String[] words = description.split("hello");

// Get number of characters words other than "hello"
int lengthOfNonMatchingWords = 0;
for (String word : words) {
    lengthOfNonMatchingWords += word.length();
}

// Following code gets length of `description` - length of all non-matching
// words and divide it by length of word to be counted
System.out.println("Number of matching words are " +
(description.length() - lengthOfNonMatchingWords) / textToBeCounted.length());


问:
Loop through array, print with string
I have a simple array like:

```<code>var myArr=["one","two","three"];
</code>```

an I have a counting loop, which increases the value of var i by one.

What I want to do is print the next value from the array each time the loop runs, next to a text string, like so:

```<code>alert('value number '+myArr[i]+);
</code>```

But for some reason I can't get this to work.
The following code works, so I'm assuming I'm not calling the counter right:

```<code>alert('value number '+myArr[0]+);
</code>```

答:
Your second option alert('value number '+myArr[0]+); because you define array index like 0 in this case working , but myArr[i] not working because i is not define so if assign i = 0 then first value work, but main solution is that use loop and increment counter and get total array use myArr.length , other wise which time loop run you do not know.

```<code>for (var i = 0; i < myArr.length; ++i) {
  alert('Array value at index [' + i + '] :  [' + myArr[i] + ']');
}
</code>```

for more information

https://www.w3schools.com/js/js_loop_for.asp

ContentLicense: CC BY-SA 2.5

Title: Loop through array, print with string

Body:
I have a simple array like:

var myArr=["one","two","three"];

an I have a counting loop, which increases the value of var i by one.

What I want to do is print the next value from the array each time the loop runs, next to a text string, like so:

alert('value number '+myArr[i]+);

But for some reason I can't get this to work.
The following code works, so I'm assuming I'm not calling the counter right:

alert('value number '+myArr[0]+);

Body:
Your second option alert('value number '+myArr[0]+); because you define array index like 0 in this case working , but myArr[i] not working because i is not define so if assign i = 0 then first value work, but main solution is that use loop and increment counter and get total array use myArr.length , other wise which time loop run you do not know.

for (var i = 0; i < myArr.length; ++i) {
  alert('Array value at index [' + i + '] :  [' + myArr[i] + ']');
}

for more information

https://www.w3schools.com/js/js_loop_for.asp


问:
Flash - XML random text display
I am stumped on this... All I want is to display a random node from an xml file in Flash...
I can display one node fine, but if try to display 2 or more, Flash sticks the XML tags back on the items - change the number following questions in the urlLoader_complete function to see what I mean.
Here's my AS3:

```<code>var questions:XML;

var urlRequest:URLRequest = new URLRequest("breakfast.xml");
var urlLoader:URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
urlLoader.addEventListener(Event.COMPLETE, urlLoader_complete);
urlLoader.load(urlRequest);

function urlLoader_complete(evt:Event):void {
    questions = new XML(evt.target.data);
    textArea.text = generateRandomQuestions(questions, 2).toString();
}

function generateRandomQuestions(source:XML, nodes:int = 6):XMLList
{
    if (source.*.length() < nodes) return source.*;
    var list:XMLList;
    var hash:Array = [];
    var randomPosition:int;
    var node:XML;
    do
    {
        node = source.*[(Math.random() * source.*.length()) >> 0];
        if (hash.indexOf(node.toXMLString()) < 0)
        {
            hash.push(node.toXMLString());
            list ? list += node : list = XMLList(node);
        }
    } while (list.length() < nodes)
    return list;
}
</code>```

and my XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<breakfast>
    <person>K</person>
    <person>Dave</person>
    <person>Andrew</person>
    <person>Bart</person>
    <person>Ricky</person>
</breakfast>
</code>```

答:
Try this out.

```<code>import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLRequest;

var urlRequest:URLRequest = new URLRequest("test.xml");
var urlLoader:URLLoader = new URLLoader();
urlLoader.load(urlRequest);
urlLoader.addEventListener(Event.COMPLETE, loadComplete, false, 0, true);

function loadComplete(evt:Event):void
{
    var xml:XML = new XML(evt.target.data);
    trace(generateRandomNodes(xml, 3).toString());
}

function generateRandomNodes(xml:XML, limit:int):Array
{
    var nodes:Array = new Array();
    for each(var node in xml.children())
    {
        nodes.push(node);
    }
    if(limit <= nodes.length)
    {
        nodes = shuffleArray(nodes);
        return nodes.slice(0, limit);
    }else
    {
        return [];
    }
}

function shuffleArray(array:Array):Array
{
    var temp:Array = new Array();
    for(var i:int=0;i<array.length;i++)
    {
        var rand = Math.floor(Math.random() * (i + 1));
        var tmp = array[i];
        temp[i] = temp[rand];
        temp[rand] = tmp;
    }
    return temp;
}
</code>```

This will give you an array with randomly shuffled XML node values.

Title: Flash - XML random text display

Body:
I am stumped on this... All I want is to display a random node from an xml file in Flash...
I can display one node fine, but if try to display 2 or more, Flash sticks the XML tags back on the items - change the number following questions in the urlLoader_complete function to see what I mean.
Here's my AS3:

var questions:XML;

var urlRequest:URLRequest = new URLRequest("breakfast.xml");
var urlLoader:URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
urlLoader.addEventListener(Event.COMPLETE, urlLoader_complete);
urlLoader.load(urlRequest);

function urlLoader_complete(evt:Event):void {
    questions = new XML(evt.target.data);
    textArea.text = generateRandomQuestions(questions, 2).toString();
}

function generateRandomQuestions(source:XML, nodes:int = 6):XMLList
{
    if (source.*.length() < nodes) return source.*;
    var list:XMLList;
    var hash:Array = [];
    var randomPosition:int;
    var node:XML;
    do
    {
        node = source.*[(Math.random() * source.*.length()) >> 0];
        if (hash.indexOf(node.toXMLString()) < 0)
        {
            hash.push(node.toXMLString());
            list ? list += node : list = XMLList(node);
        }
    } while (list.length() < nodes)
    return list;
}

and my XML:

<?xml version="1.0" encoding="utf-8"?>
<breakfast>
    <person>K</person>
    <person>Dave</person>
    <person>Andrew</person>
    <person>Bart</person>
    <person>Ricky</person>
</breakfast>

Body:
Try this out.

import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLRequest;

var urlRequest:URLRequest = new URLRequest("test.xml");
var urlLoader:URLLoader = new URLLoader();
urlLoader.load(urlRequest);
urlLoader.addEventListener(Event.COMPLETE, loadComplete, false, 0, true);

function loadComplete(evt:Event):void
{
    var xml:XML = new XML(evt.target.data);
    trace(generateRandomNodes(xml, 3).toString());
}

function generateRandomNodes(xml:XML, limit:int):Array
{
    var nodes:Array = new Array();
    for each(var node in xml.children())
    {
        nodes.push(node);
    }
    if(limit <= nodes.length)
    {
        nodes = shuffleArray(nodes);
        return nodes.slice(0, limit);
    }else
    {
        return [];
    }
}

function shuffleArray(array:Array):Array
{
    var temp:Array = new Array();
    for(var i:int=0;i<array.length;i++)
    {
        var rand = Math.floor(Math.random() * (i + 1));
        var tmp = array[i];
        temp[i] = temp[rand];
        temp[rand] = tmp;
    }
    return temp;
}

This will give you an array with randomly shuffled XML node values.


问:
Clone rep:policy on AEM
I am currently working on with a solution that would be able to clone/copy/backup my existing rep:policy. 'Cause when we do some jobs it accidentally removed. I am trying to apply this kind of fix, but am failing to. It says it is an invalid path.

javax.jcr.security.AccessControlException: OakAccessControl0006: Isolated policy node. Parent is not of type [rep:AccessControllable]

```<code>        final Workspace ws = session.getWorkspace();
           ws.copy("/etc/commerce/products/abccompany/TvPackChannelMap/rep:policy","/tmp/nxt/TvPackChannelMap/rep:policy");
</code>```

Are there other ways that I can be able to take the rep:policy thru code?

答:
The Other approach is to retrieve the ACL permissions through the query language.
For example, SELECT * FROM [rep:ACL]  or SELECT * FROM [rep:ACE] where [rep:principalName] is not null should give you the results.

For more information, I would recommend you to check the ACS commons ACL Packager Implementation which is available on GitHub.
Reference Link - https://github.com/Adobe-Consulting-Services/acs-aem-commons/blob/master/bundle/src/main/java/com/adobe/acs/commons/packaging/impl/ACLPackagerServletImpl.java

Title: Clone rep:policy on AEM

Body:
I am currently working on with a solution that would be able to clone/copy/backup my existing rep:policy. 'Cause when we do some jobs it accidentally removed. I am trying to apply this kind of fix, but am failing to. It says it is an invalid path.

javax.jcr.security.AccessControlException: OakAccessControl0006: Isolated policy node. Parent is not of type [rep:AccessControllable]

        final Workspace ws = session.getWorkspace();
           ws.copy("/etc/commerce/products/abccompany/TvPackChannelMap/rep:policy","/tmp/nxt/TvPackChannelMap/rep:policy");

Are there other ways that I can be able to take the rep:policy thru code?


问:
Convert JSON Source to c# ASP .NET Output
I'm trying to load data from https://www.quandl.com/api/v3/datatables/WIKI.

Comes out in a form like below

```<code>{"datatable":{"data":[["A","2017-11-14",66.98,67.8,66.89,67.46,1682158.0,0.0,1.0,66.98,67.8,66.89,67.46,1682158.0]],"columns":[{"name":"ticker","type":"String"},{"name":"date","type":"Date"},{"name":"open","type":"BigDecimal(34,12)"},{"name":"high","type":"BigDecimal(34,12)"},{"name":"low","type":"BigDecimal(34,12)"},{"name":"close","type":"BigDecimal(34,12)"},{"name":"volume","type":"BigDecimal(37,15)"},{"name":"ex-dividend","type":"BigDecimal(42,20)"},{"name":"split_ratio","type":"double"},{"name":"adj_open","type":"BigDecimal(50,28)"},{"name":"adj_high","type":"BigDecimal(50,28)"},{"name":"adj_low","type":"BigDecimal(50,28)"},{"name":"adj_close","type":"BigDecimal(50,28)"},{"name":"adj_volume","type":"double"}]},"meta":{"next_cursor_id":null}}.
</code>```

However I try to load in asp .net like below but get an error saying it can't find data.

```<code>public partial class _Default : System.Web.UI.Page
{
    protected string url = "https://www.quandl.com/api/v3/datatables/WIKI/PRICES?date=2017-11-14&ticker=A&api_key=<YOURAPIKEY>";

    protected void Page_Load(object sender, EventArgs e)
    {
        //create an instance of HttpClient
        HttpClient client = new HttpClient();

        //DefaultRequestHeader to Json
        client.DefaultRequestHeaders.Accept.Add(new  MediaTypeWithQualityHeaderValue("application/json"));

        //Create an instance of HttpResponse & invoke the service asynchronously
        HttpResponseMessage response = client.GetAsync(url).Result;

        //Http Status code 200
        if (response.IsSuccessStatusCode)
        {
            //Read response content result into string variable
            string JSON = response.Content.ReadAsStringAsync().Result;

           //Deserialize the string(JSON) object
           var jObj = (JObject)JsonConvert.DeserializeObject(JSON);

           //access items from anonymous (Json object) type and add to the list
            var result = jObj["datatable"].Select(item => new
            {
                key = item["data"][0],
                code = item["data"][1],
                description = item["data"][2],
                buy = item["data"][3],
                sell = item["data"][4],
            }).ToList();

            //output the data || NOTE: **NSERT into database table**
            foreach (var item in result)
            {
                lblOutput.Text = item.key + "--" + item.code + "--" + item.description + item.buy + item.sell + "<br/>";
            }
        }

    }
}
</code>```

I can't seem to figure out how to load the data in the beginning bit of the json file
{"datatable":{"data":[["A","2017-11-14",66.98,67.8,66.89,67.46,1682158.0,0.0,1.0,66.98,67.8,66.89,67.46,1682158.0]],

答:
You need to go over the data items not datatable items</p>

```<code> var result = jObj["datatable"]["data"].Select(item => new
                {
                    key = item[0],
                    code = item[1],
                    description = item[2],
                    buy = item[3],
                    sell = item[4],
                }).ToList();
</code>```

Body:
I'm trying to load data from https://www.quandl.com/api/v3/datatables/WIKI.

Comes out in a form like below

{"datatable":{"data":[["A","2017-11-14",66.98,67.8,66.89,67.46,1682158.0,0.0,1.0,66.98,67.8,66.89,67.46,1682158.0]],"columns":[{"name":"ticker","type":"String"},{"name":"date","type":"Date"},{"name":"open","type":"BigDecimal(34,12)"},{"name":"high","type":"BigDecimal(34,12)"},{"name":"low","type":"BigDecimal(34,12)"},{"name":"close","type":"BigDecimal(34,12)"},{"name":"volume","type":"BigDecimal(37,15)"},{"name":"ex-dividend","type":"BigDecimal(42,20)"},{"name":"split_ratio","type":"double"},{"name":"adj_open","type":"BigDecimal(50,28)"},{"name":"adj_high","type":"BigDecimal(50,28)"},{"name":"adj_low","type":"BigDecimal(50,28)"},{"name":"adj_close","type":"BigDecimal(50,28)"},{"name":"adj_volume","type":"double"}]},"meta":{"next_cursor_id":null}}.

However I try to load in asp .net like below but get an error saying it can't find data.

public partial class _Default : System.Web.UI.Page
{
    protected string url = "https://www.quandl.com/api/v3/datatables/WIKI/PRICES?date=2017-11-14&ticker=A&api_key=<YOURAPIKEY>";

    protected void Page_Load(object sender, EventArgs e)
    {
        //create an instance of HttpClient
        HttpClient client = new HttpClient();

        //DefaultRequestHeader to Json
        client.DefaultRequestHeaders.Accept.Add(new  MediaTypeWithQualityHeaderValue("application/json"));

        //Create an instance of HttpResponse & invoke the service asynchronously
        HttpResponseMessage response = client.GetAsync(url).Result;

        //Http Status code 200
        if (response.IsSuccessStatusCode)
        {
            //Read response content result into string variable
            string JSON = response.Content.ReadAsStringAsync().Result;

           //Deserialize the string(JSON) object
           var jObj = (JObject)JsonConvert.DeserializeObject(JSON);

           //access items from anonymous (Json object) type and add to the list
            var result = jObj["datatable"].Select(item => new
            {
                key = item["data"][0],
                code = item["data"][1],
                description = item["data"][2],
                buy = item["data"][3],
                sell = item["data"][4],
            }).ToList();

            //output the data || NOTE: **NSERT into database table**
            foreach (var item in result)
            {
                lblOutput.Text = item.key + "--" + item.code + "--" + item.description + item.buy + item.sell + "
";
            }
        }

    }
}

I can't seem to figure out how to load the data in the beginning bit of the json file
{"datatable":{"data":[["A","2017-11-14",66.98,67.8,66.89,67.46,1682158.0,0.0,1.0,66.98,67.8,66.89,67.46,1682158.0]],

Body:
You need to go over the data items not datatable items

 var result = jObj["datatable"]["data"].Select(item => new
                {
                    key = item[0],
                    code = item[1],
                    description = item[2],
                    buy = item[3],
                    sell = item[4],
                }).ToList();


问:
Modal jQuery doesn't work (bootstrap 4)
I have a problem with jQuery. When I click on the link the modal opens and I want to pass the value of data-href to the button inside the modal.

Nothing happens when I click the button. Could you please help me?

Link

```<code><a href="#" data-href="stackoverflow.com" data-toggle="modal" data-target="#openModal">Link</a>
</code>```

Modal

```<code><div class="modal fade" id="openModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                        <button class="btn btn-danger btn-ok" href="">Go</button>
                    </div>
                </div>
            </div>
        </div>
</code>```

JQuery

```<code>    <script>
        $('#openModal').on('show.bs.modal', function(e) {
            $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
            $('.debug-url').html('Delete URL: <strong>' + $(this).find('.btn-ok').attr('href') + '</strong>');
        });
    </script>
</code>```

jQuery/Popper/JS

```<code><script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.2/umd/popper.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>
</code>```

Error

```<code>Uncaught ReferenceError: $ is not defined
</code>```

答:
Try This If you found this error "Uncaught ReferenceError: $ is not defined" than replace "$" to "jQuery".

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Modal Example

  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

          <button type="button" class="close" data-dismiss="modal">×</button>

Modal Header

Some text in the modal.

          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

```

Title: Modal jQuery doesn't work (bootstrap 4)

Body:
I have a problem with jQuery. When I click on the link the modal opens and I want to pass the value of data-href to the button inside the modal.

Nothing happens when I click the button. Could you please help me?

Link

Link

Modal

                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                        <button class="btn btn-danger btn-ok" href="">Go</button>

JQuery

jQuery/Popper/JS

Error

Uncaught ReferenceError: $ is not defined

Body:
Try This If you found this error "Uncaught ReferenceError: $ is not defined" than replace "$" to "jQuery".

<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Modal Example</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div>

</div>

</body>
</html>


问:
python regex- positive lookahead
```<code>str='filename=1817616353&realname=Arguments%20for%20&%20against%20protection%20.pdf&code2=pds'
ptn='(?<=realname=).+(?=&)'
re.search(ptn,str).group()
</code>```

well, when i run this code i'm expecting to get

```<code>'Arguments%20for%20'
</code>```

as the match, but instead it gives me

```<code>'Arguments%20for%20&%20against%20protection%20.pdf'
</code>```

i thought the match should occur at the first occurrence of '&', which is right after 'for%20' part, so i have no idea why it's going all the way down to 'pdf'. what am i doing wrong?

答:
Your assumption that the first occurrence of & would match is fundamentally wrong.

.+ means match as many as possible of any character (except newline). Thus this causes anything after it to be matched at the last possible position.

A common fix for "I want as few as possible" is to use a greedy quantifier .+? which means match as few as possible but it could still end up matching things you don't want.

If you really mean "match the first possible &" then the expression you should repeat before it is "anything except &".

```<code>ptn=r'(?<=realname=)[^&]+(?=&)'
</code>```

(Notice also the use of an r'...' string. It doesn't make any difference here, but it's another common newbie error -- you want backslashes in your regex and don't understand why Python is losing them.)

This is basically a restatement of the other answer on this page but hopefully easier for a beginner to digest.

Title: python regex- positive lookahead

Body:
str='filename=1817616353&realname=Arguments%20for%20&%20against%20protection%20.pdf&code2=pds'
ptn='(?<=realname=).+(?=&)'
re.search(ptn,str).group()

well, when i run this code i'm expecting to get

'Arguments%20for%20'

as the match, but instead it gives me

'Arguments%20for%20&%20against%20protection%20.pdf'

i thought the match should occur at the first occurrence of '&', which is right after 'for%20' part, so i have no idea why it's going all the way down to 'pdf'. what am i doing wrong?

Body:
Your assumption that the first occurrence of & would match is fundamentally wrong.

.+ means match as many as possible of any character (except newline). Thus this causes anything after it to be matched at the last possible position.

A common fix for "I want as few as possible" is to use a greedy quantifier .+? which means match as few as possible but it could still end up matching things you don't want.

If you really mean "match the first possible &" then the expression you should repeat before it is "anything except &".

ptn=r'(?<=realname=)[^&]+(?=&)'

(Notice also the use of an r'...' string. It doesn't make any difference here, but it's another common newbie error -- you want backslashes in your regex and don't understand why Python is losing them.)

This is basically a restatement of the other answer on this page but hopefully easier for a beginner to digest.


问:
can't run .jar file /java.jar: line 1: public: command not found
I have Ubuntu 16.04.

and downloaded a JDK with a tar.gz file extension and followed This wikihow to install it.

When I try to run a .jar game (like Minecraft) It works successfully, and I have netbeans downloaded that is connected to the same JDK and compiled some programs that i can run in terminal, But When I type :

./Hello_world.jar

Which is :

```<code>package main;

public class project {

   public static void main(String[] args) {
      System.out.println("Hello world");
   }
}
</code>```

I get this output :

```<code>./Hello_world.jar: line 1: $'PK\003\004': command not found
./Hello_world.jar: line 2: $'\b.\020oK': command not found
./Hello_world.jar: line 3: syntax error near unexpected token `)'
./Hello_world.jar: line 3:-oK�}����META-INF/MANIFEST.MFM�1
                                                        �0��@��uHh          Q���X� ��N1�Ҧ$)��7�(�p�ww
�A����|��}�1���ή�n��p<�Рŗ��:CpN~�s�ν�˚�3��%
                                                 ��)���goPK`
</code>```

答:
Simple: JAR files aren't executables. You can only invoke binaries/scripts by telling your shell to ./command.

They are archives that contain compiled Java classes.

Thus you use them like:

```<code>java -jar somejar.jar
</code>```

This starts a java virtual machine, and tells it to open the given JAR file. The JVM will then figure the "main" class to run from the meta information that can be backed into the JAR file - to then "run" that main class.

( assuming that the corresponding JAR file has been built in a why that allows running it like this. see here for details on how you enable this "easy way" of running a JAR file )

And just in case: with some scripting magic, you actually can turn a JAR file into a "binary", see here for example.

ContentLicense: CC BY-SA 4.0

Body:
I have Ubuntu 16.04.

and downloaded a JDK with a tar.gz file extension and followed This wikihow to install it.

When I try to run a .jar game (like Minecraft) It works successfully, and I have netbeans downloaded that is connected to the same JDK and compiled some programs that i can run in terminal, But When I type :

./Hello_world.jar

Which is :

package main;

public class project {

   public static void main(String[] args) {
      System.out.println("Hello world");
   }
}

I get this output :

./Hello_world.jar: line 1: $'PK\003\004': command not found
./Hello_world.jar: line 2: $'\b.\020oK': command not found
./Hello_world.jar: line 3: syntax error near unexpected token `)'
./Hello_world.jar: line 3:-oK�}����META-INF/MANIFEST.MFM�1
                                                        �0��@��uHh          Q���X� ��N1�Ҧ$)��7�(�p�ww
�A����|��}�1���ή�n��p<�Рŗ��:CpN~�s�ν�˚�3��%
                                                 ��)���goPK`

Body:
Simple: JAR files aren't executables. You can only invoke binaries/scripts by telling your shell to ./command.

They are archives that contain compiled Java classes.

Thus you use them like:

java -jar somejar.jar

This starts a java virtual machine, and tells it to open the given JAR file. The JVM will then figure the "main" class to run from the meta information that can be backed into the JAR file - to then "run" that main class.

( assuming that the corresponding JAR file has been built in a why that allows running it like this. see here for details on how you enable this "easy way" of running a JAR file )

And just in case: with some scripting magic, you actually can turn a JAR file into a "binary", see here for example.


问:
How to add all of the migrations/ to git .gitignore file in django?
In my Django project, I have many migrations directory, I want to add to my .gitignore file:

Because they are under each app directory, I do not want to add every one.

How can I add all the migrations directories in it?

Now in it only like this:

```<code>.idea/
</code>```

答:
You can add a new line in .gitignore file like so -

```<code>**/migrations/
</code>```

if the migrations folder is multiple level deep add the same in the .gitignore like the following

```<code>**/**/migrations
</code>```

Body:
In my Django project, I have many migrations directory, I want to add to my .gitignore file:

Because they are under each app directory, I do not want to add every one.

How can I add all the migrations directories in it?

Now in it only like this:

.idea/

Body:
You can add a new line in .gitignore file like so -

**/migrations/

if the migrations folder is multiple level deep add the same in the .gitignore like the following

**/**/migrations


问:
Search a codebase for references to table names
I have a directory full of legacy code from a VB6 application.

I have been asked to provide a list of all the tables that this application uses, so we can assign a special SQL Server username to it.

What is the best way to scan a codebase for references to table names?

Some ideas I've had:

Search for the following keywords:
"FROM", "UPDATE", "INSERT", and
manually note the table name(s)
surrounding those phrases.

Problem: Lots of manual work

Run the application with a SQL
Trace, and try to exercise each
function, then scan the logs for
table names

Problem: Same manual work, plus I might overlook some obscure functions

Can anyone suggest better alternatives?

答:
I would select from information_schema.tables and save the results to file to build a table list and then use a bat file or command line regex tool to use the table list as a source for comparisons against the files in the source code directory. You could output what files had a hit, and what table names were hit (what line the hit was on if you're interested). I'm not a grep whiz, but I think that would be the right sort of tool to use.

EDIT
Depending on how the data access was handled, you might want to expand the search list to include stored procs from information_schema.routines

Edit 2 Approach using finstr, a cursor, and maybe the dark side

Please note that while the below should work, if pointed at the wrong directory, it could cause havoc. Also, it will only work if the source code is accessible from the server and xp_cmdshell is enabled. Maybe the whole idea is evil, I don't know.

```<code>create table #files (filepath   varchar(4000))
create table #tablesfound (tablename sysname, filepath varchar(4000))

declare @sql nvarchar(4000)
Declare @cmd nvarchar(400)
Declare @dir varchar(256)
Declare @tbl sysname
set @dir = 'source code directory with e.g. c:\source\'
declare crsX cursor for
Select table_name from information_schema.tables
open crsX
Fetch Next from crsX into @tbl

While (@@Fetch_Status = 0)
Begin
    set @cmd = 'findstr /S /M '  + quotename(@tbl, char(34)) + ' ' + @dir + '*.*'

    insert into #files exec xp_cmdshell  @cmd
    if exists (Select 1 from #files where filepath is not null)
    Begin
        insert into #tablesfound (tablename, filepath)
        Select @tbl, filepath from #files where filepath is not null
        delete from #files
    End
    print @cmd
    Fetch Next from crsX into @tbl
End
close crsX
Deallocate crsX

Select * from #tablesfound
</code>```

OwnerDisplayName: kogus

Body:
I would select from information_schema.tables and save the results to file to build a table list and then use a bat file or command line regex tool to use the table list as a source for comparisons against the files in the source code directory. You could output what files had a hit, and what table names were hit (what line the hit was on if you're interested). I'm not a grep whiz, but I think that would be the right sort of tool to use.

EDIT
Depending on how the data access was handled, you might want to expand the search list to include stored procs from information_schema.routines

Edit 2 Approach using finstr, a cursor, and maybe the dark side

Please note that while the below should work, if pointed at the wrong directory, it could cause havoc. Also, it will only work if the source code is accessible from the server and xp_cmdshell is enabled. Maybe the whole idea is evil, I don't know.

create table #files (filepath   varchar(4000))
create table #tablesfound (tablename sysname, filepath varchar(4000))

declare @sql nvarchar(4000)
Declare @cmd nvarchar(400)
Declare @dir varchar(256)
Declare @tbl sysname
set @dir = 'source code directory with e.g. c:\source\'
declare crsX cursor for
Select table_name from information_schema.tables
open crsX
Fetch Next from crsX into @tbl

While (@@Fetch_Status = 0)
Begin
    set @cmd = 'findstr /S /M '  + quotename(@tbl, char(34)) + ' ' + @dir + '*.*'

    insert into #files exec xp_cmdshell  @cmd
    if exists (Select 1 from #files where filepath is not null)
    Begin
        insert into #tablesfound (tablename, filepath)
        Select @tbl, filepath from #files where filepath is not null
        delete from #files
    End
    print @cmd
    Fetch Next from crsX into @tbl
End
close crsX
Deallocate crsX

Select * from #tablesfound

OwnerDisplayName: cmsjr

LastEditorDisplayName: cmsjr


问:
Command ...swiftc failed with exit code 1
I am stuck with this error for a while, and none of the solutions I've found seems to work (at least, in my case). Here is the full error log:

```<code>CompileSwiftSources normal x86_64 com.apple.xcode.tools.swift.compiler
cd "/Users/user/Documents/Music Kit A"
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc -target x86_64-apple-macosx10.10 -module-name Music_Kit_A -Onone -sdk /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk -g -module-cache-path /Users/user/Library/Developer/Xcode/DerivedData/ModuleCache -I /Users/user/Library/Developer/Xcode/DerivedData/Music_Kit_A-cimwnaollginmxefzprqiioyrhfl/Build/Products/Debug -F /Users/user/Library/Developer/Xcode/DerivedData/Music_Kit_A-cimwnaollginmxefzprqiioyrhfl/Build/Products/Debug -c -j4 /Users/user/Documents/Music\ Kit\ A/Music\ Kit\ A/AppDelegate.swift /Users/user/Documents/Music\ Kit\ A/Music\ Kit\ A/main.swift -output-file-map /Users/user/Library/Developer/Xcode/DerivedData/Music_Kit_A-cimwnaollginmxefzprqiioyrhfl/Build/Intermediates/Music\ Kit\ A.build/Debug/Music\ Kit\ A.build/Objects-normal/x86_64/Music\ Kit\ A-OutputFileMap.json -parseable-output -serialize-diagnostics -emit-dependencies -emit-module -emit-module-path /Users/user/Library/Developer/Xcode/DerivedData/Music_Kit_A-cimwnaollginmxefzprqiioyrhfl/Build/Intermediates/Music\ Kit\ A.build/Debug/Music\ Kit\ A.build/Objects-normal/x86_64/Music_Kit_A.swiftmodule -Xcc -I/Users/user/Library/Developer/Xcode/DerivedData/Music_Kit_A-cimwnaollginmxefzprqiioyrhfl/Build/Intermediates/Music\ Kit\ A.build/Debug/Music\ Kit\ A.build/swift-overrides.hmap -Xcc -iquote -Xcc /Users/user/Library/Developer/Xcode/DerivedData/Music_Kit_A-cimwnaollginmxefzprqiioyrhfl/Build/Intermediates/Music\ Kit\ A.build/Debug/Music\ Kit\ A.build/Music\ Kit\ A-generated-files.hmap -Xcc -I/Users/user/Library/Developer/Xcode/DerivedData/Music_Kit_A-cimwnaollginmxefzprqiioyrhfl/Build/Intermediates/Music\ Kit\ A.build/Debug/Music\ Kit\ A.build/Music\ Kit\ A-own-target-headers.hmap -Xcc -I/Users/user/Library/Developer/Xcode/DerivedData/Music_Kit_A-cimwnaollginmxefzprqiioyrhfl/Build/Intermediates/Music\ Kit\ A.build/Debug/Music\ Kit\ A.build/Music\ Kit\ A-all-target-headers.hmap -Xcc -iquote -Xcc /Users/user/Library/Developer/Xcode/DerivedData/Music_Kit_A-cimwnaollginmxefzprqiioyrhfl/Build/Intermediates/Music\ Kit\ A.build/Debug/Music\ Kit\ A.build/Music\ Kit\ A-project-headers.hmap -Xcc -I/Users/user/Library/Developer/Xcode/DerivedData/Music_Kit_A-cimwnaollginmxefzprqiioyrhfl/Build/Products/Debug/include -Xcc -I/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include -Xcc -I/Users/user/Library/Developer/Xcode/DerivedData/Music_Kit_A-cimwnaollginmxefzprqiioyrhfl/Build/Intermediates/Music\ Kit\ A.build/Debug/Music\ Kit\ A.build/DerivedSources/x86_64 -Xcc -I/Users/user/Library/Developer/Xcode/DerivedData/Music_Kit_A-cimwnaollginmxefzprqiioyrhfl/Build/Intermediates/Music\ Kit\ A.build/Debug/Music\ Kit\ A.build/DerivedSources -Xcc -DDEBUG=1 -emit-objc-header -emit-objc-header-path /Users/user/Library/Developer/Xcode/DerivedData/Music_Kit_A-cimwnaollginmxefzprqiioyrhfl/Build/Intermediates/Music\ Kit\ A.build/Debug/Music\ Kit\ A.build/Objects-normal/x86_64/Music_Kit_A-Swift.h

Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1
</code>```

What I've tried:

Clean the project

Comment my last changes

Create a new project and transfer the code

When I create a new project, this error goes away, but get another one saying that there is an implicit entry point to main. Searched the whole project for a main function, but nothing showed up. My whole code is here, if it's of any use.

答:
For other people who are having this problem now. Please revert your previously deleted files in the system.

Your project might still be referencing that file somewhere in your project.

Body:
I am stuck with this error for a while, and none of the solutions I've found seems to work (at least, in my case). Here is the full error log:

CompileSwiftSources normal x86_64 com.apple.xcode.tools.swift.compiler
cd "/Users/user/Documents/Music Kit A"
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc -target x86_64-apple-macosx10.10 -module-name Music_Kit_A -Onone -sdk /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk -g -module-cache-path /Users/user/Library/Developer/Xcode/DerivedData/ModuleCache -I /Users/user/Library/Developer/Xcode/DerivedData/Music_Kit_A-cimwnaollginmxefzprqiioyrhfl/Build/Products/Debug -F /Users/user/Library/Developer/Xcode/DerivedData/Music_Kit_A-cimwnaollginmxefzprqiioyrhfl/Build/Products/Debug -c -j4 /Users/user/Documents/Music\ Kit\ A/Music\ Kit\ A/AppDelegate.swift /Users/user/Documents/Music\ Kit\ A/Music\ Kit\ A/main.swift -output-file-map /Users/user/Library/Developer/Xcode/DerivedData/Music_Kit_A-cimwnaollginmxefzprqiioyrhfl/Build/Intermediates/Music\ Kit\ A.build/Debug/Music\ Kit\ A.build/Objects-normal/x86_64/Music\ Kit\ A-OutputFileMap.json -parseable-output -serialize-diagnostics -emit-dependencies -emit-module -emit-module-path /Users/user/Library/Developer/Xcode/DerivedData/Music_Kit_A-cimwnaollginmxefzprqiioyrhfl/Build/Intermediates/Music\ Kit\ A.build/Debug/Music\ Kit\ A.build/Objects-normal/x86_64/Music_Kit_A.swiftmodule -Xcc -I/Users/user/Library/Developer/Xcode/DerivedData/Music_Kit_A-cimwnaollginmxefzprqiioyrhfl/Build/Intermediates/Music\ Kit\ A.build/Debug/Music\ Kit\ A.build/swift-overrides.hmap -Xcc -iquote -Xcc /Users/user/Library/Developer/Xcode/DerivedData/Music_Kit_A-cimwnaollginmxefzprqiioyrhfl/Build/Intermediates/Music\ Kit\ A.build/Debug/Music\ Kit\ A.build/Music\ Kit\ A-generated-files.hmap -Xcc -I/Users/user/Library/Developer/Xcode/DerivedData/Music_Kit_A-cimwnaollginmxefzprqiioyrhfl/Build/Intermediates/Music\ Kit\ A.build/Debug/Music\ Kit\ A.build/Music\ Kit\ A-own-target-headers.hmap -Xcc -I/Users/user/Library/Developer/Xcode/DerivedData/Music_Kit_A-cimwnaollginmxefzprqiioyrhfl/Build/Intermediates/Music\ Kit\ A.build/Debug/Music\ Kit\ A.build/Music\ Kit\ A-all-target-headers.hmap -Xcc -iquote -Xcc /Users/user/Library/Developer/Xcode/DerivedData/Music_Kit_A-cimwnaollginmxefzprqiioyrhfl/Build/Intermediates/Music\ Kit\ A.build/Debug/Music\ Kit\ A.build/Music\ Kit\ A-project-headers.hmap -Xcc -I/Users/user/Library/Developer/Xcode/DerivedData/Music_Kit_A-cimwnaollginmxefzprqiioyrhfl/Build/Products/Debug/include -Xcc -I/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include -Xcc -I/Users/user/Library/Developer/Xcode/DerivedData/Music_Kit_A-cimwnaollginmxefzprqiioyrhfl/Build/Intermediates/Music\ Kit\ A.build/Debug/Music\ Kit\ A.build/DerivedSources/x86_64 -Xcc -I/Users/user/Library/Developer/Xcode/DerivedData/Music_Kit_A-cimwnaollginmxefzprqiioyrhfl/Build/Intermediates/Music\ Kit\ A.build/Debug/Music\ Kit\ A.build/DerivedSources -Xcc -DDEBUG=1 -emit-objc-header -emit-objc-header-path /Users/user/Library/Developer/Xcode/DerivedData/Music_Kit_A-cimwnaollginmxefzprqiioyrhfl/Build/Intermediates/Music\ Kit\ A.build/Debug/Music\ Kit\ A.build/Objects-normal/x86_64/Music_Kit_A-Swift.h

Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1

What I've tried:

Clean the project

Comment my last changes

Create a new project and transfer the code

When I create a new project, this error goes away, but get another one saying that there is an implicit entry point to main. Searched the whole project for a main function, but nothing showed up. My whole code is here, if it's of any use.


问:
How to remove different times from the date from MYSQL
can you help me to update the column of due_date where is something like:

```<code>2017-12-04T02:36:00.000Z
2017-12-04T22:56:00.000Z
2017-12-04T21:34:00.000Z
2017-12-04T06:23:00.000Z
</code>```

to get just pure date like: 2017-12-04

I can use something like:

```<code>UPDATE projects set due_date = REPLACE
(due_date, 'T23:00:00.000Z', '')
</code>```

But the problem is that, in the "due_date" column times can be different like:

```<code>2017-12-04T22:36:00.000Z
2017-12-04T12:22:00.000Z
2017-12-04T15:22:00.000Z
..............
</code>```

Can I update the due_date column to remove completely this part (T15:22:00.000Z), and get just 2017-12-04?
Date column is varchar,

答:
```<code>UPDATE projects SET due_date = DATE(due_date)
</code>```

... done.

https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date

Body:
can you help me to update the column of due_date where is something like:

2017-12-04T02:36:00.000Z
2017-12-04T22:56:00.000Z
2017-12-04T21:34:00.000Z
2017-12-04T06:23:00.000Z

to get just pure date like: 2017-12-04

I can use something like:

UPDATE projects set due_date = REPLACE
(due_date, 'T23:00:00.000Z', '')

But the problem is that, in the "due_date" column times can be different like:

2017-12-04T22:36:00.000Z
2017-12-04T12:22:00.000Z
2017-12-04T15:22:00.000Z
..............

Can I update the due_date column to remove completely this part (T15:22:00.000Z), and get just 2017-12-04?
Date column is varchar,

Body:
UPDATE projects SET due_date = DATE(due_date)

... done.

https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date


问:
how to run all queue jobs in one line
Can someone know how can I run in one command to Laravel artisan work on all queue in project?

I know that I can run something like that nohup php artisan queue:work --queue=admin_contact_message_mail,user_get_message_notification,user_get_message_mail --daemon & , but I have a huge list of queues and asks is there any way to call it all in once or I need to list them all to queue run it and listen it?

答: php artisan queue:listen will do the job!

Title: how to run all queue jobs in one line


问:
Creating Auto run on USB device
I want to make A project which the disk on key I insert will run a python file  that blocks access to the files in the disk on key , therefore I need to make an autorun on the disk on key to run that code
I was trying reading about the autorun and as I found it was blocked on windows 7 and above
Is there any way to do it in win7 and above?</p>

答:
You have to enable the autorun feature in newer versions of windows.By default, it is disabled for security purposes so in short you cannot use autorun feature without enabling autorun.
Edit: I searched a bit and it is nearly impossible to autorun a program in any other computer without admin privileges however this link might help you as they claim it worked.</p>

Title: Creating Auto run on USB device


问:
Python - using multi-processing / multi threading for web scraping
I am using wikipedia python package to scrape data of a particular topic

```<code>q=['NASA', 'NASA_insignia', 'NASA_spinoff_technologies', 'NASA_facilities', 'NASA_Pathfinder', 'List_of_NASA_missions', 'Langley_Research_Center', 'NASA-TLX', 'Budget_of_NASA', 'NASA_(disambiguation)']
</code>```

Example above, I've searched for NASA. Now I need to obtain the summary for each of the element in the list.

```<code>ny = []
for i in range(len(q)):
    y = wikipedia.page(q[i])
    x = y.summary
    ny.append(x)
</code>```

In doing this whole process i.e. traversing each element of list and retrieving summary of each element, it's taking almost 40-60 seconds for the entire process to be completed (even with a good network connection)

I don't know much about multiprocessing / multithreading. How can i speed up the execution by a considerable time? Any help will be appreciated.

答:
You can use a processing pool (see documentation).

Here is an example based on your code:

```<code>from multiprocessing import Pool

q = ['NASA', 'NASA_insignia', 'NASA_spinoff_technologies', 'NASA_facilities', 'NASA_Pathfinder',
     'List_of_NASA_missions', 'Langley_Research_Center', 'NASA-TLX', 'Budget_of_NASA', 'NASA_(disambiguation)']

def f(q_i):
    y = wikipedia.page(q_i)
    return y.summary

with Pool(5) as p:
    ny = p.map(f, q)
</code>```

Basically f is applied for each element in q in separate processes.
You can determine the number of processes when defining the pool (5 in my example).

Body:
I am using wikipedia python package to scrape data of a particular topic

q=['NASA', 'NASA_insignia', 'NASA_spinoff_technologies', 'NASA_facilities', 'NASA_Pathfinder', 'List_of_NASA_missions', 'Langley_Research_Center', 'NASA-TLX', 'Budget_of_NASA', 'NASA_(disambiguation)']

Example above, I've searched for NASA. Now I need to obtain the summary for each of the element in the list.

ny = []
for i in range(len(q)):
    y = wikipedia.page(q[i])
    x = y.summary
    ny.append(x)

In doing this whole process i.e. traversing each element of list and retrieving summary of each element, it's taking almost 40-60 seconds for the entire process to be completed (even with a good network connection)

I don't know much about multiprocessing / multithreading. How can i speed up the execution by a considerable time? Any help will be appreciated.

Body:
You can use a processing pool (see documentation).

Here is an example based on your code:

from multiprocessing import Pool

q = ['NASA', 'NASA_insignia', 'NASA_spinoff_technologies', 'NASA_facilities', 'NASA_Pathfinder',
     'List_of_NASA_missions', 'Langley_Research_Center', 'NASA-TLX', 'Budget_of_NASA', 'NASA_(disambiguation)']

def f(q_i):
    y = wikipedia.page(q_i)
    return y.summary

with Pool(5) as p:
    ny = p.map(f, q)

Basically f is applied for each element in q in separate processes.
You can determine the number of processes when defining the pool (5 in my example).


问:
How to design forms in Xamarin?
I have Design One page but it not look like the requirement. I am new to Xamarin and I don't know how to design like Attached image.

My Code is

```<code> <Grid Margin="5">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="80"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="40"/>
                <RowDefinition Height="40"/>
                <RowDefinition Height="40"/>
                <RowDefinition Height="40"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="40"/>
            </Grid.RowDefinitions>
            <Label Text="From" Font="20" Grid.Row="0" Grid.Column="0"></Label>
            <Entry x:Name="txtFrom" HorizontalOptions="FillAndExpand" Grid.Row="0" Grid.Column="1" ></Entry>
            <Label Text="To" Font="20" Grid.Row="1" Grid.Column="0"></Label>
            <Entry x:Name="txtTo"  Grid.Row="1" Grid.Column="1" HorizontalOptions="FillAndExpand"></Entry>
            <Label Text="Subject" Font="20" Grid.Column="0" Grid.Row="2"></Label>
            <Entry x:Name="txtSubject" HorizontalOptions="FillAndExpand" Grid.Column="1" Grid.Row="2"></Entry>
            <Label Text="Body" Font="20" Grid.Column="0" Grid.Row="3"></Label>
            <Editor  x:Name="txtBody" HeightRequest="100"  Grid.Row="4" Grid.ColumnSpan="2"></Editor>
            <Button x:Name="btnSend"  Text="Send" BackgroundColor="Orange" Grid.Row="5" Grid.ColumnSpan="2"></Button>

        </Grid>
</code>```

My Ui Look like another attached image.

答:
Use .Xaml file for design forms in xamarin.form.

see Xamarin official  tutorial
https://developer.xamarin.com/

Title: How to design forms in Xamarin?

Body:
I have Design One page but it not look like the requirement. I am new to Xamarin and I don't know how to design like Attached image.

My Code is

 <Grid Margin="5">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="80"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="40"/>
                <RowDefinition Height="40"/>
                <RowDefinition Height="40"/>
                <RowDefinition Height="40"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="40"/>
            </Grid.RowDefinitions>

            <Entry x:Name="txtFrom" HorizontalOptions="FillAndExpand" Grid.Row="0" Grid.Column="1" ></Entry>

            <Entry x:Name="txtTo"  Grid.Row="1" Grid.Column="1" HorizontalOptions="FillAndExpand"></Entry>

            <Entry x:Name="txtSubject" HorizontalOptions="FillAndExpand" Grid.Column="1" Grid.Row="2"></Entry>

            <Editor  x:Name="txtBody" HeightRequest="100"  Grid.Row="4" Grid.ColumnSpan="2"></Editor>
            <Button x:Name="btnSend"  Text="Send" BackgroundColor="Orange" Grid.Row="5" Grid.ColumnSpan="2"></Button>

        </Grid>

My Ui Look like another attached image.


问:
Save byte array to binary file
I have class representing car with two attributes. I want to convert it to byte[] and save it to binary file.

```<code>class Car
    {
        private string type;
        private int id;

        public Car(string paType, int paId)
        {
            type = paType;
            id = paId;
        }

        public byte[] ByteConverter()
        {
            byte[] bArr = new byte[14];

            byte[] hlpType = Encoding.UTF8.GetBytes(this.type);

            byte[] hlpId = BitConverter.GetBytes(this.id);

            hlpType.CopyTo(bArr, 0);
            hlpId.CopyTo(bArr, hlpType.Length);

            return bArr;
        }
    }
</code>```

Save method body:

```<code>Car c = new Car("abcd", 12);
FileStream fsStream = new FileStream("cardata.bin", FileMode.Create);
fsStream.Write(c.ByteConverter(), 0, 14);
fsStream.Close();
</code>```

If I open file cardata.dat, there is string.

abcd

How to solve this? Thanks.

答:
You need to convert/serialize the object Car to a byte array</p>

```<code>public static byte[] CarToByteArray(Car car)
{
    BinaryFormatter binf = new BinaryFormatter();
    using (var ms = new MemoryStream())
    {
        binf.Serialize(ms, car);
        return ms.ToArray();
    }
}
</code>```

Title: Save byte array to binary file

Body:
I have class representing car with two attributes. I want to convert it to byte[] and save it to binary file.

class Car
    {
        private string type;
        private int id;

        public Car(string paType, int paId)
        {
            type = paType;
            id = paId;
        }

        public byte[] ByteConverter()
        {
            byte[] bArr = new byte[14];

            byte[] hlpType = Encoding.UTF8.GetBytes(this.type);

            byte[] hlpId = BitConverter.GetBytes(this.id);

            hlpType.CopyTo(bArr, 0);
            hlpId.CopyTo(bArr, hlpType.Length);

            return bArr;
        }
    }

Save method body:

Car c = new Car("abcd", 12);
FileStream fsStream = new FileStream("cardata.bin", FileMode.Create);
fsStream.Write(c.ByteConverter(), 0, 14);
fsStream.Close();

If I open file cardata.dat, there is string.

abcd

How to solve this? Thanks.

Body:
You need to convert/serialize the object Car to a byte array

public static byte[] CarToByteArray(Car car)
{
    BinaryFormatter binf = new BinaryFormatter();
    using (var ms = new MemoryStream())
    {
        binf.Serialize(ms, car);
        return ms.ToArray();
    }
}


问:
How to put HTML, CSS and JS in one single file
So I have created a landing page for a client's website. They apparenlty can't upload the folder with the JS files, so they need all the JS and CSS in one same file.

I started putting (before the body section) all the CSS putting it into  and the JS putting in into , but all the animations inside the JS don't work.

Is there any way/advice on how to put it all together?

Thanks!

Ps: I could give more info if needed!

答:
You just need to add a style section and a scripts section in the head</p>

```<code><html>
<head>
    <style type="text/css">

        /* CSS goes here */

    </style>
    <script type="text/javascript">

        /* Javascript goes here */

    </script>
</head>
<body>
</body>
</html>
</code>```

Body:
You just need to add a style section and a scripts section in the head

<html>
<head>
    <style type="text/css">

        /* CSS goes here */

    </style>
    <script type="text/javascript">

        /* Javascript goes here */

    </script>
</head>
<body>
</body>
</html>


问:
Finding objects in Core Data by array attribute, performantly in >10k elements
Short:

I need to find core data objects by a key, which holds a unique immutable array (fixed length, but chosen at runtime) of arbitrary objects (for which not only element membership, but also element order determines uniqueness). NSManagedObject however forbids overriding [isEqual:]. Now what?

Long:

I have an entity (see diagram image for entity "…Link") in my Core Data model for which I have to guarantee uniqueness based on an attribute key ("tuple"). So far so good.

The entity's unique attribute however has to be an NSArray.

And to make things a bit more difficult I neither know the class type of the tuple's elements.

Nor do I know the tuple's element count. Well, actually the count is the same for every tuple (per core data context at least), but not known before the app runs.

There must only ever be one instance of my link entity with a given tuple.

And for obvious reason only ever one tuple instance with a given array of arbitrary objects.

Whereas two tuples are to be considered equal if [tuple_1 isEqual:tuple_n] returns YES.  NSManagedObject forbids the overriding of [isEqual:] and [hash] though, otherwise things would be pretty much a piece of cake.

"…Tuple" objects are created together with their array of tokens (via a convenience method) and are immutable (and so is each "…Token" and its data attribute). (think of "…Tuple" as a "…Link"'s dictionary key.)

"…Tuple" implements "- (NSArray *)tokens;", which returnes a neatly ordered array of tokens, based on the "order" keys of "…TokenOrder". (Tuples are expected to contain at most 5 elements.)

I however expect to have tens of thousands (potentially even more in some edge cases) of "…Link" objects, which I have to (frequently) find based on their "tuple" attribute.

Sadly I couldn't find any article (let alone solution) for such a scenario in any literature or the web.

Any ideas?

A possible solution I've come up with so far would be:

Narrow amount of elements to compare
by tuple by adding another attribute
to "…Tuple" called "tupleHash",
which is pre-calculated on
object creation via: Snippet 1

Query with NSPredicate for objects of matching tupleHash (narrowing down the list of candidates quite a bit).

Find "…Link" featuring given tuple in narrowed candidate list by: Snippet 1

Snippet 1:

```<code>NSUInteger tupleHash = [[self class] hash];
for (id token in self.tokens) {
    tupleHash ^= [token.data hash];
}
</code>```

Snippet 2:

```<code>__block NSArray *tupleTokens = someTokens;
NSArray *filteredEntries = [narrowedCandidates filteredArrayUsingPredicate:
  [NSPredicate predicateWithBlock: ^(id evaluatedObject, NSDictionary *bindings) {
    return [evaluatedObject.tuple.tokens isEqualToArray:tupleTokens];
}]];
</code>```

(Sorry, markdown appears to oppose mixing of lists with code snippets.)

Good idea of or just insane?

Thanks in advance!

答:
As recommended in a comment by Joe Blow I'm just gonna go with SQLite. Core Data simply appears to be the wrong tool here.

Benefits:

Fast thanks to SQL's column indexing

No object allocation/initialization on SELECT, prior to returning the results. (which Core Data would require for attribute checks)

Easily query link tuples using JOINs.

Easy use of SQLite's JOIN, GROUP BY, ORDER BY, etc

Little to no wrapper code thanks to EGODatabase (FMDB-inspired SQLite Objective-C wrapper)

Body:
Short:

I need to find core data objects by a key, which holds a unique immutable array (fixed length, but chosen at runtime) of arbitrary objects (for which not only element membership, but also element order determines uniqueness). NSManagedObject however forbids overriding [isEqual:]. Now what?

Long:

I have an entity (see diagram image for entity "…Link") in my Core Data model for which I have to guarantee uniqueness based on an attribute key ("tuple"). So far so good.

The entity's unique attribute however has to be an NSArray.

And to make things a bit more difficult I neither know the class type of the tuple's elements.

Nor do I know the tuple's element count. Well, actually the count is the same for every tuple (per core data context at least), but not known before the app runs.

There must only ever be one instance of my link entity with a given tuple.

And for obvious reason only ever one tuple instance with a given array of arbitrary objects.

Whereas two tuples are to be considered equal if [tuple_1 isEqual:tuple_n] returns YES.  NSManagedObject forbids the overriding of [isEqual:] and [hash] though, otherwise things would be pretty much a piece of cake.

"…Tuple" objects are created together with their array of tokens (via a convenience method) and are immutable (and so is each "…Token" and its data attribute). (think of "…Tuple" as a "…Link"'s dictionary key.)

"…Tuple" implements "- (NSArray *)tokens;", which returnes a neatly ordered array of tokens, based on the "order" keys of "…TokenOrder". (Tuples are expected to contain at most 5 elements.)

I however expect to have tens of thousands (potentially even more in some edge cases) of "…Link" objects, which I have to (frequently) find based on their "tuple" attribute.

Sadly I couldn't find any article (let alone solution) for such a scenario in any literature or the web.

Any ideas?

A possible solution I've come up with so far would be:

Narrow amount of elements to compare
by tuple by adding another attribute
to "…Tuple" called "tupleHash",
which is pre-calculated on
object creation via: Snippet 1

Query with NSPredicate for objects of matching tupleHash (narrowing down the list of candidates quite a bit).

Find "…Link" featuring given tuple in narrowed candidate list by: Snippet 1

Snippet 1:

NSUInteger tupleHash = [[self class] hash];
for (id token in self.tokens) {
    tupleHash ^= [token.data hash];
}

Snippet 2:

__block NSArray *tupleTokens = someTokens;
NSArray *filteredEntries = [narrowedCandidates filteredArrayUsingPredicate:
  [NSPredicate predicateWithBlock: ^(id evaluatedObject, NSDictionary *bindings) {
    return [evaluatedObject.tuple.tokens isEqualToArray:tupleTokens];
}]];

(Sorry, markdown appears to oppose mixing of lists with code snippets.)

Good idea of or just insane?

Thanks in advance!


问:
First TCP response receiving 0 bytes but according to netmon there are responses after that
I have a situation where I am sending the correct request bytes to a machine. When run through another application I can see that the response is sent, the machine sends a first response that contains no bytes (only header data) so in my code I am checking if "tcpStream.DataAvailable" it obviously returns "false" then the program exits.

The problem is that first response is not where the data is...it is in several following responses.

So basically how do I ignore the first response and wait for the data in the 2+ responses?

This is the snippet of code I am using:

```<code>byte[] myReadBuffer = new byte[1024];
StringBuilder myCompleteMessage = new StringBuilder();
int numberOfBytesRead = 0;

// Incoming message may be larger than the buffer size.
do
{
    numberOfBytesRead = tcpStream.Read(myReadBuffer, 0, myReadBuffer.Length);
    myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));
}
while (tcpStream.DataAvailable);
</code>```

UPDATE:

I changed the code to asynchronously handle the communication. This is the new code (still doesn't work):

```<code> public class GetCellList
{
    private ManualResetEvent connectDone = new ManualResetEvent(false);
    private ManualResetEvent sendDone = new ManualResetEvent(false);
    private ManualResetEvent receiveDone = new ManualResetEvent(false);

    private string _serverIP;
    private int _serverPort;
    private StateObject _stateObject = new StateObject();

    private static String response = String.Empty;

    public GetCellList(string serverIP, int serverPort)
    {
        _serverIP = serverIP;
        _serverPort = serverPort;
        _stateObject.workSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(_serverIP), _serverPort);
        StartClient(remoteEP);
    }

    private void StartClient(IPEndPoint remoteEndpoint)
    {
        try
        {
            _stateObject.workSocket.BeginConnect(remoteEndpoint,
                    new AsyncCallback(ConnectCallback), _stateObject.workSocket);
            connectDone.WaitOne();

            Send(_stateObject.workSocket, GetData());
            sendDone.WaitOne();

            Receive(_stateObject.workSocket);
            receiveDone.WaitOne();

            Console.WriteLine("Response received : {0}", response);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private byte[] GetData()
    {
        var requestString = "00 25 B4 CE 42 80 D4 81 D7 DD 44 37 08 00 45 00 00 43 06 27 00 00 80 06 00 00 0A D4 E2 4E 0A 68 3D CC 2E 12 04 01 4B 7A C8 7B FE 5C 2E F5 50 18 00 FF 35 8C 00 00 43 50 43 52 00 01 19 00 00 00 1B 00 00 00 02 00 00 00 00 00 00 00 1D 00 00 00 00".Replace(" ", "");

        return Convertors.ConvertToByteArray(requestString);

    }

    private void ConnectCallback(IAsyncResult ar)
    {
        try
        {
            Socket client = (Socket)ar.AsyncState;

            client.EndConnect(ar);

            Console.WriteLine("Socket connected to {0}",
                client.RemoteEndPoint.ToString());

            connectDone.Set();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private void Receive(Socket client)
    {
        try
        {
            StateObject state = new StateObject();
            state.workSocket = client;

            client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReceiveCallback), state);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private void ReceiveCallback(IAsyncResult ar)
    {
        try
        {
            StateObject state = (StateObject)ar.AsyncState;
            Socket client = state.workSocket;

            int bytesRead = client.EndReceive(ar);

            if (bytesRead > 0)
            {
                state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReceiveCallback), state);
            }
            else
            {

                if (state.sb.Length > 1)
                {
                    response = state.sb.ToString();
                }

                receiveDone.Set();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private void Send(Socket client, byte[] byteData)
    {
        client.BeginSend(byteData, 0, byteData.Length, 0,
            new AsyncCallback(SendCallback), client);
    }

    private void SendCallback(IAsyncResult ar)
    {
        try
        {
            Socket client = (Socket)ar.AsyncState;

            int bytesSent = client.EndSend(ar);
            Console.WriteLine("Sent {0} bytes to server.", bytesSent);

            sendDone.Set();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
}
</code>```

}

答:
The problem here is exactly that you're checking for tcpStream.DataAvailable. This is the amount of data buffered locally, and it being zero tells you nothing about what is about to arrive. The more typical loop would be:

```<code>while((numberOfBytesRead = tcpStream.Read(myReadBuffer, 0, myReadBuffer.Length)) > 0)
{ ... }
</code>```

The only real use for DataAvailable is deciding whether to read synchronously or asynchronously - you might choose to read asynchronously if there's nothing in the buffer.

Note that in general you should also be very careful about "framing" and knowing whether what you have in the buffer can be sensibly processed; you just about get away with it in your case since you're using ASCII, but if this was something like UTF8 you'd need to be much more careful, as a single character might span two (or more, in theory) Read calls - meaning you might get one byte of a 3-byte character at the end of the buffer, and the other two bytes of that same character at the start of the buffer in the next Read call.

Body:
I have a situation where I am sending the correct request bytes to a machine. When run through another application I can see that the response is sent, the machine sends a first response that contains no bytes (only header data) so in my code I am checking if "tcpStream.DataAvailable" it obviously returns "false" then the program exits.

The problem is that first response is not where the data is...it is in several following responses.

So basically how do I ignore the first response and wait for the data in the 2+ responses?

This is the snippet of code I am using:

byte[] myReadBuffer = new byte[1024];
StringBuilder myCompleteMessage = new StringBuilder();
int numberOfBytesRead = 0;

// Incoming message may be larger than the buffer size.
do
{
    numberOfBytesRead = tcpStream.Read(myReadBuffer, 0, myReadBuffer.Length);
    myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(myReadBuffer, 0, numberOfBytesRead));
}
while (tcpStream.DataAvailable);

UPDATE:

I changed the code to asynchronously handle the communication. This is the new code (still doesn't work):

 public class GetCellList
{
    private ManualResetEvent connectDone = new ManualResetEvent(false);
    private ManualResetEvent sendDone = new ManualResetEvent(false);
    private ManualResetEvent receiveDone = new ManualResetEvent(false);

    private string _serverIP;
    private int _serverPort;
    private StateObject _stateObject = new StateObject();

    private static String response = String.Empty;

    public GetCellList(string serverIP, int serverPort)
    {
        _serverIP = serverIP;
        _serverPort = serverPort;
        _stateObject.workSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(_serverIP), _serverPort);
        StartClient(remoteEP);
    }

    private void StartClient(IPEndPoint remoteEndpoint)
    {
        try
        {
            _stateObject.workSocket.BeginConnect(remoteEndpoint,
                    new AsyncCallback(ConnectCallback), _stateObject.workSocket);
            connectDone.WaitOne();

            Send(_stateObject.workSocket, GetData());
            sendDone.WaitOne();

            Receive(_stateObject.workSocket);
            receiveDone.WaitOne();

            Console.WriteLine("Response received : {0}", response);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private byte[] GetData()
    {
        var requestString = "00 25 B4 CE 42 80 D4 81 D7 DD 44 37 08 00 45 00 00 43 06 27 00 00 80 06 00 00 0A D4 E2 4E 0A 68 3D CC 2E 12 04 01 4B 7A C8 7B FE 5C 2E F5 50 18 00 FF 35 8C 00 00 43 50 43 52 00 01 19 00 00 00 1B 00 00 00 02 00 00 00 00 00 00 00 1D 00 00 00 00".Replace(" ", "");

        return Convertors.ConvertToByteArray(requestString);

    }

    private void ConnectCallback(IAsyncResult ar)
    {
        try
        {
            Socket client = (Socket)ar.AsyncState;

            client.EndConnect(ar);

            Console.WriteLine("Socket connected to {0}",
                client.RemoteEndPoint.ToString());

            connectDone.Set();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private void Receive(Socket client)
    {
        try
        {
            StateObject state = new StateObject();
            state.workSocket = client;

            client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReceiveCallback), state);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private void ReceiveCallback(IAsyncResult ar)
    {
        try
        {
            StateObject state = (StateObject)ar.AsyncState;
            Socket client = state.workSocket;

            int bytesRead = client.EndReceive(ar);

            if (bytesRead > 0)
            {
                state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReceiveCallback), state);
            }
            else
            {

                if (state.sb.Length > 1)
                {
                    response = state.sb.ToString();
                }

                receiveDone.Set();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private void Send(Socket client, byte[] byteData)
    {
        client.BeginSend(byteData, 0, byteData.Length, 0,
            new AsyncCallback(SendCallback), client);
    }

    private void SendCallback(IAsyncResult ar)
    {
        try
        {
            Socket client = (Socket)ar.AsyncState;

            int bytesSent = client.EndSend(ar);
            Console.WriteLine("Sent {0} bytes to server.", bytesSent);

            sendDone.Set();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
}

}

Body:
The problem here is exactly that you're checking for tcpStream.DataAvailable. This is the amount of data buffered locally, and it being zero tells you nothing about what is about to arrive. The more typical loop would be:

while((numberOfBytesRead = tcpStream.Read(myReadBuffer, 0, myReadBuffer.Length)) > 0)
{ ... }

The only real use for DataAvailable is deciding whether to read synchronously or asynchronously - you might choose to read asynchronously if there's nothing in the buffer.

Note that in general you should also be very careful about "framing" and knowing whether what you have in the buffer can be sensibly processed; you just about get away with it in your case since you're using ASCII, but if this was something like UTF8 you'd need to be much more careful, as a single character might span two (or more, in theory) Read calls - meaning you might get one byte of a 3-byte character at the end of the buffer, and the other two bytes of that same character at the start of the buffer in the next Read call.


问:
jQuery function looping again and again
I want to create an animation where with scrolling background image of the Website changes. Changing happens with a fadeIn and fadeOut effect, But fading effect happens multiple times due to scroll function.

JSFiddle

```<code>Jquery Code:
var styles01 = {"background" : "url(https://iso.500px.com/wp-content/uploads/2016/02/cover.jpg) fixed",
                 "background-size":"cover"};
var styles02 = {"background" : "url(http://www.mybligr.com/wp-content/uploads/2017/02/beautiful-lake-wallpaper-nature-photos-pics-images-pictures-16.jpg) fixed",
            "background-size":"cover"};
var styles03 = {"background" : "url(https://cdn.fodors.com/ee/files/slideshows/9-derwent-water-lake-district-england.jpg) fixed",
            "background-size":"cover"};

$(window).scroll( function() {
 if ($(window).scrollTop() >= 50 && $(window).scrollTop() <= 150) {
     $(".wrap").fadeOut(200);
    $(".wrap").css(styles01);
     $(".wrap").fadeIn(200);
  }
 if ($(window).scrollTop() >= 150 && $(window).scrollTop() <= 250) {
      $(".wrap").fadeOut(200);
    $(".wrap").css(styles02);
       $(".wrap").fadeIn(200);
  }
 if ($(window).scrollTop() < 50) {
     $(".wrap").fadeOut(200);
    $(".wrap").css(styles03);
      $(".wrap").fadeIn(200);
  }
});
</code>```

答:
It appears to be a timing issue, because you're trying to re-style and re-fade before the initial fade-out is done.  This is an asynchronous operation:

```<code>$(".wrap").fadeOut(200);
</code>```

So anything that needs to happen after this operation should be placed in its callback, not placed immediately after this line of code.  Something like this:

```<code>$(".wrap").fadeOut(200, function () {
    $(".wrap").css(styles01);
    $(".wrap").fadeIn(200);
});
</code>```

Updated fiddle.

Title: jQuery function looping again and again

Body:
I want to create an animation where with scrolling background image of the Website changes. Changing happens with a fadeIn and fadeOut effect, But fading effect happens multiple times due to scroll function.

JSFiddle

Jquery Code:
var styles01 = {"background" : "url(https://iso.500px.com/wp-content/uploads/2016/02/cover.jpg) fixed",
                 "background-size":"cover"};
var styles02 = {"background" : "url(http://www.mybligr.com/wp-content/uploads/2017/02/beautiful-lake-wallpaper-nature-photos-pics-images-pictures-16.jpg) fixed",
            "background-size":"cover"};
var styles03 = {"background" : "url(https://cdn.fodors.com/ee/files/slideshows/9-derwent-water-lake-district-england.jpg) fixed",
            "background-size":"cover"};

$(window).scroll( function() {
 if ($(window).scrollTop() >= 50 && $(window).scrollTop() <= 150) {
     $(".wrap").fadeOut(200);
    $(".wrap").css(styles01);
     $(".wrap").fadeIn(200);
  }
 if ($(window).scrollTop() >= 150 && $(window).scrollTop() <= 250) {
      $(".wrap").fadeOut(200);
    $(".wrap").css(styles02);
       $(".wrap").fadeIn(200);
  }
 if ($(window).scrollTop() < 50) {
     $(".wrap").fadeOut(200);
    $(".wrap").css(styles03);
      $(".wrap").fadeIn(200);
  }
});

Body:
It appears to be a timing issue, because you're trying to re-style and re-fade before the initial fade-out is done.  This is an asynchronous operation:

$(".wrap").fadeOut(200);

So anything that needs to happen after this operation should be placed in its callback, not placed immediately after this line of code.  Something like this:

$(".wrap").fadeOut(200, function () {
    $(".wrap").css(styles01);
    $(".wrap").fadeIn(200);
});

Updated fiddle.


问:
Android getString() loads wrong resource
I have this method in a class (normal class not activity)

```<code>    public String getTitle(Context context) {
      Log.d(TAG, Locale.getDefault().toString() + ", " + context.getString(R.string.title));
    return context.getString(R.string.title);
  }
</code>```

When I call this method from activity passing context (getApplicationContext()) the log prints (ar, Categories)
I double checked strings in xml and there are english and arabic word
so how come? locale is arabic and it returns english resource.

答:
Add a folder in res  , named it values-ar . Create a string.xml file inside that folder  .  Put your title there as below .

```<code>  <string name="title">arbic word</string>
</code>```

If your locale is set to arbic than You can get  your resouce String using below code .

```<code>context.getResources().getString(R.string.title);
</code>```

Body:
I have this method in a class (normal class not activity)

    public String getTitle(Context context) {
      Log.d(TAG, Locale.getDefault().toString() + ", " + context.getString(R.string.title));
    return context.getString(R.string.title);
  }

When I call this method from activity passing context (getApplicationContext()) the log prints (ar, Categories)
I double checked strings in xml and there are english and arabic word
so how come? locale is arabic and it returns english resource.

Body:
Add a folder in res  , named it values-ar . Create a string.xml file inside that folder  .  Put your title there as below .

  <string name="title">arbic word</string>

If your locale is set to arbic than You can get  your resouce String using below code .

context.getResources().getString(R.string.title);


答:
If due_date is a string, I would recommend:

```<code>update projects
     set due_date = left(due_date, 10);
</code>```

Then, I would recommend changing the type:

```<code>alter table projects alter column due_date date;
</code>```

You should use the appropriate type for your columns.  Date/time values should not be stored as strings.

Title: How to remove different times from the date from MYSQL

Body:
If due_date is a string, I would recommend:

update projects
     set due_date = left(due_date, 10);

Then, I would recommend changing the type:

alter table projects alter column due_date date;

You should use the appropriate type for your columns.  Date/time values should not be stored as strings.


问:
mod rewrite Rule for Image + String to Imagefolder Rewrite
I have got some images on my server, which were always generated on the fly and requested right here:
http://www.mydomain.com/en/images.png?domain=test.com

They are now cached in
http://www.mydomain.com/images/test.com.png

I tried the following rule in my htaccess, but it doesn't work:

RewriteRule ^(en|de)?/images.png\?domain=(.*) /images/$2.png   [QSA,L]

Any clue what's wrong?

答:
The query string is not part of what you're comparing to implicitly with RewriteRule, you need a RewriteCond to match/capture it to use in your substitution:

http://wiki.apache.org/httpd/RewriteQueryString


问:
Compiler error for Haskell program not understood
I'm working on a large Haskell program, so I'm only including the code that seems relevant here to make the problem clearer.  Please comment if I should include more.

When I compile, I get only one error message: "parse error (possibly incorrect indentation or mismatched brackets)"

Here is some code with no errors (printStmt) and a very similar section (VarDeclStmt) with the error directed at the line reading, "expr >>= \s ->".  I don't see why one would be fine and the other would cause a problem.  In what way are they different?

```<code>printStmt =
            keyword "print" >>
            expr >>= \e ->
            symbol ";" >>
            return (Print e)

varDeclStmt = do
              keyword "var" >>
              expr >>= \s -> --ERROR
              symbol "=" >>
              expr >>= \e ->
              return (VarDecl s e)
</code>```

答:
This is an indentation issue. The block

```<code>varDeclStmt = do
              keyword "var" >>
              expr >>= \s -> --ERROR
              symbol "=" >>
              expr >>= \e ->
              return (VarDecl s e)
</code>```

parses as

```<code>varDeclStmt = do
              { keyword "var" >>
              ; expr >>= \s -> --ERROR
              ; symbol "=" >>
              ; expr >>= \e ->
              ; return (VarDecl s e)
              }
</code>```

which is nonsense, since the first entry keyword "var" >> is not valid.

Note that indenting the whole block further (or less) does not change how it is parsed.

The easiest fix is to remove do completely, so that the text below that is not parsed as a block, hence it is not split into separate entries, but parsed as if it were on a single line.

Otherwise, you can switch to proper do notation

```<code>varDeclStmt = do
              keyword "var"
              s <- expr
              symbol "="
              e <- expr
              return (VarDecl s e)
</code>```

or (worst solution), make the do block a single-entry one, making the block indented more than the first line, as follos

```<code>varDeclStmt = do
              keyword "var" >>
                expr >>= \s ->
                symbol "=" >>
                expr >>= \e ->
                return (VarDecl s e)
</code>```

The above solution is silly, though, since the purpose of do is splitting the block into entries, and the indentation is made so that there is only one entry. So, we use two things to counteract each other.

Body:
I'm working on a large Haskell program, so I'm only including the code that seems relevant here to make the problem clearer.  Please comment if I should include more.

When I compile, I get only one error message: "parse error (possibly incorrect indentation or mismatched brackets)"

Here is some code with no errors (printStmt) and a very similar section (VarDeclStmt) with the error directed at the line reading, "expr >>= \s ->".  I don't see why one would be fine and the other would cause a problem.  In what way are they different?

printStmt =
            keyword "print" >>
            expr >>= \e ->
            symbol ";" >>
            return (Print e)

varDeclStmt = do
              keyword "var" >>
              expr >>= \s -> --ERROR
              symbol "=" >>
              expr >>= \e ->
              return (VarDecl s e)

Body:
This is an indentation issue. The block

varDeclStmt = do
              keyword "var" >>
              expr >>= \s -> --ERROR
              symbol "=" >>
              expr >>= \e ->
              return (VarDecl s e)

parses as

varDeclStmt = do
              { keyword "var" >>
              ; expr >>= \s -> --ERROR
              ; symbol "=" >>
              ; expr >>= \e ->
              ; return (VarDecl s e)
              }

which is nonsense, since the first entry keyword "var" >> is not valid.

Note that indenting the whole block further (or less) does not change how it is parsed.

The easiest fix is to remove do completely, so that the text below that is not parsed as a block, hence it is not split into separate entries, but parsed as if it were on a single line.

Otherwise, you can switch to proper do notation

varDeclStmt = do
              keyword "var"
              s <- expr
              symbol "="
              e <- expr
              return (VarDecl s e)

or (worst solution), make the do block a single-entry one, making the block indented more than the first line, as follos

varDeclStmt = do
              keyword "var" >>
                expr >>= \s ->
                symbol "=" >>
                expr >>= \e ->
                return (VarDecl s e)

The above solution is silly, though, since the purpose of do is splitting the block into entries, and the indentation is made so that there is only one entry. So, we use two things to counteract each other.


问:
Uploading object to fireBase with image attached on android
Is there a way to upload object ,  Lets say for the example it is a User , with image to fireBase ?

According to what i have read i need to upload the user's image to storage and than upload the User to the Real time Db with the url i received when i uploaded the image in the first step .

is there a way on fire base to upload the user with the image on one Request so i will not have to

1 . do 2 request

2 . connect the request with an id so the user will know the image

3 . handle 2 requests responses .

Thanks .

答:
No, there is not! You should do two separate operations, one for storing the image into Firebase Storage and getting the url at the same time and second to upload that url to Firebase database. This means that 2 requests are needed.

```<code>//This how you initialize Firebase Storage
FirebaseStorage storage = FirebaseStorage.getInstance();

//This how you initialize Firebase database
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
</code>```

This two operations needs to be done in order to achieve what you want. Cannot be done in a single request.

Body:
No, there is not! You should do two separate operations, one for storing the image into Firebase Storage and getting the url at the same time and second to upload that url to Firebase database. This means that 2 requests are needed.

//This how you initialize Firebase Storage
FirebaseStorage storage = FirebaseStorage.getInstance();

//This how you initialize Firebase database
DatabaseReference database = FirebaseDatabase.getInstance().getReference();

This two operations needs to be done in order to achieve what you want. Cannot be done in a single request.