问:
ant build failes on Jenkins
When I start the Jenkins build, on arriving on ant-build-step the build is canceled immediately with the following stack:

```<code>...
[PROJECT] $ cmd.exe /C "D:\jenkins\tools\hudson.tasks.Ant_AntInstallation\Ant\bin\ant.bat -file build-jenkins.xml -Djenkins.result.dir=${JENKINS.WORKSPACES}/Results "-Dbranch=*/develop" -Djenkins.result.dir=C:/Tools/Jenkins/Results -Djenkins.workspace.dir=C:\Tools\Jenkins\Project-SNAPSHOT\workspace/PRO_56/PRO/java/Project -Dproject.path=C:\Tools\Jenkins\Project-SNAPSHOT\workspace clean.compile.jar.server.snapshot -v && exit %%ERRORLEVEL%%"
Usage: java [-options] class [args...]
           (to execute a class)
   or  java [-options] -jar jarfile [args...]
           (to execute a jar file)
where options include:
...
See http://www.oracle.com/technetwork/java/javase/documentation/index.html for more details.
Build step 'Invoke Ant' marked build as failure
Finished: FAILURE
</code>```

I get no debug messages, nothing.
I've got other project with a similar/equal config which work. I think it could be a incompatibility of my plugins.

Has anyone experienced this bug before?

答:
In my case the problem was a big M in the java options of the ant-build-step.
Here no m for Megabit und M für Megabyte.

-Xmx1024M
-Xms1024m

Title: ant build failes on Jenkins

Body:
When I start the Jenkins build, on arriving on ant-build-step the build is canceled immediately with the following stack:

...
[PROJECT] $ cmd.exe /C "D:\jenkins\tools\hudson.tasks.Ant_AntInstallation\Ant\bin\ant.bat -file build-jenkins.xml -Djenkins.result.dir=${JENKINS.WORKSPACES}/Results "-Dbranch=*/develop" -Djenkins.result.dir=C:/Tools/Jenkins/Results -Djenkins.workspace.dir=C:\Tools\Jenkins\Project-SNAPSHOT\workspace/PRO_56/PRO/java/Project -Dproject.path=C:\Tools\Jenkins\Project-SNAPSHOT\workspace clean.compile.jar.server.snapshot -v && exit %%ERRORLEVEL%%"
Usage: java [-options] class [args...]
           (to execute a class)
   or  java [-options] -jar jarfile [args...]
           (to execute a jar file)
where options include:
...
See http://www.oracle.com/technetwork/java/javase/documentation/index.html for more details.
Build step 'Invoke Ant' marked build as failure
Finished: FAILURE

I get no debug messages, nothing.
I've got other project with a similar/equal config which work. I think it could be a incompatibility of my plugins.

Has anyone experienced this bug before?


来源: stackexchange

问:
How to make Stream Of Objects from a Dynamic Source in Java?
I am trying to solve a problem, looks like its not possible with Java.

I have some code that calls a processObject(SomeObject someObject) and the method process it. I am trying to encapsulate this whole thing and want to get a stream of someObjects.

Below is my sample program:

```<code>import java.util.stream.Stream;

public class ProcessObject {

    public static void main(String[] args) {
        int i = 0;
        ProcessObject processObject = new ProcessObject();
        while (true) {
            processObject.processObject(new SomeObject("Hello " + i++));
        }
    }

    public void processObject(SomeObject someObject) {
        System.out.println(someObject);

    }
    //TODO
    public Stream<SomeObject> getStream(){
        //Producer here should wait and produce Objects as soon as
        //they become available like "processObject" method.
        return Stream.generate(() -> new SomeObject("Hello "));
    }
}

class SomeObject {
    public String name;

    public SomeObject(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }
}
</code>```

The static main method keeps on generating SomeObjects and call method processObject to process them and it prints them. So, all is good.

I want to create a stream of SomeObject so that instead of calling the method to process them, I will just use streams to process them, something like this:

public Stream getStream();

Now with Java 8 or Java 9, there are Streams available. But put the condition of IMMUTABLE characteristics from the sources they are being generated.

How to create a stream and then add elements to stream as soon as they become available like a true pipeline?

I thought to use a BlockingQueue and use it in Stream Generate method as Producer like blockingQueue.take() but it never compiles.

答:
The problem here is that you can't mutate a local variable i in the lambda expression, isn't it? Well, since a lambda is basically an anonymous inner class, you can just put i as a field of the inner class!

```<code>Stream<String> stream = Stream.generate(new Supplier<String>() {
    int i = 0;
    // if you have any other state you want to mutate, put it here as well!
    @Override
    public String get() {
        return "Hello" + i++;
    }
});
// prints Hello0 to Hello9!
System.out.println(stream.limit(10).collect(Collectors.toList()));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to solve a problem, looks like its not possible with Java.

I have some code that calls a processObject(SomeObject someObject) and the method process it. I am trying to encapsulate this whole thing and want to get a stream of someObjects.

Below is my sample program:

import java.util.stream.Stream;

public class ProcessObject {

    public static void main(String[] args) {
        int i = 0;
        ProcessObject processObject = new ProcessObject();
        while (true) {
            processObject.processObject(new SomeObject("Hello " + i++));
        }
    }

    public void processObject(SomeObject someObject) {
        System.out.println(someObject);

    }
    //TODO
    public Stream<SomeObject> getStream(){
        //Producer here should wait and produce Objects as soon as
        //they become available like "processObject" method.
        return Stream.generate(() -> new SomeObject("Hello "));
    }
}

class SomeObject {
    public String name;

    public SomeObject(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }
}

The static main method keeps on generating SomeObjects and call method processObject to process them and it prints them. So, all is good.

I want to create a stream of SomeObject so that instead of calling the method to process them, I will just use streams to process them, something like this:

public Stream getStream();

Now with Java 8 or Java 9, there are Streams available. But put the condition of IMMUTABLE characteristics from the sources they are being generated.

How to create a stream and then add elements to stream as soon as they become available like a true pipeline?

I thought to use a BlockingQueue and use it in Stream Generate method as Producer like blockingQueue.take() but it never compiles.

Body:
The problem here is that you can't mutate a local variable i in the lambda expression, isn't it? Well, since a lambda is basically an anonymous inner class, you can just put i as a field of the inner class!

Stream<String> stream = Stream.generate(new Supplier<String>() {
    int i = 0;
    // if you have any other state you want to mutate, put it here as well!
    @Override
    public String get() {
        return "Hello" + i++;
    }
});
// prints Hello0 to Hello9!
System.out.println(stream.limit(10).collect(Collectors.toList()));


问:
How to show ajax response into bootstrap modal
I want to pop up a modal which will show dynamic data comes from query. so when a user clicked related school will show into modal. I got the response but i'm not getting how can i show into that modal. any suggestion please?

Button:

```<code> <a href="#." data-toggle="modal" data-target="#myModal" data-id="{{$user->id}}"  class="chooseSchoolBtn">Choose School</a>
</code>```

Ajax :

```<code>$(".chooseSchoolBtn").on("click", function (argument) {
    //console.log($(this).data("id"))
    var user_id = $(this).data("id")
    var info = $.get("{{url('school-list')}}", {
        id: user_id
    });
    info.done(function (data) {
        console.log(data)
    });
});
</code>```

Modal:

```<code><div class="modal-body">
    // This section will come dynamically
    <div class="col-md-2 col-sm-4 col-xs-12">
        <div class="single_school">
            <div class="selection_area">
                <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
            </div>
            <div class="school_img_area" style="background-image: url(school/images/school/school1.jpg);">
            </div>
            <div class="school_info">
                <p class="school_name">School Name</p>
                <p class="school_description">Good School...</p>
                <p class="school_price">12$</p>
            </div>
        </div>
    </div>
    // dynamic section ends
</div>
</code>```

json response :

```<code>{
    id: 1,
    user_id: 2,
    price: "2340.00",
    name: "XYZ",
    display_image: "1510570005ajaPXajmik.png"
}, {
    id: 3,
    user_id: 2,
    price: "123.00",
    name: "ABC",
    display_image: "1510570049QZWiQUh7zY.jpg"
}
</code>```

答:
If you want to implement using JSON response than you will iterate through loop and append it html.

For ex -

```<code>var html="";
for(var i=0; i<data.length; i++) {
    var html +=<p>data.price</p>data.name<p>;
}
$('.appendTo').html(html);
</code>```

Other option is in your controller method instead of return the data as JSON you can return HTML and than replace the content when you get ajax success.

ContentLicense: CC BY-SA 4.0

Body:
I want to pop up a modal which will show dynamic data comes from query. so when a user clicked related school will show into modal. I got the response but i'm not getting how can i show into that modal. any suggestion please?

Button:

 id}}"  class="chooseSchoolBtn">Choose School

Ajax :

$(".chooseSchoolBtn").on("click", function (argument) {
    //console.log($(this).data("id"))
    var user_id = $(this).data("id")
    var info = $.get("{{url('school-list')}}", {
        id: user_id
    });
    info.done(function (data) {
        console.log(data)
    });
});

Modal:

    // This section will come dynamically

School Name

Good School...

12$

    // dynamic section ends

json response :

{
    id: 1,
    user_id: 2,
    price: "2340.00",
    name: "XYZ",
    display_image: "1510570005ajaPXajmik.png"
}, {
    id: 3,
    user_id: 2,
    price: "123.00",
    name: "ABC",
    display_image: "1510570049QZWiQUh7zY.jpg"
}

Body:
If you want to implement using JSON response than you will iterate through loop and append it html.

For ex -

var html="";
for(var i=0; i<data.length; i++) {
    var html +=<p>data.price</p>data.name<p>;
}
$('.appendTo').html(html);

Other option is in your controller method instead of return the data as JSON you can return HTML and than replace the content when you get ajax success.


问:
Error with dependance @types/geojson
I'm using react.js , with typescript and webpack configuration.

I've a problem with the dependency @types/geojson
When I compil my app , I have errors in my console

```<code>error TS1005 , expected
type parameter name cannot be any
</code>```

I have the version 1.0.6 of @types/geojon, and the version 0.0.5 of geojson.

My npm version is 3.10.8

Do you have an idea about this problem ?

Thank you

答: I found the solution, download the typescript version 2.3.0, and it would be work</p>

Title: Error with dependance @types/geojson

Body:
I'm using react.js , with typescript and webpack configuration.

I've a problem with the dependency @types/geojson
When I compil my app , I have errors in my console

error TS1005 , expected
type parameter name cannot be any

I have the version 1.0.6 of @types/geojon, and the version 0.0.5 of geojson.

My npm version is 3.10.8

Do you have an idea about this problem ?

Thank you


问:
How to store paging state in Cassandra c# driver?
I have read couple of links to implement manual paging using Cassandra c# driver.

Links referred:

Backward paging in cassandra c# driver

https://datastax.github.io/csharp-driver/features/paging/

My requirement:

I am trying to get list of all distinct partition keys form table which is too big in size.

Because of size Cassandra db is throwing error in between retrieving them or on the first execution of query. Now suppose it failed after fetching 100000 distinct partition keys I will use the Paging state provided by Cassandra c# driver.

Now I am saving the last available page state before failing to log file and use it again to continue from where it failed.

I am saving the paging state into log file using:

```<code>Encoding.ASCII.GetString(pagingState);
</code>```

And retrieving form log file using:

```<code>Encoding.ASCII.GetBytes(pagingState);
</code>```

But when I pass it to .SetPagingState(pagingState) and execute the query it throws exception like:

java.lang.IllegalStateException: Cannot call hasNext() until the
  previous iterator has been fully consumed

I compared byte by byte array bytes before saving into file and after retrieving them from file. Few values in byte array are different.
I tried with UIF8 encoding but no use.

NOTE: It works perfectly when I pass byte array without converting. I mean the below if condition code works perfectly.

```<code>if (pagingState != null)
{
     GenerateInitialLogs(pagingState);
}
</code>```

Full functions:

```<code>    private void BtnGetPrimaryKeys_Click(object sender, EventArgs e)
    {
        string fileContent = File.ReadAllText("D:/Logs/log.txt");
        if(fileContent.Length > 0)
        {
            GenerateInitialLogs(Encoding.ASCII.GetBytes(fileContent));
        }
        else
        {
            GenerateInitialLogs(null);
        }
    }

    private void Log(byte[] pagingState)
    {
        File.WriteAllText("D:/Logs/log.txt", Encoding.ASCII.GetString(pagingState));
    }

    private int GenerateInitialLogs(byte[] pagingState)
    {
        try
        {
            RowSet rowSet = BLL.SelectDistinctPrimaryKeys(pagingState);

            List<PrimaryKey> distinctPrimaryKeys = new List<PrimaryKey>();
            foreach (Row row in rowSet)
            {
                if (rowSet.PagingState != null) { pagingState = new byte[rowSet.PagingState.Length]; }
                pagingState = rowSet.PagingState;
            }
            Log(pagingState)

            if (pagingState != null)
            {
                GenerateInitialLogs(pagingState);
            }
        }
        catch(Exception ex)
        {
            throw ex;
        }
    }

    public static RowSet SelectDistinctPrimaryKeysFromTagReadings(byte[] pagingState)
    {
        try
        {
            // will execute on continuing after failing in between.
            if (pagingState != null)
            {
                PreparedStatement preparedStatement = BLL.currentSession.Prepare("SELECT DISTINCT \"Url\",\"Id\" FROM \"Readings\" ");
                BoundStatement boundStatement = preparedStatement.Bind();
                IStatement istatement = boundStatement.SetAutoPage(false).SetPageSize(1000).SetPagingState(pagingState);
                return BLL.currentSession.Execute(istatement);
            }
            else
            {
                PreparedStatement preparedStatement = BLL.currentSession.Prepare("SELECT DISTINCT \"Url\",\"Id\" FROM \"Readings\" ");
                BoundStatement boundStatement = preparedStatement.Bind();
                IStatement istatement = boundStatement.SetAutoPage(false).SetPageSize(1000);
                return BLL.currentSession.Execute(istatement);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
</code>```

答:
This solution is not figured out by me. It's done by Jorge Bay Gondra (employee of datastax).

Original answer:

https://groups.google.com/a/lists.datastax.com/forum/#!topic/csharp-driver-user/4XWTXZC-hyI

Solution:

Can't convert them into ASCII or UIF8 or any encoding because they don't represent text.

Use these functions to convert byte array into hexadecimal and vice versa.

```<code>public static string ByteArrayToHexaDecimalString(byte[] bytes)
{
     StringBuilder stringBuilder = new StringBuilder(bytes.Length * 2);
     foreach (byte b in bytes) { stringBuilder.AppendFormat("{0:x2}", b); }
     return stringBuilder.ToString();
}

public static byte[] HexaDecimalStringToByteArray(String hexaDecimalString)
{
     int NumberChars = hexaDecimalString.Length;
     byte[] bytes = new byte[NumberChars / 2];
     for (int i = 0; i < NumberChars; i += 2)
     {
         bytes[i / 2] = Convert.ToByte(hexaDecimalString.Substring(i, 2), 16);
     }
     return bytes;
}
</code>```

Body:
I have read couple of links to implement manual paging using Cassandra c# driver.

Links referred:

Backward paging in cassandra c# driver

https://datastax.github.io/csharp-driver/features/paging/

My requirement:

I am trying to get list of all distinct partition keys form table which is too big in size.

Because of size Cassandra db is throwing error in between retrieving them or on the first execution of query. Now suppose it failed after fetching 100000 distinct partition keys I will use the Paging state provided by Cassandra c# driver.

Now I am saving the last available page state before failing to log file and use it again to continue from where it failed.

I am saving the paging state into log file using:

Encoding.ASCII.GetString(pagingState);

And retrieving form log file using:

Encoding.ASCII.GetBytes(pagingState);

But when I pass it to .SetPagingState(pagingState) and execute the query it throws exception like:

java.lang.IllegalStateException: Cannot call hasNext() until the
  previous iterator has been fully consumed

I compared byte by byte array bytes before saving into file and after retrieving them from file. Few values in byte array are different.
I tried with UIF8 encoding but no use.

NOTE: It works perfectly when I pass byte array without converting. I mean the below if condition code works perfectly.

if (pagingState != null)
{
     GenerateInitialLogs(pagingState);
}

Full functions:

    private void BtnGetPrimaryKeys_Click(object sender, EventArgs e)
    {
        string fileContent = File.ReadAllText("D:/Logs/log.txt");
        if(fileContent.Length > 0)
        {
            GenerateInitialLogs(Encoding.ASCII.GetBytes(fileContent));
        }
        else
        {
            GenerateInitialLogs(null);
        }
    }

    private void Log(byte[] pagingState)
    {
        File.WriteAllText("D:/Logs/log.txt", Encoding.ASCII.GetString(pagingState));
    }

    private int GenerateInitialLogs(byte[] pagingState)
    {
        try
        {
            RowSet rowSet = BLL.SelectDistinctPrimaryKeys(pagingState);

            List<PrimaryKey> distinctPrimaryKeys = new List<PrimaryKey>();
            foreach (Row row in rowSet)
            {
                if (rowSet.PagingState != null) { pagingState = new byte[rowSet.PagingState.Length]; }
                pagingState = rowSet.PagingState;
            }
            Log(pagingState)

            if (pagingState != null)
            {
                GenerateInitialLogs(pagingState);
            }
        }
        catch(Exception ex)
        {
            throw ex;
        }
    }

    public static RowSet SelectDistinctPrimaryKeysFromTagReadings(byte[] pagingState)
    {
        try
        {
            // will execute on continuing after failing in between.
            if (pagingState != null)
            {
                PreparedStatement preparedStatement = BLL.currentSession.Prepare("SELECT DISTINCT \"Url\",\"Id\" FROM \"Readings\" ");
                BoundStatement boundStatement = preparedStatement.Bind();
                IStatement istatement = boundStatement.SetAutoPage(false).SetPageSize(1000).SetPagingState(pagingState);
                return BLL.currentSession.Execute(istatement);
            }
            else
            {
                PreparedStatement preparedStatement = BLL.currentSession.Prepare("SELECT DISTINCT \"Url\",\"Id\" FROM \"Readings\" ");
                BoundStatement boundStatement = preparedStatement.Bind();
                IStatement istatement = boundStatement.SetAutoPage(false).SetPageSize(1000);
                return BLL.currentSession.Execute(istatement);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

Body:
This solution is not figured out by me. It's done by Jorge Bay Gondra (employee of datastax).

Original answer:

https://groups.google.com/a/lists.datastax.com/forum/#!topic/csharp-driver-user/4XWTXZC-hyI

Solution:

Can't convert them into ASCII or UIF8 or any encoding because they don't represent text.

Use these functions to convert byte array into hexadecimal and vice versa.

public static string ByteArrayToHexaDecimalString(byte[] bytes)
{
     StringBuilder stringBuilder = new StringBuilder(bytes.Length * 2);
     foreach (byte b in bytes) { stringBuilder.AppendFormat("{0:x2}", b); }
     return stringBuilder.ToString();
}

public static byte[] HexaDecimalStringToByteArray(String hexaDecimalString)
{
     int NumberChars = hexaDecimalString.Length;
     byte[] bytes = new byte[NumberChars / 2];
     for (int i = 0; i < NumberChars; i += 2)
     {
         bytes[i / 2] = Convert.ToByte(hexaDecimalString.Substring(i, 2), 16);
     }
     return bytes;
}


问:
iPhone - UIImagePickerControllerDelegate inheritance
I have added a UIImagePickerController to a UIViewController. I have also assigned the UIImagePickerControllerDelegate to that UIViewController.

When I execute the following line,

```<code>myPicker.delegate = self;
</code>```

Xcode gifts me with the following message:

warning: assigning to
  id
  from incompatible type 'RootViewController'

Then I added the UINavigationControllerDelegate protocol to the same UIViewController and the error message vanished.

So, do I have to add both protocols to the UIViewController when I add a UIImagePickerController?

If the UIImagePickerController is a subclass of UINavigationController as stated in the docs, shouldn't this be automatic? Why do I have to add its parent's delegate protocol and not just the UIImagePickerControllerDelegate protocol?

Is this a bug or am I missing something?

答:
As you noted, UIImagePickerController inherits from UINavigationController. It uses the same delegate property though and doesn't declare a (hypothetical) "imagePickerDelegate" of its own, so your delegate has to conform to both protocols. It makes sense, because you're also assigning the same delegate to the UINavigationController part (that knows nothing about the image picker).

The API design is a bit questionable here in my opinion, but anyway, all methods in UINavigationControllerDelegate are optional, so it suffices to declare that you conform to the protocol and be done with it.

Body:
I have added a UIImagePickerController to a UIViewController. I have also assigned the UIImagePickerControllerDelegate to that UIViewController.

When I execute the following line,

myPicker.delegate = self;

Xcode gifts me with the following message:

warning: assigning to
  id
  from incompatible type 'RootViewController'

Then I added the UINavigationControllerDelegate protocol to the same UIViewController and the error message vanished.

So, do I have to add both protocols to the UIViewController when I add a UIImagePickerController?

If the UIImagePickerController is a subclass of UINavigationController as stated in the docs, shouldn't this be automatic? Why do I have to add its parent's delegate protocol and not just the UIImagePickerControllerDelegate protocol?

Is this a bug or am I missing something?


问:
Need correct if statement code for button that closes the searchView
I have a searchView in my app that when you click on the search icon it displays searchView and the <-- button closes searchView. The code for displaying the <-- button is...

```<code> actionBar.setDisplayHomeAsUpEnabled(true);
</code>```

What if statement would I need to code my <-- button so I can code what it does.

```<code>if(actionBar.setDisplayHomeAsUpEnabled(true)) {}
</code>```

The above code doesn't work. There is also no...

```<code>if(actionBar.onClick){}
</code>```

I'm looking for an if statement that says if that <-- button is clicked on, close the searchView.

```<code>if(onBackPressed){}  //doesn't work either
</code>```

答:
```<code> @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(android.R.id.home == item.getItemId()){
            //write your code here
        }
        return super.onOptionsItemSelected(item);
    }
</code>```

Body:
I have a searchView in my app that when you click on the search icon it displays searchView and the <-- button closes searchView. The code for displaying the <-- button is...

 actionBar.setDisplayHomeAsUpEnabled(true);

What if statement would I need to code my <-- button so I can code what it does.

if(actionBar.setDisplayHomeAsUpEnabled(true)) {}

The above code doesn't work. There is also no...

if(actionBar.onClick){}

I'm looking for an if statement that says if that <-- button is clicked on, close the searchView.

if(onBackPressed){}  //doesn't work either


问:
Android Studio Google Map Change Marker Color
I want to change the marker colors on my map depending on the color inside my database. There's no error so Idk what's wrong with my code. I think it's the for loop but Idk what's the correct logic here.

```<code>private void AllSpeciesLocation() {
    ArrayList<HashMap<String, String>> location = null;
    String url = "http://192.168.1.4/android_login_api/getLatLong.php";
    try {

        JSONArray data = new JSONArray(getHttpGet(url));

        location = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> map;

        for(int i = 0; i < data.length(); i++){
            JSONObject c = data.getJSONObject(i);
            search_species = c.getString("speciesid");
            map = new HashMap<String, String>();
            map.put("locationid", c.getString("locationid"));
            map.put("brgy", c.getString("brgy"));
            map.put("town", c.getString("town"));
            map.put("latitude", c.getString("latitude"));
            map.put("longitude", c.getString("longitude"));
            map.put("speciesid", c.getString("speciesid"));

            String url2 = "http://192.168.1.4/android_login_api/search_species_color.php?species_name=" + search_species;
            try {

                JSONArray data2 = new JSONArray(getHttpGet(url2));

                for(i = 0; i < data2.length(); i++){
                    JSONObject c2 = data.getJSONObject(i);
                    map.put("color", c2.getString("flowercolor"));
                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
            }

            location.add(map);
        }

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
</code>```

I don't have problems with my markers. Just the for loop. My logcat says there's no value for flowercolor. When I run it, nothing appears on my screen. Hope u can help me.

答:
Simply change data to  data2 in your second loop:

```<code>        String url2 = "http://192.168.1.4/android_login_api/search_species_color.php?species_name=" + search_species;
        try {

            JSONArray data2 = new JSONArray(getHttpGet(url2));

            for(i = 0; i < data2.length(); i++){
                JSONObject c2 = data2.getJSONObject(i); // This line..
                map.put("color", c2.getString("flowercolor"));
            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
        }
</code>```

Body:
I want to change the marker colors on my map depending on the color inside my database. There's no error so Idk what's wrong with my code. I think it's the for loop but Idk what's the correct logic here.

private void AllSpeciesLocation() {
    ArrayList<HashMap<String, String>> location = null;
    String url = "http://192.168.1.4/android_login_api/getLatLong.php";
    try {

        JSONArray data = new JSONArray(getHttpGet(url));

        location = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> map;

        for(int i = 0; i < data.length(); i++){
            JSONObject c = data.getJSONObject(i);
            search_species = c.getString("speciesid");
            map = new HashMap<String, String>();
            map.put("locationid", c.getString("locationid"));
            map.put("brgy", c.getString("brgy"));
            map.put("town", c.getString("town"));
            map.put("latitude", c.getString("latitude"));
            map.put("longitude", c.getString("longitude"));
            map.put("speciesid", c.getString("speciesid"));

            String url2 = "http://192.168.1.4/android_login_api/search_species_color.php?species_name=" + search_species;
            try {

                JSONArray data2 = new JSONArray(getHttpGet(url2));

                for(i = 0; i < data2.length(); i++){
                    JSONObject c2 = data.getJSONObject(i);
                    map.put("color", c2.getString("flowercolor"));
                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
            }

            location.add(map);
        }

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

I don't have problems with my markers. Just the for loop. My logcat says there's no value for flowercolor. When I run it, nothing appears on my screen. Hope u can help me.

Body:
Simply change data to  data2 in your second loop:

        String url2 = "http://192.168.1.4/android_login_api/search_species_color.php?species_name=" + search_species;
        try {

            JSONArray data2 = new JSONArray(getHttpGet(url2));

            for(i = 0; i < data2.length(); i++){
                JSONObject c2 = data2.getJSONObject(i); // This line..
                map.put("color", c2.getString("flowercolor"));
            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
        }


问:
How to copy one branch to other in Git
I have a branch with name A on which I have my running project. I have a friend who is working on branch B. Recently we did the major version changes in our source code, so the branch B is now up to date. I need to copy all the source code and files/folders to my branch so that branch A is sync with B and is also up to date. As I do not have much idea about git commands I simply thought of pulling the branch by using commands:

```<code>git checkout B
git pull origin B
</code>```

Now after these two commands, all the changes of B was in my branch A. But then when I switched back to my branch by using git checkout A, everything reverted back. All I want is to copy all the content of B to A.

答:
I suggest to do it in the following way.

```<code>git checkout B
git pull origin B
git checkout -b B_backup
git push origin B_backup

git checkout A
git pull origin A

git checkout B
git rebase -i A
</code>```

(solving conflicts, check if everything works)

```<code>git push origin B -f
</code>```

(this will overwrite branch B, be sure that there are no changes appeared there)

```<code>git push origin A:B
git checkout A
git pull origin A
</code>```

Title: How to copy one branch to other in Git

Body:
I have a branch with name A on which I have my running project. I have a friend who is working on branch B. Recently we did the major version changes in our source code, so the branch B is now up to date. I need to copy all the source code and files/folders to my branch so that branch A is sync with B and is also up to date. As I do not have much idea about git commands I simply thought of pulling the branch by using commands:

git checkout B
git pull origin B

Now after these two commands, all the changes of B was in my branch A. But then when I switched back to my branch by using git checkout A, everything reverted back. All I want is to copy all the content of B to A.

Body:
I suggest to do it in the following way.

git checkout B
git pull origin B
git checkout -b B_backup
git push origin B_backup

git checkout A
git pull origin A

git checkout B
git rebase -i A

(solving conflicts, check if everything works)

git push origin B -f

(this will overwrite branch B, be sure that there are no changes appeared there)

git push origin A:B
git checkout A
git pull origin A


问:
Kafka->S3->Oozie->Hadoop, Kafka writing to a S3 location, oozie read this folder every 15 mins and push the new files to hadoop
The above title describes the workflow and I want to validate the design here, plus discuss how to manage the updates coming to shared S3 folder.

As oozie is consumer of data, and kafka is producer of data here, how do I maintain which files have already been consumed and which files are yet to be consumed, given that the producer of data is continuously writing to the location.

Are there any atomicity features provided by Amazon-s3 to maintain this?

Update Note : Kafka cannot directly write to HDFS because of network connectivity constraints.

答:
You can use Oozie coordinator here. The oozie cordinator can poll continuously for new files and once a file has arrived, it can trigger a oozie workflow to copy copy the data. The file names/folders you can create based on the format ${baseFsURI}/${YEAR}/${MONTH}/${DAY}/${HOUR}/${MINUTE}. It will help oozie cordinator to identify the new files that has arrived.

More information is here : https://oozie.apache.org/docs/3.1.3-incubating/CoordinatorFunctionalSpec.html

To set up oozie cordinator to poll for s3 files use : https://community.cloudera.com/t5/Batch-Processing-and-Workflow/Getting-Oozie-Coordinator-datasets-working-with-S3-after-a-lost/td-p/27233


问:
Any SQL Server multiple-recordset stored procedure gotchas?

Context

My current project is a large-ish public site (2 million pageviews per day) site running a mixture of asp classic and asp.net with a SQL Server 2005 back-end. We're heavy on reads, with occasional writes and virtually no updates/deletes. Our pages typically concern a single 'master' object with a stack of dependent (detail) objects.

I like the idea of returning all the data required for a page in a single proc (and absolutely no unnecesary data). True, this requires a dedicated proc for such pages, but some pages receive double-digit percentages of our overall site traffic so it's worth the time/maintenance hit. We typically only consume multiple-recordsets from our .net code, using System.Data.SqlClient.SqlDataReader and it's NextResult method. Oh, yeah, I'm not doing any updates/inserts in these procs either (except to table variables).

The question

SQL Server (2005) procs which return multiple recordsets are working well (in prod) for us so far but I am a little worried that multi-recordset procs are my new favourite hammer that i'm hitting every problem (nail) with. Are there any multi-recordset sql server proc gotchas I should know about? Anything that's going to make me wish I hadn't used them? Specifically anything about it affecting connection pooling, memory utilization etc.

答:
I would recommend having invoking in one stored procedure several inner invocations of stored procedures that return 1 resultset each.

```<code>create proc foo
as
execute foobar --returns one result

execute barfoo --returns one result

execute bar  --returns one result
</code>```

That way when requirments change and you only need the 3rd and 5th result set, you have a easy way to invoke them without adding new stored procedures and regenerating your data access layer.  My current app returns all reference tables (e.g. US states table)  if I want them or not.  Worst is when you need to get a reference table and the only access is via a stored procedure that also runs an expensive query as one of its six resultsets.

OwnerDisplayName: Jaysen Marais

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Jaysen Marais

Body:
I would recommend having invoking in one stored procedure several inner invocations of stored procedures that return 1 resultset each.

create proc foo
as
execute foobar --returns one result

execute barfoo --returns one result

execute bar  --returns one result

That way when requirments change and you only need the 3rd and 5th result set, you have a easy way to invoke them without adding new stored procedures and regenerating your data access layer.  My current app returns all reference tables (e.g. US states table)  if I want them or not.  Worst is when you need to get a reference table and the only access is via a stored procedure that also runs an expensive query as one of its six resultsets.

OwnerDisplayName: MatthewMartin


问:
jQuery rotating banner
I'm looking for a jQuery rotating banner that I can use my own image thumbnails/layout for that I can just div tags instead of simple images.  I found this one: http://malsup.com/jquery/cycle/lite/ but it's a bit outdated</p>

答:
I just started using GalleryView from spaceforaname.com (http://spaceforaname.com/galleryview) and I like it a lot. It will allow you to use image or html content, automatic or manual transitions, and optional captioning.

Default/Basic example (you can turn off the caption overlay and just have the images or html content fill the space:

http://spaceforaname.com/gallery-light.html

Here is another example:

http://spaceforaname.com/webcomics.html

Title: jQuery rotating banner


问:
GIT not working with Eclipse SVN - all repositories
Since a few days ago, I have no access to GIT using Eclipse 3.8 and SVN 1.10

All was ok, but now I'm getting errors accessing ALL the GIT repositories!

RA layer request failed
  svn: Unable to connect to a repository at URL 'https://github.com/eclipse/birt'
  svn: Unexpected HTTP status 503 'Service Unavailable' on '/eclipse/birt'
  svn: Additional errors:
  svn: OPTIONS request on '/eclipse/birt' failed: 503 Service Unavailable

Any ideas? Thanks in advance.

UPDATE: This was a GIT PROBLEM... all is back to normal now... except https://github.com/eclipse/birt

答:
As far as I know svn and git are not same thing, but they are very similar, but I could be wrong. Use git functionality, because form your output I see, that you try to use svn with github

Cheers


问:
Update product price using a hook in WooCommerce
I am trying to update the product regular price using the meta key _regular_price with an integer or string when the product is updated in the wp-admin.

My desired user-flow is:

Open the product edit page

Click the update button

See that the _regular_price is set to 20 after the page has reloaded.

```<code>add_action( 'woocommerce_process_product_meta', 'update_test' );
function update_test( $post_id ) {
    update_post_meta( $post_id, '_regular_price', 20 );
}
</code>```

Please help me find what I'm doing wrong in the above function and let me know of any other ways to accomplish this.

答:
Updated (August 2018)

Your code is correct but the hook is made for Metaboxes custom fields.

You should use instead save_post_{$post->post_type} Wordpress hook targeting product post type only.

Also You may need to update the active price and to refresh the product transient cache with the function wc_delete_product_transients().

So your code will be:

```<code>add_action( 'save_post', 'update_the_product_price', 10, 3 );
function update_the_product_price( $post_id, $post, $update ) {

    if ( $post->post_type != 'product') return; // Only products

    // If this is an autosave, our form has not been submitted, so we don't want to do anything.
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
        return $post_id;

    // Check the user's permissions.
    if ( ! current_user_can( 'edit_product', $post_id ) )
        return $post_id;

    $price = 50; // <===  <===  <===  <===  <===  <=== Set your price

    $product = wc_get_product( $post_id ); // The WC_Product object

    // if product is not on sale
    if( ! $product->is_on_sale() ){
        update_post_meta( $post_id, '_price', $price ); // Update active price
    }
    update_post_meta( $post_id, '_regular_price', $price ); // Update regular price
    wc_delete_product_transients( $post_id ); // Update product cache
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works…

Body:
I am trying to update the product regular price using the meta key _regular_price with an integer or string when the product is updated in the wp-admin.

My desired user-flow is:

Open the product edit page

Click the update button

See that the _regular_price is set to 20 after the page has reloaded.

add_action( 'woocommerce_process_product_meta', 'update_test' );
function update_test( $post_id ) {
    update_post_meta( $post_id, '_regular_price', 20 );
}

Please help me find what I'm doing wrong in the above function and let me know of any other ways to accomplish this.

Body:
Updated (August 2018)

Your code is correct but the hook is made for Metaboxes custom fields.

You should use instead save_post_{$post->post_type} Wordpress hook targeting product post type only.

Also You may need to update the active price and to refresh the product transient cache with the function wc_delete_product_transients().

So your code will be:

add_action( 'save_post', 'update_the_product_price', 10, 3 );
function update_the_product_price( $post_id, $post, $update ) {

    if ( $post->post_type != 'product') return; // Only products

    // If this is an autosave, our form has not been submitted, so we don't want to do anything.
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
        return $post_id;

    // Check the user's permissions.
    if ( ! current_user_can( 'edit_product', $post_id ) )
        return $post_id;

    $price = 50; // <===  <===  <===  <===  <===  <=== Set your price

    $product = wc_get_product( $post_id ); // The WC_Product object

    // if product is not on sale
    if( ! $product->is_on_sale() ){
        update_post_meta( $post_id, '_price', $price ); // Update active price
    }
    update_post_meta( $post_id, '_regular_price', $price ); // Update regular price
    wc_delete_product_transients( $post_id ); // Update product cache
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works…


问:
Firebase user data storage issue
I am working with Firebase Authentication and while coding I realised that I can use User user = FirebaseAuth.getInstance().getCurrentUser; to fetch user data in any activity through out the application if user successfully logged in but I am confused that whether I can store user data in sharedPreferences after user login or I can use User user = FirebaseAuth.getInstance().getCurrentUser; way to get user data in whichever activity I want to. So which method is preferable to use firebase user data. And if there any other method you have to suggest then you are always welcome. Thanks in advance.

答: I would use an AuthStateListener to listen to possible changes to the authenticated user, and persist changes to that user object only when they might change, according to that listener.  It's probably not worthwhile to continually ping currentUser for changes when you know it can only change when response to the listener callback.</p>

Title: Firebase user data storage issue


问:
White spaces and oledb
I'm reading an excel file using OleDb on ASP. NET (C#).
All the information is returned ok and I was surprised to see that even the cell type defined on the Excel file is returned to my code.
The problem is that I have column where all the cells "general" types and since the values are only numbers Excel assumes it to be Number.
If there are no spaces olebd driver returns the right value to my code but if there are space it returns ""...

Here's how I'm getting the information:

```<code>OleDbConnection oleDbConn = new OleDbConnection(connString);
oleDbConn.Open();
OleDbCommand oleDbComm = new OleDbCommand("SELECT * FROM [Sheet1$]", oleDbConn);
OleDbDataAdapter oleDbDtAdapter = new OleDbDataAdapter();
oleDbDtAdapter.SelectCommand = oleDbComm;

DataSet dtSet = new DataSet();
oleDbDtAdapter.Fill(dtSet, "SMSs");
Object testZeroZero = dtSet.Tables[0].Rows[0][0];
</code>```

I can't go to the Excel and change the cell type to "text" because the end user must not worry on changing this so how can I overcome this?

Regards!

答:
Have you considered your connection string?

"IMEX=1;" tells the driver to always
  read "intermixed" (numbers, dates,
  strings etc) data columns as text.
  Note that this option might affect
  excel sheet write access negative.

-- http://www.connectionstrings.com/excel

Title: White spaces and oledb

Body:
I'm reading an excel file using OleDb on ASP. NET (C#).
All the information is returned ok and I was surprised to see that even the cell type defined on the Excel file is returned to my code.
The problem is that I have column where all the cells "general" types and since the values are only numbers Excel assumes it to be Number.
If there are no spaces olebd driver returns the right value to my code but if there are space it returns ""...

Here's how I'm getting the information:

OleDbConnection oleDbConn = new OleDbConnection(connString);
oleDbConn.Open();
OleDbCommand oleDbComm = new OleDbCommand("SELECT * FROM [Sheet1$]", oleDbConn);
OleDbDataAdapter oleDbDtAdapter = new OleDbDataAdapter();
oleDbDtAdapter.SelectCommand = oleDbComm;

DataSet dtSet = new DataSet();
oleDbDtAdapter.Fill(dtSet, "SMSs");
Object testZeroZero = dtSet.Tables[0].Rows[0][0];

I can't go to the Excel and change the cell type to "text" because the end user must not worry on changing this so how can I overcome this?

Regards!


问:
FB.AppRequest does not work
I am trying to send App Requests with Facebook SDK on Unity. Everything is alright until I press 'send'. It also returns a success but nothing happens in my friends' facebook :S

```<code>    FB.AppRequest(message, null, null, null, null, null, title,
        (result) => {
            Debug.Log(result.RawResult);
        }
    );
</code>```

As you can see, I am able to show the friends list and select the ones who will receive the request. After pressing send, it returns a success(I have put the Xs intentionally). However, nothing happens on my friend's facebook.

```<code>{"to":"10XXXXXXXXXXXXXX33","request":"161XXXXXXXXXXXXXX89","callback_id":"4"}
</code>```

答: I have assigned my friend receiving the request as administrator so that he was able to get the notification. Otherwise, he does not get anything because the facebook app is currently in development mode.</p>

Title: FB.AppRequest does not work

Body:
I am trying to send App Requests with Facebook SDK on Unity. Everything is alright until I press 'send'. It also returns a success but nothing happens in my friends' facebook :S

    FB.AppRequest(message, null, null, null, null, null, title,
        (result) => {
            Debug.Log(result.RawResult);
        }
    );

As you can see, I am able to show the friends list and select the ones who will receive the request. After pressing send, it returns a success(I have put the Xs intentionally). However, nothing happens on my friend's facebook.

{"to":"10XXXXXXXXXXXXXX33","request":"161XXXXXXXXXXXXXX89","callback_id":"4"}


问:
Exception when split big XML file in small chunks with VTD-XML
I am developing a small program that divides a very big XML file (more than 2Gb) in little chunks.

After a research of many libraries, I chose VTD-XML (using VTDGenHuge for big files) and I started developing a little code test. But I am getting an issue when I read the segment bytes of the file.

I get offset and lenght with:

```<code>            long [] l = vn.getElementFragment();
</code>```

Then I get the information of result:

```<code>            int offset = (int) (l[0] >> 64);
            int len = new Integer("" + l[1]);
</code>```

Finally I try to extract the segment of bytes to write it in another file:

```<code>            b = new byte[len];
            fis.read(b, offset, len); **//<===== this is the exception problem**
</code>```

But I am getting java.lang.IndexOutOfBoundsException

Also, when I assign a fixed number to the array of bytes (new byte[400] for example], the program ends OK, but the output file is corrupted.

My code:

```<code>    File fo = new File("\\path\\post_people.xml");
    FileOutputStream fos = new FileOutputStream(fo);

    int count = 0;

    File f = new File("\\path\\people.xml");
    FileInputStream fis = new FileInputStream(f);
    byte[] b;

    VTDGenHuge vg = new VTDGenHuge();
    if (vg.parseFile("\\path\\people.xml", false, VTDGenHuge.MEM_MAPPED)){

        VTDNavHuge vn = vg.getNav();

        AutoPilotHuge ap = new AutoPilotHuge();
        ap.bind(vn);
        ap.selectXPath("/people/person"); //here it could be posible add another condition

        while (ap.evalXPath() != -1) {
            long [] l = vn.getElementFragment();
            int offset = (int) (l[0] >> 64);
            int len = new Integer("" + l[1]);
            b = new byte[len];
            fis.read(b, offset, len); //<===== this is the line problem

            fos.write(b); // writing the fragment out into other file

            count++;

            if (count == 3) { //this is just a test
                break;
            }

        }

    }
</code>```

A sample of XML file:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<people>
    <person>
        <name>Nombre 0</name>
        <lastName>ApPaterno 1</lastName>
        <birthdate>2017-11-10T10:20:44.926-05:00</birthdate>
        <age>0</age>
        <address>
            <streetType>Tipo Calle 0</streetType>
            <streetName>Nombre de Calle 0</streetName>
            <number>0</number>
        </address>
    </person>
    <person>
        <name>Nombre 1</name>
        <lastName>ApPaterno 1</lastName>
        <birthdate>2017-11-10T10:20:44.926-05:00</birthdate>
        <age>1</age>
        <address>
            <streetType>Tipo Calle 1</streetType>
            <streetName>Nombre de Calle 1</streetName>
            <number>1</number>
        </address>
    </person>
</people>
</code>```

Please, can you help me, guys?

UPDATE and SOLUTION:

Finally, the fragment code that I should modify was the following:

```<code>long [] l = vn.getElementFragment();
int offset = (int) (l[0] >> 64);
int len = new Integer("" + l[1]);
b = new byte[len];

fis.getChannel().position(0); //must return to position 0
fis.skip(offset); //must move to offset position
fis.read(b, 0, len);
</code>```

答:
As you've pointed out the main issue in your code is within the read of the inputstream:

```<code>int offset = (int) (l[0] >> 64);
int len = new Integer("" + l[1]);
b = new byte[len];
fis.read(b, offset, len);
</code>```

According to InputStream.read()'s JavaDoc:

The first byte read is stored into element b[off], the next one into b[off+1], and so on.

This means that your actual buffer either has to be of lenght offset + len, which leave the bytes 0 to offset as 0, or you skip the first offset bytes of the input stream and read len bytes into the buffer by filling the buffer from position 0 onwards.

If you replace the above code with

```<code>int offset = (int) (l[0] >> 64);
int len = new Integer("" + l[1]);
b = new byte[len];
fis.skip(offset);
fis.read(b, 0, len);
</code>```

the buffer should fill with the bytes of the actual String representation of

```<code><person>
    <name>Nombre 0</name>
    <lastName>ApPaterno 1</lastName>
    <birthdate>2017-11-10T10:20:44.926-05:00</birthdate>
    <age>0</age>
    <address>
        <streetType>Tipo Calle 0</streetType>
        <streetName>Nombre de Calle 0</streetName>
        <number>0</number>
    </address>
</person>
</code>```

Body:
I am developing a small program that divides a very big XML file (more than 2Gb) in little chunks.

After a research of many libraries, I chose VTD-XML (using VTDGenHuge for big files) and I started developing a little code test. But I am getting an issue when I read the segment bytes of the file.

I get offset and lenght with:

            long [] l = vn.getElementFragment();

Then I get the information of result:

            int offset = (int) (l[0] >> 64);
            int len = new Integer("" + l[1]);

Finally I try to extract the segment of bytes to write it in another file:

            b = new byte[len];
            fis.read(b, offset, len); **//<===== this is the exception problem**

But I am getting java.lang.IndexOutOfBoundsException

Also, when I assign a fixed number to the array of bytes (new byte[400] for example], the program ends OK, but the output file is corrupted.

My code:

    File fo = new File("\\path\\post_people.xml");
    FileOutputStream fos = new FileOutputStream(fo);

    int count = 0;

    File f = new File("\\path\\people.xml");
    FileInputStream fis = new FileInputStream(f);
    byte[] b;

    VTDGenHuge vg = new VTDGenHuge();
    if (vg.parseFile("\\path\\people.xml", false, VTDGenHuge.MEM_MAPPED)){

        VTDNavHuge vn = vg.getNav();

        AutoPilotHuge ap = new AutoPilotHuge();
        ap.bind(vn);
        ap.selectXPath("/people/person"); //here it could be posible add another condition

        while (ap.evalXPath() != -1) {
            long [] l = vn.getElementFragment();
            int offset = (int) (l[0] >> 64);
            int len = new Integer("" + l[1]);
            b = new byte[len];
            fis.read(b, offset, len); //<===== this is the line problem

            fos.write(b); // writing the fragment out into other file

            count++;

            if (count == 3) { //this is just a test
                break;
            }

        }

    }

A sample of XML file:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<people>
    <person>
        <name>Nombre 0</name>
        <lastName>ApPaterno 1</lastName>
        <birthdate>2017-11-10T10:20:44.926-05:00</birthdate>
        <age>0</age>
        <address>
            <streetType>Tipo Calle 0</streetType>
            <streetName>Nombre de Calle 0</streetName>
            <number>0</number>
        </address>
    </person>
    <person>
        <name>Nombre 1</name>
        <lastName>ApPaterno 1</lastName>
        <birthdate>2017-11-10T10:20:44.926-05:00</birthdate>
        <age>1</age>
        <address>
            <streetType>Tipo Calle 1</streetType>
            <streetName>Nombre de Calle 1</streetName>
            <number>1</number>
        </address>
    </person>
</people>

Please, can you help me, guys?

UPDATE and SOLUTION:

Finally, the fragment code that I should modify was the following:

long [] l = vn.getElementFragment();
int offset = (int) (l[0] >> 64);
int len = new Integer("" + l[1]);
b = new byte[len];

fis.getChannel().position(0); //must return to position 0
fis.skip(offset); //must move to offset position
fis.read(b, 0, len);

Body:
As you've pointed out the main issue in your code is within the read of the inputstream:

int offset = (int) (l[0] >> 64);
int len = new Integer("" + l[1]);
b = new byte[len];
fis.read(b, offset, len);

According to InputStream.read()'s JavaDoc:

The first byte read is stored into element b[off], the next one into b[off+1], and so on.

This means that your actual buffer either has to be of lenght offset + len, which leave the bytes 0 to offset as 0, or you skip the first offset bytes of the input stream and read len bytes into the buffer by filling the buffer from position 0 onwards.

If you replace the above code with

int offset = (int) (l[0] >> 64);
int len = new Integer("" + l[1]);
b = new byte[len];
fis.skip(offset);
fis.read(b, 0, len);

the buffer should fill with the bytes of the actual String representation of

<person>
    <name>Nombre 0</name>
    <lastName>ApPaterno 1</lastName>
    <birthdate>2017-11-10T10:20:44.926-05:00</birthdate>
    <age>0</age>
    <address>
        <streetType>Tipo Calle 0</streetType>
        <streetName>Nombre de Calle 0</streetName>
        <number>0</number>
    </address>
</person>


问:
Compare only time from datetime in entity framework 6 with odp.net Oracle 12c
I am using entity framework 6 with oracle and Sql. Timespan datatype is not working with oracle. so i changed datatype to datetime. now i want to compare only time in datetime with Linq query. ex.

```<code>var db0010016 = _idb0010016Rep.GetAll().Where(e => e.ExecutionTime.TimeOfDay == viewmodel.ExecutionTime).FirstOrDefault();
</code>```

in above example e.ExecutionTime is datetime  and viewmodel.ExecutionTime is timespan. i am using timeofday function to convert it to timespan

above query failed to execute so i used DbFunctions.CreateTime() function

```<code>var db0010016 = _idb0010016Rep.FindBy(e => DbFunctions.CreateTime(e.ExecutionTime.Hour, e.ExecutionTime.Minute, e.ExecutionTime.Second) == exetime).FirstOrDefault();
</code>```

above ex exetime is timespan.still i am getting below error

```<code>{"Invalid parameter binding\r\nParameter name: ParameterName"}
</code>```

答:
Because of the date- and time-problems with oracle, we do it string-only:

```<code>using(MyDbContext ctx = new MyDbContext())
{
    TimeSpan myTime = new TimeSpan(12, 00, 00);
    string myTimeString = myTime.ToString("hh':'mm':'ss");
    List<ExecutionObjects> tmp = ctx.ExecutionObjects.Where(a => a.ExecutionTime.EndsWith(myTimeString)).ToList();

    // Access field in source with seperated DateTime-property.
    tmp.ForEach(e => Console.WriteLine(e.ExecutionTimeDateTime.ToShortDateString()));
}
</code>```

In the source you can add an DateTime-parsing-property:

```<code>public class ExecutionObject
{
    [Column("ColExecutionTime")]
    public string ExecutionTime { get; set; }
    [NotMapped]
    public DateTime ExecutionTimeDateTime {
        get
        {
            return DateTime.ParseExact(this.ExecutionTime, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
        }
        set
        {
            this.ExecutionTime = value.ToString("yyyy-MM-dd HH:mm:ss");
        }
    }
}
</code>```

Not the most beautiful version, but working.

This is an Oracle-based problem in the DbFunctions. If you activate the sql-log you'll see that a function "CREATETIME()" is used, which is unknown.

Activate sql-log:
ctx.Database.Log = Console.WriteLine;

The log will look like this:

```<code>SELECT *
  FROM "ExecutionTimes" "Extent1"
 WHERE ((((CREATETIME (EXTRACT (HOUR FROM (CAST (
[...]
</code>```

Body:
I am using entity framework 6 with oracle and Sql. Timespan datatype is not working with oracle. so i changed datatype to datetime. now i want to compare only time in datetime with Linq query. ex.

var db0010016 = _idb0010016Rep.GetAll().Where(e => e.ExecutionTime.TimeOfDay == viewmodel.ExecutionTime).FirstOrDefault();

in above example e.ExecutionTime is datetime  and viewmodel.ExecutionTime is timespan. i am using timeofday function to convert it to timespan

above query failed to execute so i used DbFunctions.CreateTime() function

var db0010016 = _idb0010016Rep.FindBy(e => DbFunctions.CreateTime(e.ExecutionTime.Hour, e.ExecutionTime.Minute, e.ExecutionTime.Second) == exetime).FirstOrDefault();

above ex exetime is timespan.still i am getting below error

{"Invalid parameter binding\r\nParameter name: ParameterName"}

Body:
Because of the date- and time-problems with oracle, we do it string-only:

using(MyDbContext ctx = new MyDbContext())
{
    TimeSpan myTime = new TimeSpan(12, 00, 00);
    string myTimeString = myTime.ToString("hh':'mm':'ss");
    List<ExecutionObjects> tmp = ctx.ExecutionObjects.Where(a => a.ExecutionTime.EndsWith(myTimeString)).ToList();

    // Access field in source with seperated DateTime-property.
    tmp.ForEach(e => Console.WriteLine(e.ExecutionTimeDateTime.ToShortDateString()));
}

In the source you can add an DateTime-parsing-property:

public class ExecutionObject
{
    [Column("ColExecutionTime")]
    public string ExecutionTime { get; set; }
    [NotMapped]
    public DateTime ExecutionTimeDateTime {
        get
        {
            return DateTime.ParseExact(this.ExecutionTime, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
        }
        set
        {
            this.ExecutionTime = value.ToString("yyyy-MM-dd HH:mm:ss");
        }
    }
}

Not the most beautiful version, but working.

This is an Oracle-based problem in the DbFunctions. If you activate the sql-log you'll see that a function "CREATETIME()" is used, which is unknown.

Activate sql-log:
ctx.Database.Log = Console.WriteLine;

The log will look like this:

SELECT *
  FROM "ExecutionTimes" "Extent1"
 WHERE ((((CREATETIME (EXTRACT (HOUR FROM (CAST (
[...]


问:
Wordpress Rewrite URL with params
I have the following url and I'm using the type parameter in a WP_Query to generate a list of posts.

http://wordpress.dev/en-ie/category-holiday-deals/?type=city-breaks

I want to rewrite the url so it looks like this:

http://wordpress.dev/en-ie/holiday-deals/city-breaks

but I want to be able to use the type param still.

I have the following that's capturing the query vars:

```<code>add_filter('query_vars', 'sd_query_vars', 10, 1);

function sd_query_vars($vars) {
    $vars[] = 'type';
    $vars[] = 'destination';
    return $vars;
}
</code>```

but I can't figure out how to rewrite the URL.

Any suggestions?

答:
Whenever I've had to handle redirects with WordPress, I have used a plug-in like Rewrite. It gives you a nice interface to create rewrite rules.

I've found it's a lot easier than fiddling with the .htaccess file directly.

Title: Wordpress Rewrite URL with params

Body:
I have the following url and I'm using the type parameter in a WP_Query to generate a list of posts.

http://wordpress.dev/en-ie/category-holiday-deals/?type=city-breaks

I want to rewrite the url so it looks like this:

http://wordpress.dev/en-ie/holiday-deals/city-breaks

but I want to be able to use the type param still.

I have the following that's capturing the query vars:

add_filter('query_vars', 'sd_query_vars', 10, 1);

function sd_query_vars($vars) {
    $vars[] = 'type';
    $vars[] = 'destination';
    return $vars;
}

but I can't figure out how to rewrite the URL.

Any suggestions?


问:
database datatype performance: int or string
I'm storing phone country codes. They range from 1 to about 300. What's going to be more performant for datatype: int or string? I'm using SQL server 2008 and linq-to-sql.

Thanks.

答: my rule of thumb has always been.. do I need an average?  For example, you can store a zip code as integer, but are you ever going to need the average zip code?  Probably not.  As such, store as char.. unless you may need more than 5 characters, in which case store as varchar.</p>


问:
Create a html file and upload it to some server with Node.js
I have a sample HTML content string:

```<code>const HTMLTEMPLATE = `
  <!DOCTYPE html>
  <html>
    <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="format-detection" content="telephone=no">
    <link rel="icon" type="image/png" href="/static-for-dev/favicon.png">
    </head>
    <body>
      <div>Test</div>
    </body>
  </html>
`;
</code>```

I use this string to generate a HTML file with fs.writeFile() method:

```<code>fs.writeFile('sample.html', HTMLTEMPLATE, (err) => {
  if (err) {
    throw err;
  }
  console.log('The file has been saved!');
});
</code>```

My question is, Is there some way that I can retrieve the file after fs.writeFile() complete and upload it to some other server (maybe some cloud storage server) with Node.js?

答:
Install the scp module and include it in your code like this,

```<code>var scp = require('scp');
</code>```

To read the sample.html that you have created and to upload it to the server, you can try the following,

```<code>var options = {
  file: 'sample.html',
  user: 'username',
  host: 'myServer',
  port: '22',
  path: '~'
}

fs.readdir('./uploads', function(err, files) {
    var fileExists = true;
        files.forEach(function(file) {
        if(file=="sample.html") {
            scp.send(options, function (err) {
                if (err)
                    console.log(err);
                else
                    console.log('File transferred.');
            });
        }
    });
});
</code>```

Hope this helps!

Body:
I have a sample HTML content string:

const HTMLTEMPLATE = `
  <!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="format-detection" content="telephone=no">
    <link rel="icon" type="image/png" href="/static-for-dev/favicon.png">

Test

`;

I use this string to generate a HTML file with fs.writeFile() method:

fs.writeFile('sample.html', HTMLTEMPLATE, (err) => {
  if (err) {
    throw err;
  }
  console.log('The file has been saved!');
});

My question is, Is there some way that I can retrieve the file after fs.writeFile() complete and upload it to some other server (maybe some cloud storage server) with Node.js?

Body:
Install the scp module and include it in your code like this,

var scp = require('scp');

To read the sample.html that you have created and to upload it to the server, you can try the following,

var options = {
  file: 'sample.html',
  user: 'username',
  host: 'myServer',
  port: '22',
  path: '~'
}

fs.readdir('./uploads', function(err, files) {
    var fileExists = true;
        files.forEach(function(file) {
        if(file=="sample.html") {
            scp.send(options, function (err) {
                if (err)
                    console.log(err);
                else
                    console.log('File transferred.');
            });
        }
    });
});

Hope this helps!


问:
can I import two python classes like this?
I have two the python classes.  I wonder if I can do something like

file A

```<code># file A.py
from B import B
class A(){
    def Foo():
        pass

}
</code>```

file B

```<code># file B.py
from A import A
class B(){
    def Bar():
        pass

}
</code>```

答:
Yes you can, however, you might be better advised to use different names for the files and the classes they contain.

Please note that the use of {} is not a python construct to mark scope boundaries

file a.py

```<code># file a.py
from b import B
class A()
    def Foo():
        pass
</code>```

file b.py

```<code># file b.py
from a import A
class B()
    def Bar():
        pass
</code>```

This type of circular import will work, but there are better ways, notably placing imports in an __init__.py file

Body:
I have two the python classes.  I wonder if I can do something like

file A

# file A.py
from B import B
class A(){
    def Foo():
        pass

}

file B

# file B.py
from A import A
class B(){
    def Bar():
        pass

}

Body:
Yes you can, however, you might be better advised to use different names for the files and the classes they contain.

Please note that the use of {} is not a python construct to mark scope boundaries

file a.py

# file a.py
from b import B
class A()
    def Foo():
        pass

file b.py

# file b.py
from a import A
class B()
    def Bar():
        pass

This type of circular import will work, but there are better ways, notably placing imports in an __init__.py file


问:
how to make single array using all index value?
```<code>Array
(
    [8] => Array
        (
            [9] => Array
                (
                    [13] => Array()
            )
    )

[14] => Array
    (
        [15] => Array()
    )
)
</code>```

I want all index value in single array like this one array('8','9','13','14','15');

答:
You could combine the array_keys() function with recursion to grab all keys inside your array like shown below:</p>

```<code>// Your given array
$array = [
    8 => [
        9 => [
            13 => []
        ]
    ],

    14 => [
        15 => []
    ]
];

// What this function does, is it loops through the array, and if the given
// value is an array too, it does the same until it hits a value which is not an array
function array_keys_recursive($array, $keys = []) {
    foreach ($array as $key => $value) {
        $keys[] = $key;

        if (is_array($value)) {
            $keys = array_merge($keys, array_keys_recursive($value));
        }
    }

    return $keys;
}

// You call it like a so:
$keys = array_keys_recursive($array);
print_r($keys); // Outputs Array ( [0] => 8 [1] => 9 [2] => 13 [3] => 14  [4] => 15 )
</code>```

Body:
Array
(
    [8] => Array
        (
            [9] => Array
                (
                    [13] => Array()
            )
    )

[14] => Array
    (
        [15] => Array()
    )
)

I want all index value in single array like this one array('8','9','13','14','15');

Body:
You could combine the array_keys() function with recursion to grab all keys inside your array like shown below:

// Your given array
$array = [
    8 => [
        9 => [
            13 => []
        ]
    ],

    14 => [
        15 => []
    ]
];

// What this function does, is it loops through the array, and if the given
// value is an array too, it does the same until it hits a value which is not an array
function array_keys_recursive($array, $keys = []) {
    foreach ($array as $key => $value) {
        $keys[] = $key;

        if (is_array($value)) {
            $keys = array_merge($keys, array_keys_recursive($value));
        }
    }

    return $keys;
}

// You call it like a so:
$keys = array_keys_recursive($array);
print_r($keys); // Outputs Array ( [0] => 8 [1] => 9 [2] => 13 [3] => 14  [4] => 15 )


问:
Debugging Jquery ajax function
JS code:

```<code>$.ajax({

        type: 'POST',
         url: 'http://localhost/MyServiceDir/Service.asmx/Foo',
         contentType: 'application/json; charset=utf-8',
         data: jsonData,
         success: function (msg) {
             alert("good");
         },
         error: function (xhr, status) {
              switch (status) {
                 case 404:
                     alert('File not found');
                     break;
                 case 500:
                     alert('Server error');
                     break;
                 case 0:
                     alert('Request aborted');
                     break;
                 default:
                     alert('Unknown error ' + status);
             }
         }
     });
</code>```

I get "unknown error error". How do I get to the bottom of this? I would like to know what the error actually is. Thanks!

答: Check xhr.status.

Title: Debugging Jquery ajax function

Body:
JS code:

$.ajax({

        type: 'POST',
         url: 'http://localhost/MyServiceDir/Service.asmx/Foo',
         contentType: 'application/json; charset=utf-8',
         data: jsonData,
         success: function (msg) {
             alert("good");
         },
         error: function (xhr, status) {
              switch (status) {
                 case 404:
                     alert('File not found');
                     break;
                 case 500:
                     alert('Server error');
                     break;
                 case 0:
                     alert('Request aborted');
                     break;
                 default:
                     alert('Unknown error ' + status);
             }
         }
     });

I get "unknown error error". How do I get to the bottom of this? I would like to know what the error actually is. Thanks!

Body: Check xhr.status.


问:
Creating dynamic table using AngularJS and restful api
I'm trying to create a table using Quandl restful api along with AngularJS. While table headers created well table rows aren't filled with data at all, there are only empty rows.

Here is my controller:

```<code>angular.module('stockControllers', [])
.controller('stockController', function($scope, $http){
  var results = {};
  $http.get('https://www.quandl.com/api/v3/datasets/WIKI/FB.json?start_date=2017-11-01&api_key=3pg7TVEyogz6D6FXhf5g').
  then(function(response) {
      $scope.resulting = response.data;
      console.log($scope.resulting);
 });
});
</code>```

HTML code:

```<code><div ng-controller="stockController">

<div class='page-header'>
<h1> {{resulting.dataset.name}} </h1>
<p> Note: showing only OHLC data </p>
</div>

<table class="table table-striped">
    <tr>
        <th>{{resulting.dataset.column_names[0]}}</th>
        <th>{{resulting.dataset.column_names[1]}}</th>
        <th>{{resulting.dataset.column_names[2]}}</th>
    <th>{{resulting.dataset.column_names[3]}}</th>
    <th>{{resulting.dataset.column_names[4]}}</th>
</tr>
<tr ng-repeat="row in resulting.dataset.data">
    <td>{{resulting.dataset.data[row][0]}}</td>
    <td>{{resulting.dataset.data[row][1]}}</td>
    <td>{{resulting.dataset.data[row][2]}}</td>
    <td>{{resulting.dataset.data[row][3]}}</td>
    <td>{{resulting.dataset.data[row][4]}}</td>
</tr>
</table>

</div>
</code>```

And api response fragment which I want to use:

```<code>"dataset": {
"column_names": ["Date","Open","High","Low","Close","Volume","Ex-Dividend","Split Ratio","Adj. Open","Adj. High","Adj. Low","Adj. Close","Adj. Volume"],
"data": [["2017-11-13",
 177.5,
 179.04,
 177.3,
 178.77,
 9431449,
 0,
 1,
 177.5,
 179.04,
 177.3,
 178.77,
 9431449 ],,
[
 "2017-11-10",
 178.35,
 179.0999,
 177.96,
 178.46,
 10933405,
 0,
 1,
 178.35,
 179.0999,
 177.96,
 178.46,
 10933405 ],,
</code>```

答:
angular.module('app', []).controller('ctrl', function($scope) {
  $scope.resulting = {
    dataset: {
      column_names: ["Date", "Open", "High", "Low", "Close", "Volume", "Ex-Dividend", "Split Ratio", "Adj. Open", "Adj. High", "Adj. Low", "Adj. Close", "Adj. Volume"],
      data: [
        ["2017-11-13",
          177.5,
          179.04,
          177.3,
          178.77,
          9431449,
          0,
          1,
          177.5,
          179.04,
          177.3,
          178.77,
          9431449
        ],
        [
          "2017-11-10",
          178.35,
          179.0999,
          177.96,
          178.46,
          10933405,
          0,
          1,
          178.35,
          179.0999,
          177.96,
          178.46,
          10933405
        ]
      ]
    }
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table,
th,
td {
  border: 1px solid black;
  border-collapse: collapse;
}</code>```

      <th ng-repeat='head in resulting.dataset.column_names' ng-if='$index < 5'>{{head}}

      <td ng-repeat='val in row track by $index' ng-if='$index < 5'>{{val}}

```

Body:
I'm trying to create a table using Quandl restful api along with AngularJS. While table headers created well table rows aren't filled with data at all, there are only empty rows.

Here is my controller:

angular.module('stockControllers', [])
.controller('stockController', function($scope, $http){
  var results = {};
  $http.get('https://www.quandl.com/api/v3/datasets/WIKI/FB.json?start_date=2017-11-01&api_key=3pg7TVEyogz6D6FXhf5g').
  then(function(response) {
      $scope.resulting = response.data;
      console.log($scope.resulting);
 });
});

HTML code:

 {{resulting.dataset.name}}

 Note: showing only OHLC data

        {{resulting.dataset.column_names[0]}}
        {{resulting.dataset.column_names[1]}}
        {{resulting.dataset.column_names[2]}}
    {{resulting.dataset.column_names[3]}}
    {{resulting.dataset.column_names[4]}}

    {{resulting.dataset.data[row][0]}}
    {{resulting.dataset.data[row][1]}}
    {{resulting.dataset.data[row][2]}}
    {{resulting.dataset.data[row][3]}}
    {{resulting.dataset.data[row][4]}}

And api response fragment which I want to use:

"dataset": {
"column_names": ["Date","Open","High","Low","Close","Volume","Ex-Dividend","Split Ratio","Adj. Open","Adj. High","Adj. Low","Adj. Close","Adj. Volume"],
"data": [["2017-11-13",
 177.5,
 179.04,
 177.3,
 178.77,
 9431449,
 0,
 1,
 177.5,
 179.04,
 177.3,
 178.77,
 9431449 ],,
[
 "2017-11-10",
 178.35,
 179.0999,
 177.96,
 178.46,
 10933405,
 0,
 1,
 178.35,
 179.0999,
 177.96,
 178.46,
 10933405 ],,

Body:
angular.module('app', []).controller('ctrl', function($scope) {
  $scope.resulting = {
    dataset: {
      column_names: ["Date", "Open", "High", "Low", "Close", "Volume", "Ex-Dividend", "Split Ratio", "Adj. Open", "Adj. High", "Adj. Low", "Adj. Close", "Adj. Volume"],
      data: [
        ["2017-11-13",
          177.5,
          179.04,
          177.3,
          178.77,
          9431449,
          0,
          1,
          177.5,
          179.04,
          177.3,
          178.77,
          9431449
        ],
        [
          "2017-11-10",
          178.35,
          179.0999,
          177.96,
          178.46,
          10933405,
          0,
          1,
          178.35,
          179.0999,
          177.96,
          178.46,
          10933405
        ]
      ]
    }
  }
});

table,
th,
td {
  border: 1px solid black;
  border-collapse: collapse;
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<table ng-app='app' ng-controller='ctrl'>
  <thead>
    <tr>
      <th ng-repeat='head in resulting.dataset.column_names' ng-if='$index < 5'>{{head}}</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="row in resulting.dataset.data">
      <td ng-repeat='val in row track by $index' ng-if='$index < 5'>{{val}}</td>
    </tr>
  </tbody>
</table>


问:
How to integration masking phone number for send and receive sms
I want to send sms to shipper and shipper replay the SMS to drivers through Twilio.But Shipper don't want to see the courier number.But when the shipper replays the sms the courier able to see it.</p>

答:
Twilio developer evangelist here.

To do number masking, you need to use a Twilio number to receive the messages and send them on to the other party. This article explains how you would achieve that.

You may also be interested in Twilio Proxy which can handle these relationships automatically. It is in preview though, so you need to request access.

Let me know if that helps.


问:
How to Close() all the instances of the Realm before deleting its file
I got the java.lang.IllegalStateException while trying to delete the realm file.

java.lang.IllegalStateException: It's not allowed to delete the file associated with an open Realm. Remember to close() all the instances of the Realm before deleting its file: /data/data/com.mypackage.name/files/filename.realm

I used both executeTransactionAsync and executeTransaction method. So, I guess that there is an instance async that I can not close it before delete the whole realm file.

How can I close all the instances of realm or how to delete realm file without getting this exception?

答:
Hard to answer without some more details, as open instances can come from a lot of places. Perhaps the two links below can provide some guidance in how you work with the Realm instances:

See https://realm.io/docs/java/latest/#closing-realms and https://realm.io/docs/java/latest/#realm-instance-lifecycle


问:
Xamarin Android Microcharts with Fragments
I'm trying to add a chart to my Xamarin Android application (Visual Studio 2017)
I followed this repository MicroCharts, Post

I'm using a Navigation Drawer in my application. So I'm using fragments to add my code. Above mentioned repository is for Xamarin.Forms Cross Platform. But I'm just using Xamarin.Android.

I have a Xamarin.Android repository here.
Any help would be highly appreciated. Thanks

答:
You could refer to this : https://github.com/aloisdeniel/Microcharts

Here is a simple demo about how to use BarChart in your Fragment :

First, Add it to your UI, MGradesView.axml :

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
  <LinearLayout
      android:orientation="vertical"
      android:layout_width="match_parent"
      android:layout_height="wrap_content">
    <microcharts.droid.ChartView
        android:id="@+id/chartView"
        android:layout_width="match_parent"
        android:layout_height="160dp" />
  </LinearLayout>
</ScrollView>
</code>```

Second, your chart will need a set of data entries :

```<code>var entries = new[]
{
    new Entry(200)
    {
        Label = "January",
        ValueLabel = "200",
        Color = SKColor.Parse("#266489")
    },
    new Entry(400)
    {
        Label = "February",
        ValueLabel = "400",
        Color = SKColor.Parse("#68B9C0")
    },
    new Entry(-100)
    {
        Label = "March",
        ValueLabel = "-100",
        Color = SKColor.Parse("#90D585")
    }
};
</code>```

Third, instanciate a chart from those entries :

```<code>var chart = new BarChart() { Entries = entries };
</code>```

Modify your MGradeFragment.cs like this :

```<code>public class MGradeFragment : Fragment
{
    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        SetHasOptionsMenu(true);

        View view = LayoutInflater.From(Activity).Inflate(Resource.Layout.MGradesView, null);

        var entries = new[]
        {
            new Entry(200)
            {
                Label = "January",
                ValueLabel = "200",
                Color = SKColor.Parse("#266489")
            },
            new Entry(400)
            {
                Label = "February",
                ValueLabel = "400",
                Color = SKColor.Parse("#68B9C0")
            },
            new Entry(-100)
            {
                Label = "March",
                ValueLabel = "-100",
                Color = SKColor.Parse("#90D585")
            }
        };
        var chart = new BarChart() { Entries = entries };

        var chartView = view.FindViewById<ChartView>(Resource.Id.chartView);
        chartView.Chart = chart;

        return view;
    }

    public override void OnCreateOptionsMenu(IMenu menu, MenuInflater inflater)
    {
        inflater.Inflate(Resource.Menu.menu_MGradeToolbar, menu);
    }
}
</code>```

Body:
You could refer to this : https://github.com/aloisdeniel/Microcharts

Here is a simple demo about how to use BarChart in your Fragment :

First, Add it to your UI, MGradesView.axml :

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
  <LinearLayout
      android:orientation="vertical"
      android:layout_width="match_parent"
      android:layout_height="wrap_content">
    <microcharts.droid.ChartView
        android:id="@+id/chartView"
        android:layout_width="match_parent"
        android:layout_height="160dp" />
  </LinearLayout>
</ScrollView>

Second, your chart will need a set of data entries :

var entries = new[]
{
    new Entry(200)
    {
        Label = "January",
        ValueLabel = "200",
        Color = SKColor.Parse("#266489")
    },
    new Entry(400)
    {
        Label = "February",
        ValueLabel = "400",
        Color = SKColor.Parse("#68B9C0")
    },
    new Entry(-100)
    {
        Label = "March",
        ValueLabel = "-100",
        Color = SKColor.Parse("#90D585")
    }
};

Third, instanciate a chart from those entries :

var chart = new BarChart() { Entries = entries };

Modify your MGradeFragment.cs like this :

public class MGradeFragment : Fragment
{
    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        SetHasOptionsMenu(true);

        View view = LayoutInflater.From(Activity).Inflate(Resource.Layout.MGradesView, null);

        var entries = new[]
        {
            new Entry(200)
            {
                Label = "January",
                ValueLabel = "200",
                Color = SKColor.Parse("#266489")
            },
            new Entry(400)
            {
                Label = "February",
                ValueLabel = "400",
                Color = SKColor.Parse("#68B9C0")
            },
            new Entry(-100)
            {
                Label = "March",
                ValueLabel = "-100",
                Color = SKColor.Parse("#90D585")
            }
        };
        var chart = new BarChart() { Entries = entries };

        var chartView = view.FindViewById<ChartView>(Resource.Id.chartView);
        chartView.Chart = chart;

        return view;
    }

    public override void OnCreateOptionsMenu(IMenu menu, MenuInflater inflater)
    {
        inflater.Inflate(Resource.Menu.menu_MGradeToolbar, menu);
    }
}


问:
Griddle v1.9 inputbox in customFilterComponent lose focus
I'm stuck with the following problem: every time I update the searchString in my redux store, the CustomFilterConnectedComponent that I pass to Griddle loses focus and I don't understand why this happens.

this is my code based on the documentation:

Dumb component:

```<code>import { connect } from "react-redux";

const CustomFilterComponent = (props) => (
  <input
    value={props.searchString}
    onChange={(e) => { props.setSearchString(e.target.value); }}
  />
);
</code>```

Smart component:

```<code>const CustomFilterConnectedComponent = connect(
  (state: TRootReducerState) => {
    return ({
      searchString: state.searchString,
    });
  },
  (dispatch: any) => ({
    setSearchString: (e) => dispatch(setSearchStringActionCreator(e))
  })
)(CustomFilterComponent);
</code>```

Usage:

```<code>class SomePage extends React.Component<Props, {}> {
  render() {
  return (
        <div>

          {/* keypress - everything is ok, value is updated & focus is not lost*/}
          <CustomFilterConnectedComponent/>

          <Griddle
            components={{
                /* keypress - value is updated, but focus lost */
                Filter: CustomFilterConnectedComponent
            }}
            storeKey="griddleStore"
            data={this.props.requests as any}
          />
     </div>
     );
   }
}
</code>```

Here is a link to the issue on github.

答:
I've turned your repro into a story and am not seeing your focus issue.

That said, my best guess is that the issue is related to how props.requests is provided to SomePage.

Body:
I'm stuck with the following problem: every time I update the searchString in my redux store, the CustomFilterConnectedComponent that I pass to Griddle loses focus and I don't understand why this happens.

this is my code based on the documentation:

Dumb component:

import { connect } from "react-redux";

const CustomFilterComponent = (props) => (
  <input
    value={props.searchString}
    onChange={(e) => { props.setSearchString(e.target.value); }}
  />
);

Smart component:

const CustomFilterConnectedComponent = connect(
  (state: TRootReducerState) => {
    return ({
      searchString: state.searchString,
    });
  },
  (dispatch: any) => ({
    setSearchString: (e) => dispatch(setSearchStringActionCreator(e))
  })
)(CustomFilterComponent);

Usage:

class SomePage extends React.Component<Props, {}> {
  render() {
  return (

          {/* keypress - everything is ok, value is updated & focus is not lost*/}
          <CustomFilterConnectedComponent/>

          <Griddle
            components={{
                /* keypress - value is updated, but focus lost */
                Filter: CustomFilterConnectedComponent
            }}
            storeKey="griddleStore"
            data={this.props.requests as any}
          />

     );
   }
}

Here is a link to the issue on github.


问:
What HW resource is mostly used when one does memcpy()?
This feels like a very newbie question, but I suddenly find myself clueless. I'm trying to profile a c application that does a lot of memory copies, and there is an option for me to reduce that number (requires some re-design). I'm trying to realize if it's worth it, but I have no idea what resource it will affect, or how to monitor it.

If someone knows what resource (and how to monitor it in Linux), and/or has a reference to a section in Agner or any other optimization manual I would very much appreciate it. Thanks.

答:
memcpy uses the CPU in order to copy memory from one buffer to the other. Generally speaking, code doing lots of memcpy will be CPU bound.

With that said, some of the underlying design might make this different. In particular, if you're doing a lot of memory copying, it might be that you are using memory once and throwing it away. If that's the case, you are making poor use of the CPU's data cache. Switching to an algorithm that keeps the memory where it is may give you a huge benefit on that front.

As for profiling, I know valgrind has a tool for checking cache efficiency. Maybe others too.


问:
Mac keyboard shortcuts not working on iOS Simulator
All the mac keyboard short cuts like Cmd + Q (Quit Simulator app), Cmd + K (Toggle keyboard hide/show in Simulator) etc has stopped workings for iOS Simulator app since this morning suddenly.

All other apps, including Xcode, shows the shortcut in menus and they are working fine.

I noticed, the shortcut keys shows up against menu items momentarily on launch of simulator but then disappears completely (see attached)...

I tried following but no success...

Launch simulator (Open Xcode project and then menu Product > Run. And, directly through menu Xcode > Open Developer Tools).

Erase All Content and Settings in Simulator...

Restart Mac

Xcode 9.0.1 (9A1004) | Mac 10.13 (17A405)

答:
You might have enabled (checked) the "Send all keyboard shortcuts to device" mode. It's in the Hardware > Keyboard submenu.

Pressing both Left and Right Cmd keys at the same time will exit keyboard capturing mode and re-enable menu shortcuts.


问:
pointers in C++ (need overview)
```<code>int firstvalue = 5, secondvalue = 15;
int * p1, * p2;

p1 = &firstvalue;
p2 = &secondvalue;
*p1 = 10;    //line 1
*p2 = *p1;  //line 2
 p1 = p2;   //line 3
*p1 = 20;

cout << "firstvalue is " << firstvalue << '\n';
cout << "secondvalue is " << secondvalue << '\n';
return 0;
</code>```

My Analysis of this code:
p1 points to the first value and p2 points to the second value. Now, p1 points to value 10. My first question is :

Does this means that first value now stores 10. (line 1)

According to me, line 2 means that p2 and p1 point to the value stored at the address of the second value. AM I correct or wrong?

Lastly, I have no clue of line 3. So, need some help over there too.

答:
Lets understand what is a pointer - Pointer is storage of address it does not store value itself in light of it lets analyze the code line by line

1) Line 1 - Defined two variables (space to hold value)

2) Line 2 - Defined two pointers (space to hold address)

3) Line 4 & 5 - assigned address of the variables to pointers p1 & p2 now p1 points to location where value 5 is stored and p2 points to a location where 15 is stored

4) Line 6 - Value 10 is stored at the location p1 is pointing this means value of the variable firstvalue is changed from 5 to 10

5) Line 7 - Value of the location pointed by p1 is copied to location pointed by p2. Now both firstvalue and secondvalue is same which is 10

6) Line 8 - Value of the p2 pointer (which is address of secondvalue variable) is assigned to p1. now p1 and p2 both points to secondvalue variable

7) Line 9 - Assigned value 20 to the location pointed by pointer p1 which is now secondvalue variable

Result - both output will show value 20 as both pointers are now pointing to secondvalue variable and it is update to 20 at Line number 9

Title: pointers in C++ (need overview)

Body:
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;

p1 = &firstvalue;
p2 = &secondvalue;
*p1 = 10;    //line 1
*p2 = *p1;  //line 2
 p1 = p2;   //line 3
*p1 = 20;

cout << "firstvalue is " << firstvalue << '\n';
cout << "secondvalue is " << secondvalue << '\n';
return 0;

My Analysis of this code:
p1 points to the first value and p2 points to the second value. Now, p1 points to value 10. My first question is :

Does this means that first value now stores 10. (line 1)

According to me, line 2 means that p2 and p1 point to the value stored at the address of the second value. AM I correct or wrong?

Lastly, I have no clue of line 3. So, need some help over there too.


答:
No, you can't. Cross reference can be achieve by local import. See below example

File A:

```<code># file A.py
from B import B
class A():
    def Foo():
        pass
</code>```

File B:

```<code># file B.py
class B():
    def Bar():
        pass

def some_function():
    from A import A
    # use A here
</code>```

Title: can I import two python classes like this?

Body:
No, you can't. Cross reference can be achieve by local import. See below example

File A:

# file A.py
from B import B
class A():
    def Foo():
        pass

File B:

# file B.py
class B():
    def Bar():
        pass

def some_function():
    from A import A
    # use A here