问:
How to ensure Python script runs by double clicking on Windows OS
I have two Windows 7 machines. On one machine I can run python scripts by double clicking on the .py file, however on the other machine the script does not execute, the command prompt will flash quickly and the script does not execute. I can execute scripts on both machines using the command line. I have the same version of python installed on both machines.

How do I ensure that a python script can be executed by double clicking the script on Windows 7?

答:
Step 1. Check if your .py files are associated with "python launcher" (Not just "python"). You can check that by right clicking the .py file and see:

In my case, I have two machines of Windows 10. The one with Python 3.6 installed by choosing "Install Now" works perfectly. The another one which having the same version of python installed in a customized location has problems. It seems nothing to do with the environment path setting, as I could run python in the console mode correctly. So at the end, I was forced to uninstall the python, (then removing all the related paths manually if needed), and install it again with default setting "Install Now".


来源: stackexchange

问:
How to compare 2 vectors and create a separate vector based on the comparison
i'm looking at creating an algorithm that will compare 2 vectors (v1,v2), and create a new vector v3 that will hold the values not shared between v1 and v2.

```<code>#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(int args[])
{
vector<int> v1 = { 1,2,3,4,5,6,7,8,9 };
vector<int> v2 = { 1,2,6 };
vector<int> v3; //V3 should equal = {3,4,5,7,8,9}.

return 0;
}
</code>```

The vectors will always be sorted.

答:
If, as in your example, the ranges are sorted then you can use std::set_symmetric_difference.  It will return all elements that are not shared between the two ranges.  Using you example you would use

```<code>std::set_symmetric_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(v3));
</code>```

So putting it all together we have

```<code>int main()
{
    std::vector<int> v1 = { 1,2,3,4,5,6,7,8,9 };
    std::vector<int> v2 = { 1,2,6 };
    std::vector<int> v3; //V3 should equal = {3,4,5,7,8,9}.

    std::set_symmetric_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(v3));

    for (auto e : v3)
        std::cout << e << " ";

    return 0;
}
</code>```

Output:

```<code>3 4 5 7 8 9
</code>```

Live example

ContentLicense: CC BY-SA 3.0

Body:
i'm looking at creating an algorithm that will compare 2 vectors (v1,v2), and create a new vector v3 that will hold the values not shared between v1 and v2.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(int args[])
{
vector<int> v1 = { 1,2,3,4,5,6,7,8,9 };
vector<int> v2 = { 1,2,6 };
vector<int> v3; //V3 should equal = {3,4,5,7,8,9}.

return 0;
}

The vectors will always be sorted.

Body:
If, as in your example, the ranges are sorted then you can use std::set_symmetric_difference.  It will return all elements that are not shared between the two ranges.  Using you example you would use

std::set_symmetric_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(v3));

So putting it all together we have

int main()
{
    std::vector<int> v1 = { 1,2,3,4,5,6,7,8,9 };
    std::vector<int> v2 = { 1,2,6 };
    std::vector<int> v3; //V3 should equal = {3,4,5,7,8,9}.

    std::set_symmetric_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(v3));

    for (auto e : v3)
        std::cout << e << " ";

    return 0;
}

Output:

3 4 5 7 8 9

Live example


问:
Ruby - converting a string into hash with each character as key and index as value?
I am trying to transform a given string into a hash with each its character = key and index = value.

For example, if I have str = "hello", I would like it to transform into {"h"=>0, "e"=>1, "l"=>2, "l"=>3, "o"=>4}.

I created a method as such:

```<code>def map_indices(arr)
  arr.map.with_index {|el, index| [el, index]}.to_h
end
#=> map_indices('hello'.split(''))
#=> {"h"=>0, "e"=>1, "l"=>3, "o"=>4}
</code>```

The problem is it skips the first l. If I reverse the order of el and index:   arr.map.with_index {|el, index| [index, el]}.to_h, I get all the letters spelled out: {0=>"h", 1=>"e", 2=>"l", 3=>"l", 4=>"o"}

But when I invert it, I get the same hash that skips one of the l's.

```<code>map_indices('hello'.split('')).invert
#=> {"h"=>0, "e"=>1, "l"=>3, "o"=>4}
</code>```

Why is this behaving like such? How can I get it to print {"h"=>0, "e"=>1, "l"=>2, "l"=>3, "o"=>4}?

答:
It can be done, but will confuse other Ruby programmers.A normal hash treats a key "a" as identical to another "a". Unless a little known feature .compare_by_identity is used:

```<code>h = {}.compare_by_identity
"hello".chars.each_with_index{|c,i| h[c] = i}
p h    # => {"h"=>0, "e"=>1, "l"=>2, "l"=>3, "o"=>4}
</code>```

Body:
I am trying to transform a given string into a hash with each its character = key and index = value.

For example, if I have str = "hello", I would like it to transform into {"h"=>0, "e"=>1, "l"=>2, "l"=>3, "o"=>4}.

I created a method as such:

def map_indices(arr)
  arr.map.with_index {|el, index| [el, index]}.to_h
end
#=> map_indices('hello'.split(''))
#=> {"h"=>0, "e"=>1, "l"=>3, "o"=>4}

The problem is it skips the first l. If I reverse the order of el and index:   arr.map.with_index {|el, index| [index, el]}.to_h, I get all the letters spelled out: {0=>"h", 1=>"e", 2=>"l", 3=>"l", 4=>"o"}

But when I invert it, I get the same hash that skips one of the l's.

map_indices('hello'.split('')).invert
#=> {"h"=>0, "e"=>1, "l"=>3, "o"=>4}

Why is this behaving like such? How can I get it to print {"h"=>0, "e"=>1, "l"=>2, "l"=>3, "o"=>4}?

Body:
It can be done, but will confuse other Ruby programmers.A normal hash treats a key "a" as identical to another "a". Unless a little known feature .compare_by_identity is used:

h = {}.compare_by_identity
"hello".chars.each_with_index{|c,i| h[c] = i}
p h    # => {"h"=>0, "e"=>1, "l"=>2, "l"=>3, "o"=>4}


问:
how to add float in animation as I slide down in parallax website
i want to know how to add effects as like in my website created using wix anjeneyagroups(wix)

Currently I am creating website using wordpress , so I need some experts to suggest me a plugin or css to add effects to each element as I scroll down my website. my current website is anjneyagroups(wordpress)

答:
Waypoints is a good library to use if you need to trigger animations at specific points on the page.

http://imakewebthings.com/waypoints/

You can then use something like Transit to run your animations once a waypoint is triggered.

http://ricostacruz.com/jquery.transit/


问:
Input string was not in a correct format (double)
I'm trying to convert a string (ex. "0.20055") to its equivalent double.

I already know that for some reason that string does not contain a valid double, but I don't understand why.

I really need to be able to convert this string to a double... Could anyone explain me why it's not a valid double? And how to fix this?

Here is some of my code:

```<code>double[] values_in_double = null;
string[] values_in_string = lines[j].Split(',');
for(int x=0; x < numCols; x++)
{
    double val;
    bool r = double.TryParse(values_in_string[x],out val);
    if (!r)
        return;
    values_in_double[x] = Convert.ToDouble(values_in_string[x]);

}
</code>```

As you can see I have a string[] of lines, in which a line is like:

0.20055,0.37951,0.39641,2.0472,32.351,0.38825,0.24976,1.3305,1.1389,0.50494

and I split them. But then I need to convert each one to a double value.

答:
change

```<code>double[] values_in_double = null;

    string[] values_in_string = lines[j].Split(',');
</code>```

to

```<code>string[] values_in_string = lines[j].Split(',');
int arraySize = values_in_string.Length;
double[] values_in_double = new double[arraySize];
</code>```

as you use

```<code>double[] values_in_double = null;
</code>```

and value cannot be assign to null array

Body:
I'm trying to convert a string (ex. "0.20055") to its equivalent double.

I already know that for some reason that string does not contain a valid double, but I don't understand why.

I really need to be able to convert this string to a double... Could anyone explain me why it's not a valid double? And how to fix this?

Here is some of my code:

double[] values_in_double = null;
string[] values_in_string = lines[j].Split(',');
for(int x=0; x < numCols; x++)
{
    double val;
    bool r = double.TryParse(values_in_string[x],out val);
    if (!r)
        return;
    values_in_double[x] = Convert.ToDouble(values_in_string[x]);

}

As you can see I have a string[] of lines, in which a line is like:

0.20055,0.37951,0.39641,2.0472,32.351,0.38825,0.24976,1.3305,1.1389,0.50494

and I split them. But then I need to convert each one to a double value.

Body:
change

double[] values_in_double = null;

    string[] values_in_string = lines[j].Split(',');

to

string[] values_in_string = lines[j].Split(',');
int arraySize = values_in_string.Length;
double[] values_in_double = new double[arraySize];

as you use

double[] values_in_double = null;

and value cannot be assign to null array


问:
Complex doctrine query form validation help!
I am trying to check that a combination of entries across five columns (I have parent1, parent2, parent3, parent4, and parent5 all of which are integers) does not already exist in my form validation.
I tried:

```<code>$query = Doctrine_Query::create()
->select('m.id', 'm.name') -> from ('Mix m')

->where('m.parent1=?', $values['parent1'])

->orWhere('m.parent1=?', $values['parent2'])

->orWhere('m.parent1=?', $values['parent3'])

->orWhere('m.parent1=?', $values['parent4'])

->orWhere('m.parent1=?', $values['parent5'])

->andWhere('m.parent2=?', $values['parent1'])

->orWhere('m.parent2=?', $values['parent2'])
</code>```

...and so on.
Probably not the most efficient way, but regardless it is throwing an error if one of the values matches any of the columns already in the database, it's not checking for the actual combination...
Any help would be very appreciated!

答:
How about...

```<code>// Set of possible matches
$set = array($values['parent1'], $values['parent2'], $values['parent3'], $values['parent4'], $values['parent5']);

// Let's make it two-dimensional for simpler DQL syntax
$sets = array($set, $set, $set, $set, $set);

// Multiple WHERE IN AND
$query = Doctrine_Query::create()
->select('m.id', 'm.name')
->from ('Mix m')
->where('m.parent1 IN ? AND m.parent2 IN ? AND m.parent3 IN ? AND m.parent4 IN ? AND m.parent5 IN ?', $sets);
</code>```

The WHERE IN AND should make sure each value is matched. However, at least one fail case that comes to mind is that if multiple values in the $set are the same (e.g. '5, 5, 1, 4, 1', the query will give false matches. Maybe someone else can improve on that. Might be a slow query as well.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to check that a combination of entries across five columns (I have parent1, parent2, parent3, parent4, and parent5 all of which are integers) does not already exist in my form validation.
I tried:

$query = Doctrine_Query::create()
->select('m.id', 'm.name') -> from ('Mix m')

->where('m.parent1=?', $values['parent1'])

->orWhere('m.parent1=?', $values['parent2'])

->orWhere('m.parent1=?', $values['parent3'])

->orWhere('m.parent1=?', $values['parent4'])

->orWhere('m.parent1=?', $values['parent5'])

->andWhere('m.parent2=?', $values['parent1'])

->orWhere('m.parent2=?', $values['parent2'])

...and so on.
Probably not the most efficient way, but regardless it is throwing an error if one of the values matches any of the columns already in the database, it's not checking for the actual combination...
Any help would be very appreciated!

Body:
How about...

// Set of possible matches
$set = array($values['parent1'], $values['parent2'], $values['parent3'], $values['parent4'], $values['parent5']);

// Let's make it two-dimensional for simpler DQL syntax
$sets = array($set, $set, $set, $set, $set);

// Multiple WHERE IN AND
$query = Doctrine_Query::create()
->select('m.id', 'm.name')
->from ('Mix m')
->where('m.parent1 IN ? AND m.parent2 IN ? AND m.parent3 IN ? AND m.parent4 IN ? AND m.parent5 IN ?', $sets);

The WHERE IN AND should make sure each value is matched. However, at least one fail case that comes to mind is that if multiple values in the $set are the same (e.g. '5, 5, 1, 4, 1', the query will give false matches. Maybe someone else can improve on that. Might be a slow query as well.


问:
How to offset MKMapView to put coordinates under specified point
I have two view controllers. One allows the user to enter their own sightings of things:

The other is a UITableViewController that allows them to see their submitted sightings:

What I want is for the user to be able to click on their sighting in the 2nd VC and for it to populate the 1st VC with the relevant details. I have that working for the textFields using :

```<code>override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let pvc = self.navigationController?.previousViewController() as! SubmitSightingVC
    let sighting = sightingsArray[indexPath.row]
    pvc.titleTextField.text = sighting["title"] as! String?
    pvc.locationTextField.text = sighting["location"] as! String?
    pvc.dateTextField.text = sighting["date"] as! String?
    pvc.descriptionTextView.text = sighting["sightingDesc"] as! String?

    let pinArray = ["1", "2", "3", "4", "5"]
    let pinTextArray = ["1text", "2text", "3text", "4text", "5text"]
    var pinImageArray = [#imageLiteral(resourceName: "1"), #imageLiteral(resourceName: "2"), #imageLiteral(resourceName: "3"), #imageLiteral(resourceName: "4"), #imageLiteral(resourceName: "5")]
    let pinIconString = sighting["pinIcon"] as! String
    let index = pinArray.index(of: pinIconString)

    pvc.pinImageView.image = pinImageArray[index!]
    pvc.pinTextField.text = pinTextArray[index!]

    // Bit I'm struggling with:
    var coordinates = CLLocationCoordinate2D(latitude: sighting["latitude"] as! Double, longitude: sighting["longitude"] as! Double)
    pvc.mapView.centerCoordinate = coordinates

    self.navigationController!.popViewController(animated: true)

}
</code>```

The problem is that because the centre of the map is behind the blurred view it is offset. The pin on the map isn't an actual pin but a UIImage (pinImageView). How can I move the map so that the coordinates are under this pinImage instead of in the centre of the mapView?

答:
As mentioned above you can use the MKMapCamera to position the view of the map or you can also use setVisibleMapRect and add some padding to position the map like this:

```<code>self.mapView.setVisibleMapRect(self.mapView.visibleMapRect, edgePadding: UIEdgeInsetsMake(200.0, 0.0, 0.0, 0.0), animated: true)
</code>```

This will offset the center by 200 screen pixels on the top.

ContentLicense: CC BY-SA 4.0

Body:
I have two view controllers. One allows the user to enter their own sightings of things:

The other is a UITableViewController that allows them to see their submitted sightings:

What I want is for the user to be able to click on their sighting in the 2nd VC and for it to populate the 1st VC with the relevant details. I have that working for the textFields using :

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let pvc = self.navigationController?.previousViewController() as! SubmitSightingVC
    let sighting = sightingsArray[indexPath.row]
    pvc.titleTextField.text = sighting["title"] as! String?
    pvc.locationTextField.text = sighting["location"] as! String?
    pvc.dateTextField.text = sighting["date"] as! String?
    pvc.descriptionTextView.text = sighting["sightingDesc"] as! String?

    let pinArray = ["1", "2", "3", "4", "5"]
    let pinTextArray = ["1text", "2text", "3text", "4text", "5text"]
    var pinImageArray = [#imageLiteral(resourceName: "1"), #imageLiteral(resourceName: "2"), #imageLiteral(resourceName: "3"), #imageLiteral(resourceName: "4"), #imageLiteral(resourceName: "5")]
    let pinIconString = sighting["pinIcon"] as! String
    let index = pinArray.index(of: pinIconString)

    pvc.pinImageView.image = pinImageArray[index!]
    pvc.pinTextField.text = pinTextArray[index!]

    // Bit I'm struggling with:
    var coordinates = CLLocationCoordinate2D(latitude: sighting["latitude"] as! Double, longitude: sighting["longitude"] as! Double)
    pvc.mapView.centerCoordinate = coordinates

    self.navigationController!.popViewController(animated: true)

}

The problem is that because the centre of the map is behind the blurred view it is offset. The pin on the map isn't an actual pin but a UIImage (pinImageView). How can I move the map so that the coordinates are under this pinImage instead of in the centre of the mapView?

Body:
As mentioned above you can use the MKMapCamera to position the view of the map or you can also use setVisibleMapRect and add some padding to position the map like this:

self.mapView.setVisibleMapRect(self.mapView.visibleMapRect, edgePadding: UIEdgeInsetsMake(200.0, 0.0, 0.0, 0.0), animated: true)

This will offset the center by 200 screen pixels on the top.


问:
How to run single Jasmine test in IntelliJ IDEA
Is it possible to run single Jasmine test it or suite describe in IntelliJ from popup menu as it possible with JUnit or TestNG fremeworks?

Now I can only execute tests by running karma.conf.js that will grab all specs and run them which is not exactly what I want.

Updates

This is known issue please upvote it.

答: With WebStorm 2017.1 it's possible to use RunConfiguration producer to run a single Karma test: https://github.com/develar/ij-rc-producer</p>


答:
Try changing the line :

```<code>double[] values_in_double = null;
</code>```

into

```<code>double[] values_in_double = new double[numCols];
</code>```

Because otherwise the code you provided wouldn't run since the array is not defined (cannot be null).

Title: Input string was not in a correct format (double)

Body:
Try changing the line :

double[] values_in_double = null;

into

double[] values_in_double = new double[numCols];

Because otherwise the code you provided wouldn't run since the array is not defined (cannot be null).


问:
Xamarin saving a video path in sqlite. Having permission issue to save
I am recording for 7 seconds and after that I want to save the video but I have an error. Trying to save the video. error is =

Java.IO.IOException: invalid preview surface
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ()

The code is

```<code>  private  void SetupRecording(object sender, EventArgs e)   // start recording
    {

        try
        {
            video.StopPlayback();

            recorder = new MediaRecorder();
            recorder.SetVideoSource(VideoSource.Camera);
            recorder.SetOutputFormat(OutputFormat.Default);
            recorder.SetVideoFrameRate(30);
            recorder.SetVideoEncoder(VideoEncoder.Default);
            recorder.SetOutputFile(path);
            recorder.SetPreviewDisplay(video.Holder.Surface);
            recorder.SetMaxDuration(7000);
            // recording for 7 seconds

            recorder.Prepare();

            try
            {

                Video vid = new Video()
                {
                    ProjectID = passedID,
                    VideoPath = path,

                };
                updatavideodb.insertIntoTableVideo(vid);

            }
            catch (Java.Lang.Exception ex)
            {

                recorder.Stop();
                recorder.Release();
                return;
            }
            recorder.Start();
            Thread.Sleep(8000);
            recorder.Stop();
            recorder.Release();
            textCountDown.Text = " Finshed Recording ";

            CloseCamera();
        }
</code>```

The path i am trying to save to

path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/test" + time.ToString().Replace("/", "-") + ".mp4";

The manifest is -

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="ShowWorksDemo6.ShowWorksDemo6" android:versionCode="1" android:versionName="1.0" android:installLocation="auto">
<uses-sdk android:minSdkVersion="16" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permission android:name="android.permission.INTERNET" />
<application android:label="ShowWorksDemo6"></application>
</manifest>
</code>```

the code stop running at the line recorder.Prepare();

I like any help in what I am wrong would be great help.

答: I would have added this a comment, but I don't have enough rep yet. Take a look at this answer. It looks the error is related to this line in your code recorder.SetPreviewDisplay(video.Holder.Surface);.

Body:
I am recording for 7 seconds and after that I want to save the video but I have an error. Trying to save the video. error is =

Java.IO.IOException: invalid preview surface
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw ()

The code is

  private  void SetupRecording(object sender, EventArgs e)   // start recording
    {

        try
        {
            video.StopPlayback();

            recorder = new MediaRecorder();
            recorder.SetVideoSource(VideoSource.Camera);
            recorder.SetOutputFormat(OutputFormat.Default);
            recorder.SetVideoFrameRate(30);
            recorder.SetVideoEncoder(VideoEncoder.Default);
            recorder.SetOutputFile(path);
            recorder.SetPreviewDisplay(video.Holder.Surface);
            recorder.SetMaxDuration(7000);
            // recording for 7 seconds

            recorder.Prepare();

            try
            {

                Video vid = new Video()
                {
                    ProjectID = passedID,
                    VideoPath = path,

                };
                updatavideodb.insertIntoTableVideo(vid);

            }
            catch (Java.Lang.Exception ex)
            {

                recorder.Stop();
                recorder.Release();
                return;
            }
            recorder.Start();
            Thread.Sleep(8000);
            recorder.Stop();
            recorder.Release();
            textCountDown.Text = " Finshed Recording ";

            CloseCamera();
        }

The path i am trying to save to

path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/test" + time.ToString().Replace("/", "-") + ".mp4";

The manifest is -

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="ShowWorksDemo6.ShowWorksDemo6" android:versionCode="1" android:versionName="1.0" android:installLocation="auto">
<uses-sdk android:minSdkVersion="16" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permission android:name="android.permission.INTERNET" />
<application android:label="ShowWorksDemo6"></application>
</manifest>

the code stop running at the line recorder.Prepare();

I like any help in what I am wrong would be great help.


问:
Create zip style file without compression
I know that there are many free and not so free compression libraries out there, but for the project i am working on, i need to be able to take file data from a stream and put it into some kind zip or pack file, but without compression, because i will need to access these files quickly without having to wait for them to decompress.

Anyone know how this could be approached, or if there are some libraries out there that do this that i am not aware of?

答:
Traditionally simple storage files under windows are cabinet files, which do support compression, as well as signing, what zip does not support.

Look out if theres a way to create cabinet files within .net.

OwnerDisplayName: Jason Miesionczek

OwnerDisplayName: BeowulfOF


问:
Reactive Extensions seem very slow - am I doing something wrong?
I'm evaluating Rx for a trading platform project that will need to process thousands of messages a second. The existing platform has a complex event routing system (multicast delegates) that responds to these messages and performs a lot of subsequent processing.

I've looked at Reactive Extensions for the obvious benefits but noticed it's somewhat slower, usual 100 times slower.

I've created unit test to demonstrate this which runs a simple increment 1 million times, using various Rx flavours and a straight-out-the-box delegate "control" test.

Here are the results:

```<code>Delegate                                 - (1000000) - 00:00:00.0410000
Observable.Range()                       - (1000000) - 00:00:04.8760000
Subject.Subscribe() - NewThread          - (1000000) - 00:00:02.7630000
Subject.Subscribe() - CurrentThread      - (1000000) - 00:00:03.0280000
Subject.Subscribe() - Immediate          - (1000000) - 00:00:03.0030000
Subject.Subscribe() - ThreadPool         - (1000000) - 00:00:02.9800000
Subject.Subscribe() - Dispatcher         - (1000000) - 00:00:03.0360000
</code>```

As you can see, all the Rx methods are ~100 times slower than a delegate equivalent. Obviously Rx is doing a lot under the covers that will be of use in a more complex example, but this just seems incredibly slow.

Is this normal or are my testing assumptions invalid? Nunit code for the above below -

```<code>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System.Concurrency;

namespace RxTests
{
    [TestFixture]
    class ReactiveExtensionsBenchmark_Tests
    {
        private int counter = 0;

        [Test]
        public void ReactiveExtensionsPerformanceComparisons()
        {
            int iterations = 1000000;

            Action<int> a = (i) => { counter++; };

            DelegateSmokeTest(iterations, a);
            ObservableRangeTest(iterations, a);
            SubjectSubscribeTest(iterations, a, Scheduler.NewThread, "NewThread");
            SubjectSubscribeTest(iterations, a, Scheduler.CurrentThread, "CurrentThread");
            SubjectSubscribeTest(iterations, a, Scheduler.Immediate, "Immediate");
            SubjectSubscribeTest(iterations, a, Scheduler.ThreadPool, "ThreadPool");
            SubjectSubscribeTest(iterations, a, Scheduler.Dispatcher, "Dispatcher");
        }

        public void ObservableRangeTest(int iterations, Action<int> action)
        {
            counter = 0;

            long start = DateTime.Now.Ticks;

            Observable.Range(0, iterations).Subscribe(action);

            OutputTestDuration("Observable.Range()", start);
        }

        public void SubjectSubscribeTest(int iterations, Action<int> action, IScheduler scheduler, string mode)
        {
            counter = 0;

            var eventSubject = new Subject<int>();
            var events = eventSubject.SubscribeOn(scheduler); //edited - thanks dtb
            events.Subscribe(action);

            long start = DateTime.Now.Ticks;

            Enumerable.Range(0, iterations).ToList().ForEach
                (
                    a => eventSubject.OnNext(1)
                );

            OutputTestDuration("Subject.Subscribe() - " + mode, start);
        }

        public void DelegateSmokeTest(int iterations, Action<int> action)
        {
            counter = 0;
            long start = DateTime.Now.Ticks;

            Enumerable.Range(0, iterations).ToList().ForEach
                (
                    a => action(1)
                );

            OutputTestDuration("Delegate", start);
        }

        /// <summary>
        /// Output helper
        /// </summary>
        /// <param name="test"></param>
        /// <param name="duration"></param>
        public void OutputTestDuration(string test, long duration)
        {
            Debug.WriteLine(string.Format("{0, -40} - ({1}) - {2}", test, counter, ElapsedDuration(duration)));
        }

        /// <summary>
        /// Test timing helper
        /// </summary>
        /// <param name="elapsedTicks"></param>
        /// <returns></returns>
        public string ElapsedDuration(long elapsedTicks)
        {
            return new TimeSpan(DateTime.Now.Ticks - elapsedTicks).ToString();
        }

    }
}
</code>```

答:
Remember that your Delegate doesn't guarantee any thread safety - it literally calls the delegate from whatever thread it's called from, whereas when you call Observable.ObserveOn to marshall notifications to other threads, Rx.NET has to do locking to make sure it does what you think it does.

So, Delegates might move super fast, but if you want to build something practical using it, you're going to end up building synchronization by-hand which will slow you down. That being said, Rx, just like LINQ, is an abstraction - if you need it to be ridiculously fast, you have to start writing ugly code.

Body:
I'm evaluating Rx for a trading platform project that will need to process thousands of messages a second. The existing platform has a complex event routing system (multicast delegates) that responds to these messages and performs a lot of subsequent processing.

I've looked at Reactive Extensions for the obvious benefits but noticed it's somewhat slower, usual 100 times slower.

I've created unit test to demonstrate this which runs a simple increment 1 million times, using various Rx flavours and a straight-out-the-box delegate "control" test.

Here are the results:

Delegate                                 - (1000000) - 00:00:00.0410000
Observable.Range()                       - (1000000) - 00:00:04.8760000
Subject.Subscribe() - NewThread          - (1000000) - 00:00:02.7630000
Subject.Subscribe() - CurrentThread      - (1000000) - 00:00:03.0280000
Subject.Subscribe() - Immediate          - (1000000) - 00:00:03.0030000
Subject.Subscribe() - ThreadPool         - (1000000) - 00:00:02.9800000
Subject.Subscribe() - Dispatcher         - (1000000) - 00:00:03.0360000

As you can see, all the Rx methods are ~100 times slower than a delegate equivalent. Obviously Rx is doing a lot under the covers that will be of use in a more complex example, but this just seems incredibly slow.

Is this normal or are my testing assumptions invalid? Nunit code for the above below -

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System.Concurrency;

namespace RxTests
{
    [TestFixture]
    class ReactiveExtensionsBenchmark_Tests
    {
        private int counter = 0;

        [Test]
        public void ReactiveExtensionsPerformanceComparisons()
        {
            int iterations = 1000000;

            Action<int> a = (i) => { counter++; };

            DelegateSmokeTest(iterations, a);
            ObservableRangeTest(iterations, a);
            SubjectSubscribeTest(iterations, a, Scheduler.NewThread, "NewThread");
            SubjectSubscribeTest(iterations, a, Scheduler.CurrentThread, "CurrentThread");
            SubjectSubscribeTest(iterations, a, Scheduler.Immediate, "Immediate");
            SubjectSubscribeTest(iterations, a, Scheduler.ThreadPool, "ThreadPool");
            SubjectSubscribeTest(iterations, a, Scheduler.Dispatcher, "Dispatcher");
        }

        public void ObservableRangeTest(int iterations, Action<int> action)
        {
            counter = 0;

            long start = DateTime.Now.Ticks;

            Observable.Range(0, iterations).Subscribe(action);

            OutputTestDuration("Observable.Range()", start);
        }

        public void SubjectSubscribeTest(int iterations, Action<int> action, IScheduler scheduler, string mode)
        {
            counter = 0;

            var eventSubject = new Subject<int>();
            var events = eventSubject.SubscribeOn(scheduler); //edited - thanks dtb
            events.Subscribe(action);

            long start = DateTime.Now.Ticks;

            Enumerable.Range(0, iterations).ToList().ForEach
                (
                    a => eventSubject.OnNext(1)
                );

            OutputTestDuration("Subject.Subscribe() - " + mode, start);
        }

        public void DelegateSmokeTest(int iterations, Action<int> action)
        {
            counter = 0;
            long start = DateTime.Now.Ticks;

            Enumerable.Range(0, iterations).ToList().ForEach
                (
                    a => action(1)
                );

            OutputTestDuration("Delegate", start);
        }

        ///
        /// Output helper
        ///
        /// <param name="test"></param>
        /// <param name="duration"></param>
        public void OutputTestDuration(string test, long duration)
        {
            Debug.WriteLine(string.Format("{0, -40} - ({1}) - {2}", test, counter, ElapsedDuration(duration)));
        }

        ///
        /// Test timing helper
        ///
        /// <param name="elapsedTicks"></param>
        /// <returns></returns>
        public string ElapsedDuration(long elapsedTicks)
        {
            return new TimeSpan(DateTime.Now.Ticks - elapsedTicks).ToString();
        }

    }
}


问:
Javascript - How to return object with promise
I'm trying to return an object with a specific structure but i can't return the object.

As you can see in the code if i print inside promise it prints data but if i print outside is empty... why?

How can i return the object parts?

```<code>var parts = [];
var part = [];
var articles = [];

part.push(request.query("SELECT u_order, u_familia, u_part, u_type FROM u_part (nolock) where u_order <'92' and u_order <> '100'"));

return Promise.all([Promise.all(part)]).then(function(listOfResults)
{
  for(var i=0; i<listOfResults[0][0].length; i++)
  {
    articles.push(request.query("SELECT st.u_posic, sc.ref, sc.qtt, sc.design FROM st INNER JOIN sc ON st.ref = sc.ref where sc.ststamp ='"+stamp+"' and st.u_posic = '"+listOfResults[0][0][i].u_order+"'"));
    //articles.push(request.query("SELECT ststamp, ref, design FROM st (nolock) WHERE u_posic = '"+listOfResults[0][0][i].u_order+"'"));

    Promise.all([Promise.all(articles)]).then(function(listOfArticles)
    {

      for(var j=0; j<listOfResults[0][0].length; j++)
      {
        parts.push({
          u_order: listOfResults[0][0][j].u_order,
          u_familia: listOfResults[0][0][j].u_familia,
          u_part: listOfResults[0][0][j].u_part,
          u_type: listOfResults[0][0][j].u_type,
          articles: listOfArticles[0][j-1]
        });

        console.log(parts); HERE THE OBJECT HAD DATA
      }

    });

  }
  console.log(parts); BUT HERE IS EMPTY

}).catch(function(err)
{
    console.log(err);
});
</code>```

Thank you.

答:
The whole point of Promises is being asynchronous. You need to wait for your Promise to resolve or reject to check for data. Specifically, you should only do anything with the returned value of your Promise within the Promise.then() method, which runs as soon as the Promise finishes execution. Changing variables which exist outside the Promise from within it, as you are doing by calling parts.push() is a bad practice. You should return parts within your promise, and then, in a final .then() callback, you should do whatever is required with parts.

Something like:

```<code>Promise.all(part).then(makeAllQueries).then(doSomethingWithQueryResults);
</code>```

You can only be sure you actually have data or not when your final .then callback runs.

Also, doing Promise.all([Promise.all(part)]) does nothing for you, as you're just wrapping your returned array in one more array level.

Body:
I'm trying to return an object with a specific structure but i can't return the object.

As you can see in the code if i print inside promise it prints data but if i print outside is empty... why?

How can i return the object parts?

var parts = [];
var part = [];
var articles = [];

part.push(request.query("SELECT u_order, u_familia, u_part, u_type FROM u_part (nolock) where u_order <'92' and u_order <> '100'"));

return Promise.all([Promise.all(part)]).then(function(listOfResults)
{
  for(var i=0; i<listOfResults[0][0].length; i++)
  {
    articles.push(request.query("SELECT st.u_posic, sc.ref, sc.qtt, sc.design FROM st INNER JOIN sc ON st.ref = sc.ref where sc.ststamp ='"+stamp+"' and st.u_posic = '"+listOfResults[0][0][i].u_order+"'"));
    //articles.push(request.query("SELECT ststamp, ref, design FROM st (nolock) WHERE u_posic = '"+listOfResults[0][0][i].u_order+"'"));

    Promise.all([Promise.all(articles)]).then(function(listOfArticles)
    {

      for(var j=0; j<listOfResults[0][0].length; j++)
      {
        parts.push({
          u_order: listOfResults[0][0][j].u_order,
          u_familia: listOfResults[0][0][j].u_familia,
          u_part: listOfResults[0][0][j].u_part,
          u_type: listOfResults[0][0][j].u_type,
          articles: listOfArticles[0][j-1]
        });

        console.log(parts); HERE THE OBJECT HAD DATA
      }

    });

  }
  console.log(parts); BUT HERE IS EMPTY

}).catch(function(err)
{
    console.log(err);
});

Thank you.

Body:
The whole point of Promises is being asynchronous. You need to wait for your Promise to resolve or reject to check for data. Specifically, you should only do anything with the returned value of your Promise within the Promise.then() method, which runs as soon as the Promise finishes execution. Changing variables which exist outside the Promise from within it, as you are doing by calling parts.push() is a bad practice. You should return parts within your promise, and then, in a final .then() callback, you should do whatever is required with parts.

Something like:

Promise.all(part).then(makeAllQueries).then(doSomethingWithQueryResults);

You can only be sure you actually have data or not when your final .then callback runs.

Also, doing Promise.all([Promise.all(part)]) does nothing for you, as you're just wrapping your returned array in one more array level.


问:
How to display a worksheet on a form in excel-vba
I'm trying to display a worksheet on a form, but until now i did not succeed. The worksheet it contain 15 columns and about 2000 rows. Can someone help me? </p>

答:
Build a form with a listbox on it, and also a button.  Then put this code into the form module.  The button should have the name CommandButton1 and the listbox should be named ListBox1.

Finally on the listbox control change the columncount to 15.

```<code>Private Sub CommandButton1_Click()
    Unload Me
End Sub

Private Sub UserForm_Initialize()
    ' Activate the sheet that has the data you want displayed in the listbox
    Sheet1.Activate
    ' Put the range of the data you want displayed.
    ' Here I used columns "A" to "O" and 2000 rows
    ListBox1.RowSource = "A1:O2000"
End Sub
</code>```

Body:
Build a form with a listbox on it, and also a button.  Then put this code into the form module.  The button should have the name CommandButton1 and the listbox should be named ListBox1.

Finally on the listbox control change the columncount to 15.

Private Sub CommandButton1_Click()
    Unload Me
End Sub

Private Sub UserForm_Initialize()
    ' Activate the sheet that has the data you want displayed in the listbox
    Sheet1.Activate
    ' Put the range of the data you want displayed.
    ' Here I used columns "A" to "O" and 2000 rows
    ListBox1.RowSource = "A1:O2000"
End Sub


问:
How to make nested Div wrap instead of overlap?
I'm using Bootstrap's grid system. I have 3 divs inside a "row", and inside each of those divs are nested controls.

When I horizontally decrease the browser size, the 2nd and 3rd div in the row are overlapping the 1st div. I want them to wrap, not overlap.

How can I achieve this?

Here is my code:

      <select style="min-width: 215px; max-width: 300px;" class="col-xs-4 form-control" data-bind="value: selectedSAPIValue, options: saorpi, optionsText: 'Name', optionsValue: 'CmeTypeId', optionsCaption: 'Select SA or PI'"></select>

      <select style="max-width: 300px;" class="specialties-class form-control" name="Name" id="SpecialtyId"></select>

      <button id="btnDropDownsSearch" class="btn btn-search collapsed" type="button">

       </button>

    OR

    Activity Search

      <input id="txtFreeformSearch" class="form-control" type="search" style="min-width:175px;" />

        <button id="btnFreeformSearch" class="btn btn-search collapsed" type="button">

        </button>

```

答:
I solved this by defining min-width inside a good number of the tags.
This allowed the DIVs to wrap in PC, tablet, and mobile formats.

I would post the resulting HTML, but I think it would affect too few readers to make it worthwhile. I say this because there is a knockout control and select2 control within the HTML, and some of their UI properties are defined in javascript.


问:
How to spy componentWillMount using jest and enzyme
I am trying to test whether componentWillMount was called and for that my test is

```<code>test('calls `componentWillMount` before rendering', () => {
  let fn = jest.fn(SomeComponent.prototype.componentWillMount)
  mount(<SomeComponent />)
  expect(fn).toHaveBeenCalled()
})
</code>```

But even though the componentWillMount method is called, the test does not pass.
What am I missing here?

答:
I don't know if the other answers have helped with your question, but you shouldn't need to test componentWillMount. React should already do that testing for you.

More relevant to your testing would be to test the functions or actions you are putting in that method for your component.

If you are making some API call, running a function based on props, or anything else, that is what you should be testing for. Mock the function/action/code that componentWillMount triggers, and make assertions and expectations on that.

Example:

Component:

```<code>class YourComponent extends Component {

  componentWillMount() {
    /*this fetch function is actually what you want to test*/
    this.props.fetch('data')
  }

  render() {
    /* whatever your component renders*/
  }
}
</code>```

Tests:

```<code>test('should call fetch when mounted', () => {
  let mockFetch = jest.fn()

  const wrapper = mount(<SomeComponent fetch={mockFetch}/>);

  expect(wrapper).toBeDefined();
  expect(mockFetch).toHaveBeenCalled();
  expect(mockFetch.mock.calls[0]).toEqual(['data'])
});
</code>```

Body:
I am trying to test whether componentWillMount was called and for that my test is

test('calls `componentWillMount` before rendering', () => {
  let fn = jest.fn(SomeComponent.prototype.componentWillMount)
  mount(<SomeComponent />)
  expect(fn).toHaveBeenCalled()
})

But even though the componentWillMount method is called, the test does not pass.
What am I missing here?

Body:
I don't know if the other answers have helped with your question, but you shouldn't need to test componentWillMount. React should already do that testing for you.

More relevant to your testing would be to test the functions or actions you are putting in that method for your component.

If you are making some API call, running a function based on props, or anything else, that is what you should be testing for. Mock the function/action/code that componentWillMount triggers, and make assertions and expectations on that.

Example:

Component:

class YourComponent extends Component {

  componentWillMount() {
    /*this fetch function is actually what you want to test*/
    this.props.fetch('data')
  }

  render() {
    /* whatever your component renders*/
  }
}

Tests:

test('should call fetch when mounted', () => {
  let mockFetch = jest.fn()

  const wrapper = mount(<SomeComponent fetch={mockFetch}/>);

  expect(wrapper).toBeDefined();
  expect(mockFetch).toHaveBeenCalled();
  expect(mockFetch.mock.calls[0]).toEqual(['data'])
});


问:
Trouble with my chrome extension. jQuery?
This is my first time making a Chrome extension and I think my javascript/jQuery is not loading.

These are my scripts from different files.

```<code> <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>

<script src="popup.js"></script>
</code>```

```<code><script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<!--<script src='https://cdnjs.cloudflare.com/ajax/libs/amcharts/3.21.0/amcharts.js'></script>-->

<script src="more.js"></script>
</code>```

```<code><script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
<script src="options.js"></script>
</code>```

And this is my Github repo.

Also I want to remote access jQuery I don't want to host it myself.

I'm using a bunch of APIs like reddit,stackexchange,cryptonator,bitcointalk(unofficial).
Perhaps I have to declare these or jQuery in the manifest.json?

This is my manifest.json file.

```<code>{
  "manifest_version": 2,
  "name": "TheMoneroPug",
  "short_name":"MoneroPug",
  "author": "Karthik",
  "version": "1.0.0",
  "version_name": "1.0.0",
  "description": "A Chrome extension for viewing Monero price(for traders)",
  "icons": {"128":"main/128.png"},
  "browser_action": {
   "default_icon": {
   "16": "main/16.png",
   "48": "main/48.png"
  },
    "default_title": "TheMoneroPug",
   "default_popup": "main/popup.html"
  },
  "options_ui": {
   "page": "setting/options.html",
  "chrome_style": true
  },
 "background": {
  "scripts": [
  "main/popup.js",
  "more/more.js",
  "setting/options.js"
  ]
 },
 "permissions": [
 "storage"
  ]
 }
</code>```

I do not have any background.html files the browser action is popup.
The error is with jQuery shows that $ is not defined and the error

because it violates the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:"

How do I fix this?

答:
You need to add the jQuery CDN you're using to the sites allowed by the content security policy in the manifest.

By default only scripts included in the extension are allowed, and as the whole extension is downloaded on install there's no advantage in using a CDN.

Body:
This is my first time making a Chrome extension and I think my javascript/jQuery is not loading.

These are my scripts from different files.

And this is my Github repo.

Also I want to remote access jQuery I don't want to host it myself.

I'm using a bunch of APIs like reddit,stackexchange,cryptonator,bitcointalk(unofficial).
Perhaps I have to declare these or jQuery in the manifest.json?

This is my manifest.json file.

{
  "manifest_version": 2,
  "name": "TheMoneroPug",
  "short_name":"MoneroPug",
  "author": "Karthik",
  "version": "1.0.0",
  "version_name": "1.0.0",
  "description": "A Chrome extension for viewing Monero price(for traders)",
  "icons": {"128":"main/128.png"},
  "browser_action": {
   "default_icon": {
   "16": "main/16.png",
   "48": "main/48.png"
  },
    "default_title": "TheMoneroPug",
   "default_popup": "main/popup.html"
  },
  "options_ui": {
   "page": "setting/options.html",
  "chrome_style": true
  },
 "background": {
  "scripts": [
  "main/popup.js",
  "more/more.js",
  "setting/options.js"
  ]
 },
 "permissions": [
 "storage"
  ]
 }

I do not have any background.html files the browser action is popup.
The error is with jQuery shows that $ is not defined and the error

because it violates the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:"

How do I fix this?


问:
Set the maximum character length of a UITextField in Swift
I know there are other topics on this, but I can't seem to find out how to implement it.

I'm trying to limit a UITextField to only five characters.

Preferably alphanumeric, -, ., and _.

I've seen this code:

```<code>func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange,
                       replacementString string: String) -> Bool
{
    let maxLength = 4
    let currentString: NSString = textField.text
    let newString: NSString =
             currentString.stringByReplacingCharactersInRange(range, withString: string)
    return newString.length <= maxLength
}
</code>```

and

```<code>func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    let length = count(textField.text.utf16) + count(string.utf16) - range.length
    return length <= 10
}
</code>```

How can I actually implement it? Which "textfield" should I swap out for my custom named UITextField?

答:
Modern Swift

Note that a lot of the example code online is extremely out of date.

Paste the following into any Swift file in your project, example "Handy.swift".

This fixes one of the silliest problems in iOS:

Your text fields now have a .maxLength.

It is completely OK to set that value in storyboard or set in code while the app is running.

```<code>// Handy.swift

import UIKit
private var __maxLengths = [UITextField: Int]()
extension UITextField {
    @IBInspectable var maxLength: Int {
        get {
            guard let l = __maxLengths[self] else {
               return 150 // (global default-limit. or just, Int.max)
            }
            return l
        }
        set {
            __maxLengths[self] = newValue
            addTarget(self, action: #selector(fix), for: .editingChanged)
        }
    }
    func fix(textField: UITextField) {
        let t = textField.text
        textField.text = t?.prefix(maxLength).string
    }
}
</code>```

It's that simple.

An even simpler one-off version...

The above fixes all text fields in the whole project.

If you just want one particular text field to simply be limited to say "4", and that's that...

```<code>class PinCodeEntry: UITextField {

    override func didMoveToSuperview() {

        super.didMoveToSuperview()
        addTarget(self, action: #selector(fixMe), for: .editingChanged)
    }

    @objc private func fixMe() { text = text?.prefix(4) }
}
</code>```

That's all there is to it.

(Here's a similar very useful tip relating to UITextView,
https://stackoverflow.com/a/42333832/294884 )

Body:
I know there are other topics on this, but I can't seem to find out how to implement it.

I'm trying to limit a UITextField to only five characters.

Preferably alphanumeric, -, ., and _.

I've seen this code:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange,
                       replacementString string: String) -> Bool
{
    let maxLength = 4
    let currentString: NSString = textField.text
    let newString: NSString =
             currentString.stringByReplacingCharactersInRange(range, withString: string)
    return newString.length <= maxLength
}

and

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    let length = count(textField.text.utf16) + count(string.utf16) - range.length
    return length <= 10
}

How can I actually implement it? Which "textfield" should I swap out for my custom named UITextField?

Body:
Modern Swift

Note that a lot of the example code online is extremely out of date.

Paste the following into any Swift file in your project, example "Handy.swift".

This fixes one of the silliest problems in iOS:

Your text fields now have a .maxLength.

It is completely OK to set that value in storyboard or set in code while the app is running.

// Handy.swift

import UIKit
private var __maxLengths = [UITextField: Int]()
extension UITextField {
    @IBInspectable var maxLength: Int {
        get {
            guard let l = __maxLengths[self] else {
               return 150 // (global default-limit. or just, Int.max)
            }
            return l
        }
        set {
            __maxLengths[self] = newValue
            addTarget(self, action: #selector(fix), for: .editingChanged)
        }
    }
    func fix(textField: UITextField) {
        let t = textField.text
        textField.text = t?.prefix(maxLength).string
    }
}

It's that simple.

An even simpler one-off version...

The above fixes all text fields in the whole project.

If you just want one particular text field to simply be limited to say "4", and that's that...

class PinCodeEntry: UITextField {

    override func didMoveToSuperview() {

        super.didMoveToSuperview()
        addTarget(self, action: #selector(fixMe), for: .editingChanged)
    }

    @objc private func fixMe() { text = text?.prefix(4) }
}

That's all there is to it.

(Here's a similar very useful tip relating to UITextView,
https://stackoverflow.com/a/42333832/294884 )


问:
Reusing Complex Object Instances in PHP
Is there a reasonable way to ensure that you aren't unnecessarily re-instantiating expensive object instances in PHP?

I have an application that deal with US States.  Each state is an instance of the USState class.  I'd like to ensure that the application only ever has one instance of each state object, although they are used in many places throughout the application.

I looked into the singleton pattern, but that seems to be used for times when a class only has a single instance - here there are 50 instances, but no more.

I guess I could put them in the global scope and always refer to them that way (global $california), but that seems wrong.

答: I would use Service Locator Pattern or Dependency Injection, which is provided by your framework. Usually I go with Zend Framework, but not knowing your circumstances, I assume you have no framework at all. In this case I would suggest very simple Dependency Injection Container, but that would add a dependency on DIC itself. Pimple is one of them.</p>

Title: Reusing Complex Object Instances in PHP


答:
The problem you have with that is the culture definition on your PC or server, if the delimitator are ',' the sistem interpret '.' as a char.

Use like this:

```<code>        double vValue;
        string[] vValuesString = vLines[j].Split(',');
        double[] vValuesDouble = new double[vValuesString.Length];

        for (int x = 0; x < vValuesString.Length; x++)
            if (double.TryParse(vValuesString[x], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out vValue))
                return; 'or use' continue;'or use' vValuesDouble[x] = 0;
            else vValuesDouble[x] = vValue;
</code>```

NOTES:

Instance your 'double[] vValuesDouble = new double[vValuesString.Length];', you can't asing a value to a null array.

When you use a TryParce the out var return with the result of convert string to a double, you don't need to re-convert it again.

Never declare variable in a loop, it get declare and instace every run of loop.

TryParce return a bool value that indicates the result of convert you don't need declare and instance a var, just use it in a if.

Use some protocol to define your variable's name.

Try to resume your code the most posible you can.

I put the entire using System.Globalization, but you can declare the using on top or define your System.Globalization for your entire aplication.

And last, sorry for my english, is not my first languaje.

Best.

Body:
I'm trying to convert a string (ex. "0.20055") to its equivalent double.

I already know that for some reason that string does not contain a valid double, but I don't understand why.

I really need to be able to convert this string to a double... Could anyone explain me why it's not a valid double? And how to fix this?

Here is some of my code:

double[] values_in_double = null;
string[] values_in_string = lines[j].Split(',');
for(int x=0; x < numCols; x++)
{
    double val;
    bool r = double.TryParse(values_in_string[x],out val);
    if (!r)
        return;
    values_in_double[x] = Convert.ToDouble(values_in_string[x]);

}

As you can see I have a string[] of lines, in which a line is like:

0.20055,0.37951,0.39641,2.0472,32.351,0.38825,0.24976,1.3305,1.1389,0.50494

and I split them. But then I need to convert each one to a double value.

Body:
The problem you have with that is the culture definition on your PC or server, if the delimitator are ',' the sistem interpret '.' as a char.

Use like this:

        double vValue;
        string[] vValuesString = vLines[j].Split(',');
        double[] vValuesDouble = new double[vValuesString.Length];

        for (int x = 0; x < vValuesString.Length; x++)
            if (double.TryParse(vValuesString[x], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out vValue))
                return; 'or use' continue;'or use' vValuesDouble[x] = 0;
            else vValuesDouble[x] = vValue;

NOTES:

Instance your 'double[] vValuesDouble = new double[vValuesString.Length];', you can't asing a value to a null array.

When you use a TryParce the out var return with the result of convert string to a double, you don't need to re-convert it again.

Never declare variable in a loop, it get declare and instace every run of loop.

TryParce return a bool value that indicates the result of convert you don't need declare and instance a var, just use it in a if.

Use some protocol to define your variable's name.

Try to resume your code the most posible you can.

I put the entire using System.Globalization, but you can declare the using on top or define your System.Globalization for your entire aplication.

And last, sorry for my english, is not my first languaje.

Best.


问:
grid items click event not working on small screes like mobile
I displayed a grid items in a div which is toggled to show and hide the items,
In desktop and tablets it is working good, but in mobile devices the items button click event is not working.
In desktop when i mouse over the grid item it will change its color to blue and cursor to pointer.

sample code of this grid is as follow

```<code><div class="items_grid" style="width: 50%; float: right; height: 320px; overflow-x: hidden; overflow-y: auto; position: absolute; z-index: 10; top: 0px; right: 0px; border: 1px solid rgb(219, 219, 219); display: block;">
            <div class="col-md-12 col-sm-12 col-xs-12 div_padding">
                    <div class="form-group col-md-12 col-sm-12 col-xs-12" style="background-color:#DADADA;color:#000000;border:1px solid #DADADA;">
                    <center><form class="form-inline" style="padding:0px;margin-bottom:1px;">
                        <select class="form-control" name="menucategory" onchange="getbycategory(this.value)">
                        <option value="0">--Select Category/All--</option>
                        <option value="1">ABC</option>
                        </select>
                    </form></center>
                    </div>
                </div>
                <div id="menu_items">
                <div class="col-md-2 col-sm-3 col-xs-6 itm">
                <button class="btn btn-primary itm_btn" id="itmname" onclick="insertitem('1527')">Comma Hoox Powerbank 6000</button>
                </div>
                <div class="col-md-2 col-sm-3 col-xs-6 itm">
                <button class="btn btn-primary itm_btn" id="itmname" onclick="insertitem('4002')">Epay</button>
                </div>
                <div class="col-md-2 col-sm-3 col-xs-6 itm">
                <button class="btn btn-primary itm_btn" id="itmname" onclick="insertitem('2')">Fees - 1st Installment</button>
                </div>

                <div class="row" style="background-color:#f5f5f5;">
                <div class="col-md-12 col-sm-12" style="padding-top:2px;">
                        <div class="col-md-6 col-sm-6" id="p_page"><button class="btn btn-primary btn-block pagenation disable" onclick="pagination(,0)"> << </button></div>
                        <div class="col-md-6 col-sm-6" id="n_page"><button class="btn btn-primary btn-block pagenation" onclick="pagination(12,0)"> >> </button>
</div>
                    </div>
                </div>
            </div>
</code>```

sample js

```<code>    function insertitem(invcode)
        {
            if(invcode=='')
           {
               alert("no item");
            }
    else
    {
      //some function
    }
}
</code>```

答:
Note: Never nest col within col and cols should always be inside rows.

By the way, placing

```<code><div class="clearfix"></div>
</code>```

after the last item should clear floats and fix this issue.

Body:
I displayed a grid items in a div which is toggled to show and hide the items,
In desktop and tablets it is working good, but in mobile devices the items button click event is not working.
In desktop when i mouse over the grid item it will change its color to blue and cursor to pointer.

sample code of this grid is as follow

                    <form class="form-inline" style="padding:0px;margin-bottom:1px;">
                        <select class="form-control" name="menucategory" onchange="getbycategory(this.value)">
                        <option value="0">--Select Category/All--</option>
                        <option value="1">ABC</option>
                        </select>
                    </form>

                <button class="btn btn-primary itm_btn" id="itmname" onclick="insertitem('1527')">Comma Hoox Powerbank 6000</button>

                <button class="btn btn-primary itm_btn" id="itmname" onclick="insertitem('4002')">Epay</button>

                <button class="btn btn-primary itm_btn" id="itmname" onclick="insertitem('2')">Fees - 1st Installment</button>

<button class="btn btn-primary btn-block pagenation disable" onclick="pagination(,0)"> << </button>

<button class="btn btn-primary btn-block pagenation" onclick="pagination(12,0)"> >> </button>

sample js

    function insertitem(invcode)
        {
            if(invcode=='')
           {
               alert("no item");
            }
    else
    {
      //some function
    }
}

Body:
Note: Never nest col within col and cols should always be inside rows.

By the way, placing

<div class="clearfix"></div>

after the last item should clear floats and fix this issue.


问:
mylib.so has text relocations. This is wasting memory and is a security risk. Please fix
My Android application (using native library) print this warning on Android 4.4 :

linker      mylib.so has text relocations. This is wasting memory and is a security risk. Please fix.

Have you got an idea of what it is and how to fix it ?
Thanks,

答:
In short, you need to compile your library with one of the -fpic or -fPIC flags, where PIC is an abbreviation for Position Independent Code.

The longer answer is that your yourlib.so has been compiled in a manner that does not conform to the Google Android standard for an ELF file, where this Dynamic Array Tag entry is unexpected. In the best case the library will still run, but it is still an error and future AOS version will probably not allow it to run.

DT_TEXTREL    0x16 (22)

To check whats in you library use something along the line of:

```<code># readelf --wide -S yourlib.so

There are 37 section headers, starting at offset 0x40:

Section Headers:
  [Nr] Name              Type            Address          Off    Size   ES Flg Lk Inf Al
  [ 0]                   NULL            0000000000000000 000000 000000 00      0   0  0
  [ 1] .text             PROGBITS        0000000000000000 002400 068f80 00  AX  0   0 16
  [ 2] .rodata           PROGBITS        0000000000000000 06b380 05ad00 00  WA  0   0 32
  ...
  [16] .rela.text        RELA            0000000000000000 26b8e8 023040 18     14   1  8
  ...
  [36] .rela.debug_frame RELA            0000000000000000 25a608 0112e0 18     14  27  8

Key to Flags:
  W (write), A (alloc), X (execute), M (merge), S (strings), l (large)
  I (info), L (link order), G (group), T (TLS), E (exclude), x (unknown)
  O (extra OS processing required) o (OS specific), p (processor specific)
</code>```

Please see my extensive answer on the topic, for more DT entry details. For details how to write proper dynamic libraries this is a must-read.

Body:
In short, you need to compile your library with one of the -fpic or -fPIC flags, where PIC is an abbreviation for Position Independent Code.

The longer answer is that your yourlib.so has been compiled in a manner that does not conform to the Google Android standard for an ELF file, where this Dynamic Array Tag entry is unexpected. In the best case the library will still run, but it is still an error and future AOS version will probably not allow it to run.

DT_TEXTREL    0x16 (22)

To check whats in you library use something along the line of:

# readelf --wide -S yourlib.so

There are 37 section headers, starting at offset 0x40:

Section Headers:
  [Nr] Name              Type            Address          Off    Size   ES Flg Lk Inf Al
  [ 0]                   NULL            0000000000000000 000000 000000 00      0   0  0
  [ 1] .text             PROGBITS        0000000000000000 002400 068f80 00  AX  0   0 16
  [ 2] .rodata           PROGBITS        0000000000000000 06b380 05ad00 00  WA  0   0 32
  ...
  [16] .rela.text        RELA            0000000000000000 26b8e8 023040 18     14   1  8
  ...
  [36] .rela.debug_frame RELA            0000000000000000 25a608 0112e0 18     14  27  8

Key to Flags:
  W (write), A (alloc), X (execute), M (merge), S (strings), l (large)
  I (info), L (link order), G (group), T (TLS), E (exclude), x (unknown)
  O (extra OS processing required) o (OS specific), p (processor specific)

Please see my extensive answer on the topic, for more DT entry details. For details how to write proper dynamic libraries this is a must-read.


问:
preg_match expression for phone numbers
I want to display an error message if the number doesn't match any number with hyphen, plus sign, space or brackets. No numbers either.

For example:

```<code>(012) 123 4567
(012)-123-4567
012-345-6789
123 123 1234
+12 23 213 3456
</code>```

The above examples all work with this expression:

```<code>if (!preg_match("/^[0-9\-]|[\+0-9]|[0-9\s]|[0-9()]*$/", $_POST['tel'])) {
    $telErr = "Invalid contact number";
}
</code>```

But it allows letters, which I do not want.

Example:

```<code>+00000000a
</code>```

The above example is accepted by the expression I have.

Please can someone help me with this.

答:
I first cleanup the string a bit (that avoids useless matches):

```<code>$input = preg_replace('/[^0-9+\(\)-]/', '', $_POST['tel']);
</code>```

I than match an american number +1 (xxx) xxx-xxxx;

```<code>if(preg_match('/^(\+1|001)?\(?([0-9]{3})\)?([ .-]?)([0-9]{3})([ .-]?)([0-9]{4})/',$input))
        $result = "match: USA";

else    $result = "no match";
</code>```

this allows for quite some input configurations - only your last number would not match (if I'd not do the cleanup first, not because of the international code which is matched, but because of the split in the area-code) all the others go also without cleanup.

Title: preg_match expression for phone numbers

Body:
I want to display an error message if the number doesn't match any number with hyphen, plus sign, space or brackets. No numbers either.

For example:

(012) 123 4567
(012)-123-4567
012-345-6789
123 123 1234
+12 23 213 3456

The above examples all work with this expression:

if (!preg_match("/^[0-9\-]|[\+0-9]|[0-9\s]|[0-9()]*$/", $_POST['tel'])) {
    $telErr = "Invalid contact number";
}

But it allows letters, which I do not want.

Example:

+00000000a

The above example is accepted by the expression I have.

Please can someone help me with this.

Body:
I first cleanup the string a bit (that avoids useless matches):

$input = preg_replace('/[^0-9+\(\)-]/', '', $_POST['tel']);

I than match an american number +1 (xxx) xxx-xxxx;

if(preg_match('/^(\+1|001)?\(?([0-9]{3})\)?([ .-]?)([0-9]{3})([ .-]?)([0-9]{4})/',$input))
        $result = "match: USA";

else    $result = "no match";

this allows for quite some input configurations - only your last number would not match (if I'd not do the cleanup first, not because of the international code which is matched, but because of the split in the area-code) all the others go also without cleanup.


问:
Adding images to EditText from Custom IME
I'm working on a custom keyboard for Android, and I'm running into a problem. I need to either be able to output ASCII characters from the keyboard (i.e. ∅, ⌲, ⌓, etc), or be able to add images to the selected EditText from my keyboard. I know this is possible because Emoji does it with their keyboard. They have found a way to add images to any EditText, whether they created the EditText or not.

Does anyone have any idea how they accomplished this?

答:
I came across this thread during some research and ended up elsewhere. Yes it is now possible to send images/GIF's to EditText's via a custom IME using the new CommitContent API introduced in 7.1 with backward compatibility till API level 13 - Honeycomb.

Quote from :
https://developer.android.com/guide/topics/text/image-keyboard.html#how_it_works

With Android 7.1 (API level 25), the Android SDK includes the Commit
  Content API, which provides a universal way for IMEs to send images
  and other rich content directly to a text editor in an app. The API is
  also available in v13 Support Library as of revision 25.0.0. We
  recommend using the Support Library because it runs on devices as
  early as Android 3.2 (API Level 13), and it contains helper methods
  that simplify implementation.

I tested this with the latest update of hangouts and it works!.

Sample code here: https://developer.android.com/about/versions/nougat/android-7.1-samples.html#img-kbd-ime

I have merged the main app and the IME app code to a single project and here it is : https://github.com/satheeshwaran/ImageKeyboard-Android/tree/master

UPDATE:

I have published two apps using this API and I think they are doing good,

https://play.google.com/store/apps/details?id=com.theweekendparty.indianmemekeyboard

https://play.google.com/store/apps/details?id=com.theweekendparty.indiangifboardbollywood


问:
i am trying to code in c sharp and i have a 3D array like this
i am trying to code in c sharp and i have a 3D array like this:

1 7 13

3 9 15

5 11 17

here is my code:

```<code> int row = 3;
            int col = 3;
            int[,] times;
            times = new int[col, row];
            string matrixstring = " ";
            int mult = -1;

            for (int j = 0; j != row; j++)
            {
                for (int i = 0; i != col; i++)
                {
                    mult = mult + 2;
                    matrixstring += mult.ToString();
                    matrixstring += " ";
                }
                    matrixstring += Environment.NewLine;
                }
                this.richTextBox1.Text = matrixstring;
</code>```

i got output :

1  3 5

7  9 11

13 15 17

so whats the problem in my code..?

答:
First, in a C# 2D array the first dimension would be considered the row, the second would be the column. So i would reverse the names in the times array definition. Also, assuming you want the times array for later use, you could populate it by going down the columns first, but then pivot it by outputing the rows first. Like this:

```<code>int row = 3;
int col = 3;
int[,] times = new int[row, col];
int mult = -1;

for (int c = 0; c < col; c++)
    for (int r = 0; r < row; r++)
    {
        mult += 2;
        times[r,c] = mult;
    }

string matrixstring = "";

for (int r = 0; r < row; r++)
{
    for (int c = 0; c < col; c++)
        matrixstring += times[r,c].ToString() + " ";

    matrixstring += Environment.NewLine;
}

this.richTextBox1.Text = matrixstring;
</code>```

Notice the order of the two for loops.

Body:
i am trying to code in c sharp and i have a 3D array like this:

1 7 13

3 9 15

5 11 17

here is my code:

 int row = 3;
            int col = 3;
            int[,] times;
            times = new int[col, row];
            string matrixstring = " ";
            int mult = -1;

            for (int j = 0; j != row; j++)
            {
                for (int i = 0; i != col; i++)
                {
                    mult = mult + 2;
                    matrixstring += mult.ToString();
                    matrixstring += " ";
                }
                    matrixstring += Environment.NewLine;
                }
                this.richTextBox1.Text = matrixstring;

i got output :

1  3 5

7  9 11

13 15 17

so whats the problem in my code..?

Body:
First, in a C# 2D array the first dimension would be considered the row, the second would be the column. So i would reverse the names in the times array definition. Also, assuming you want the times array for later use, you could populate it by going down the columns first, but then pivot it by outputing the rows first. Like this:

int row = 3;
int col = 3;
int[,] times = new int[row, col];
int mult = -1;

for (int c = 0; c < col; c++)
    for (int r = 0; r < row; r++)
    {
        mult += 2;
        times[r,c] = mult;
    }

string matrixstring = "";

for (int r = 0; r < row; r++)
{
    for (int c = 0; c < col; c++)
        matrixstring += times[r,c].ToString() + " ";

    matrixstring += Environment.NewLine;
}

this.richTextBox1.Text = matrixstring;

Notice the order of the two for loops.


问:
Decompress Gzip file and store in variable
I have searched a lot for conversion from byte to string but my query is a little different, please read ahead.

Currently i have a gzip file which i can decompress using the code from http://www.mkyong.com/java/how-to-decompress-file-from-gzip-file/.
This code helps me store my decompressed output in a file, but how do i store it in a variable? I am using this code currently:

```<code>public String unGunzipFile(String compressedFile, String decompressedFile) {

        byte[] buffer = new byte[1024];

        try {

            FileInputStream fileIn = new FileInputStream(compressedFile);

            GZIPInputStream gZIPInputStream = new GZIPInputStream(fileIn);

            FileOutputStream fileOutputStream = new FileOutputStream(decompressedFile);
            StringBuffer str = new StringBuffer();
            int bytes_read;
            while ((bytes_read = gZIPInputStream.read(buffer)) > 0) {

                String s = new String(buffer);
                str.append(s);
                fileOutputStream.write(buffer, 0, bytes_read);
            }

            gZIPInputStream.close();
            fileOutputStream.close();

            System.out.println("The file was decompressed successfully!");
            System.out.println(str);
            String final_string = str.toString();
            return final_string;

        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
    }
</code>```

Since i am converting bytes to string near the end when bytes_read is not 1024 in length i end up getting some weird data in my StringBuffer, but in the file there is no such data since fileOutputStream.write(buffer, 0, bytes_read); limits it to writing the updated part.
How do i fix this?

Thanks in advance.

答:
Instead of using String s = new String(buffer), i suggest use

public String(byte[] bytes,
      int offset,
      int length)

which might help you.

Body:
I have searched a lot for conversion from byte to string but my query is a little different, please read ahead.

Currently i have a gzip file which i can decompress using the code from http://www.mkyong.com/java/how-to-decompress-file-from-gzip-file/.
This code helps me store my decompressed output in a file, but how do i store it in a variable? I am using this code currently:

public String unGunzipFile(String compressedFile, String decompressedFile) {

        byte[] buffer = new byte[1024];

        try {

            FileInputStream fileIn = new FileInputStream(compressedFile);

            GZIPInputStream gZIPInputStream = new GZIPInputStream(fileIn);

            FileOutputStream fileOutputStream = new FileOutputStream(decompressedFile);
            StringBuffer str = new StringBuffer();
            int bytes_read;
            while ((bytes_read = gZIPInputStream.read(buffer)) > 0) {

                String s = new String(buffer);
                str.append(s);
                fileOutputStream.write(buffer, 0, bytes_read);
            }

            gZIPInputStream.close();
            fileOutputStream.close();

            System.out.println("The file was decompressed successfully!");
            System.out.println(str);
            String final_string = str.toString();
            return final_string;

        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
    }

Since i am converting bytes to string near the end when bytes_read is not 1024 in length i end up getting some weird data in my StringBuffer, but in the file there is no such data since fileOutputStream.write(buffer, 0, bytes_read); limits it to writing the updated part.
How do i fix this?

Thanks in advance.


问:
Keep only one copy of each ClickOnce dependency?
I'm publishing a ClickOnce application that has a few dependencies in the form of DLLs. When I publish the initial version 0.0.1 all the dependencies are copied into the deployment folder as I would expect.

If I make an update and publish version 0.0.2 all of the same dependencies, which are unchanged and have the same file hash, are copied into a second subfolder within the deployment folder.

The folder structure looks like this:

```<code>deployment/
    MyApplication.application
    setup.exe

    Application Files/
        MyApplication_1_0_0_1/
            Dll_A.dll - Hash: 0x111111111111111
            Dll_B.dll - Hash: 0x222222222222222

        MyApplication_1_0_0_2/
            Dll_A.dll - Hash: 0x111111111111111
            Dll_B.dll - Hash: 0x222222222222222
</code>```

Is there any way to only have one copy of Dll_A.dll/Dll_B.dll when they are the same file and only have a new copy if they change?

I'm referring to the size of the directory on the developer's end. Not the size of the download and cache that clients have as I understand ClickOnce already takes care to minimize that.

答:
I don't believe ClickOnce allows for that granular of control.

Edit:
Found this, it may help with your question on the cleanup.
ClickOnce deployment is leaving multiple versions (yes, more than two)

Body:
I'm publishing a ClickOnce application that has a few dependencies in the form of DLLs. When I publish the initial version 0.0.1 all the dependencies are copied into the deployment folder as I would expect.

If I make an update and publish version 0.0.2 all of the same dependencies, which are unchanged and have the same file hash, are copied into a second subfolder within the deployment folder.

The folder structure looks like this:

deployment/
    MyApplication.application
    setup.exe

    Application Files/
        MyApplication_1_0_0_1/
            Dll_A.dll - Hash: 0x111111111111111
            Dll_B.dll - Hash: 0x222222222222222

        MyApplication_1_0_0_2/
            Dll_A.dll - Hash: 0x111111111111111
            Dll_B.dll - Hash: 0x222222222222222

Is there any way to only have one copy of Dll_A.dll/Dll_B.dll when they are the same file and only have a new copy if they change?

I'm referring to the size of the directory on the developer's end. Not the size of the download and cache that clients have as I understand ClickOnce already takes care to minimize that.


问:
Device Tree Overlay naming
I'm seeing a curious problem when trying to load device tree overlays on a Beaglebone black. The loader fails to load the .dtbo file because it is looking for a file with a name different to the one it has been told to load. The .dts file was compiled on the same device using the command:

dtc -O dtb -o TEST-DT-00A0.dtbo -b 0 -@ TEST-DT-00A0.dts

The compilation completed without errors but when I attempt to load the binary using:

echo TEST-DT-00A0.dtbo > /sys/devices/bone_capemgr.9/slots

I see the error:

-bash: echo: write error: No such file or directory

Examining the reason for the failure using dmesg reveals that the loader was attempting to load a file with the name (-0 inserted into the file name):

TEST-DT-0-00A0.dtbo

Sure enough, if I rename the .dtbo file to the name expected by the loader it loads correctly and works just fine.

Does anyone have any idea why the extra '-0' was added to the name by the device tree loader? On a second Beaglebone, the loader was expecting the file to be named TEST-DT-00-00A0.dtbo (-00 added to the name).

If it helps, here's the output from uname:

Linux beaglebone 3.8.13-bone79 #1 SMP Tue Oct 13 20:44:55 UTC 2015 armv7l GNU/Linux

Thanks for any help!

答:
It appears the device tree loader is a little simplistic and assumes the filename has exactly 16 characters in its name. If the device tree fragment does not have a 16 character name then various level of padding or truncation can occur when the fragment is loaded.

The correct thing then would be for the above fragment to be renamed to something like:

TEST-DT-12345678-00A0.dtbo

(16 characters before the -00A0.dtbo)

Then this would load correctly with the device tree loader mangling the name.

Also, be wary of trying to load a file with a path:

echo /lib/firmware/TEST-DT-12345678-00A0.dtbo > /sys/devices/bone_capemgr.*/slots

The characters in the path will count towards the 16 character expected name length resulting in the device tree loader attempting to load the fragment:

TE-00A0.dtbo

If you are experiencing 'No such file or directory' errors when trying to load a fragment, be sure to check dmesg!

Title: Device Tree Overlay naming


问:
Using beach ball maps (focal mechanism) in Python
I'm very new to focal mechanisms (beach balls) and would like to plot these on to a global map using Python.

I already have installed the Anaconda suite, and would like to know if I need to install any further modules to get this working (i.e. is the obspy module included in the Anaconda suite?

I won't be using any specific seismology files as input, but would simply like to create these beach balls by just manually inserting the corresponding parameters. So far I've come across two different examples of code:

```<code>from obspy.imaging.beachball import beachball
np1 = [150, 87, 1]
beachball(np1)
</code>```

and...

```<code>from obspy.imaging.beachball import beachball
mt = [-2.39, 1.04, 1.35, 0.57, -2.94, -0.94]
beachball(mt)
</code>```

It is not clear to me what each of these values refer to. I have an example of a site where I'd like to retrieve the relevant information from, then use these values as input for the beach ball:

http://earthquake.usgs.gov/earthquakes/eventpage/us20005ysu#moment-tensor

Thanks in advance.

答:
Our Tutorial has examples of map plots including beachball patches:

http://docs.obspy.org/tutorial/code_snippets/basemap_plot_with_beachballs.html#basemap-plot-of-the-globe

Or check out our more up-to-date master branch Tutorial:

http://docs.obspy.org/master/tutorial/code_snippets/basemap_plot_with_beachballs.html

Pimping those examples you find there a bit you can arrive at this piece of code to plot moment tensors on a basemap (projection can be changed to your liking of course):

```<code>import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

from obspy import read_events
from obspy.imaging.beachball import beach

event = read_events(
    'https://earthquake.usgs.gov/archive/product/moment-tensor/'
    'us_20005ysu_mww/us/1470868224040/quakeml.xml', format='QUAKEML')[0]
origin = event.preferred_origin() or event.origins[0]
focmec = event.preferred_focal_mechanism() or event.focal_mechanisms[0]
tensor = focmec.moment_tensor.tensor
moment_list = [tensor.m_rr, tensor.m_tt, tensor.m_pp,
               tensor.m_rt, tensor.m_rp, tensor.m_tp]

m = Basemap(projection='cyl', lon_0=origin.longitude, lat_0=origin.latitude,
            resolution='c')

m.drawcoastlines()
m.fillcontinents()
m.drawparallels(np.arange(-90., 120., 30.))
m.drawmeridians(np.arange(0., 420., 60.))
m.drawmapboundary()

x, y = m(origin.longitude, origin.latitude)

ax = plt.gca()
b = beach(moment_list, xy=(x, y), width=20, linewidth=1, alpha=0.85)
b.set_zorder(10)
ax.add_collection(b)
plt.show()
</code>```

You'll need the basemap package installed for this (conda install basemap).

Body:
I'm very new to focal mechanisms (beach balls) and would like to plot these on to a global map using Python.

I already have installed the Anaconda suite, and would like to know if I need to install any further modules to get this working (i.e. is the obspy module included in the Anaconda suite?

I won't be using any specific seismology files as input, but would simply like to create these beach balls by just manually inserting the corresponding parameters. So far I've come across two different examples of code:

from obspy.imaging.beachball import beachball
np1 = [150, 87, 1]
beachball(np1)

and...

from obspy.imaging.beachball import beachball
mt = [-2.39, 1.04, 1.35, 0.57, -2.94, -0.94]
beachball(mt)

It is not clear to me what each of these values refer to. I have an example of a site where I'd like to retrieve the relevant information from, then use these values as input for the beach ball:

http://earthquake.usgs.gov/earthquakes/eventpage/us20005ysu#moment-tensor

Thanks in advance.

Body:
Our Tutorial has examples of map plots including beachball patches:

http://docs.obspy.org/tutorial/code_snippets/basemap_plot_with_beachballs.html#basemap-plot-of-the-globe

Or check out our more up-to-date master branch Tutorial:

http://docs.obspy.org/master/tutorial/code_snippets/basemap_plot_with_beachballs.html

Pimping those examples you find there a bit you can arrive at this piece of code to plot moment tensors on a basemap (projection can be changed to your liking of course):

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

from obspy import read_events
from obspy.imaging.beachball import beach

event = read_events(
    'https://earthquake.usgs.gov/archive/product/moment-tensor/'
    'us_20005ysu_mww/us/1470868224040/quakeml.xml', format='QUAKEML')[0]
origin = event.preferred_origin() or event.origins[0]
focmec = event.preferred_focal_mechanism() or event.focal_mechanisms[0]
tensor = focmec.moment_tensor.tensor
moment_list = [tensor.m_rr, tensor.m_tt, tensor.m_pp,
               tensor.m_rt, tensor.m_rp, tensor.m_tp]

m = Basemap(projection='cyl', lon_0=origin.longitude, lat_0=origin.latitude,
            resolution='c')

m.drawcoastlines()
m.fillcontinents()
m.drawparallels(np.arange(-90., 120., 30.))
m.drawmeridians(np.arange(0., 420., 60.))
m.drawmapboundary()

x, y = m(origin.longitude, origin.latitude)

ax = plt.gca()
b = beach(moment_list, xy=(x, y), width=20, linewidth=1, alpha=0.85)
b.set_zorder(10)
ax.add_collection(b)
plt.show()

You'll need the basemap package installed for this (conda install basemap).


问:
UIView should be transparent but only shows white
I have a UIViewController which contains a label and button. I would like the background of the view to be transparent so I set it to clearColor and opaque = NO.

However, the view always displays a white background. How can I fix this?

Thanks.

答:
Sorry, I do not have enough rep to comment on Rog's answer, so I will post 'Another Answer'.

Try this code and see if it turns out well for you:

```<code>UIVIew *view = [[UIView alloc] init];
view.alpha = 0; // alpha 1.0 is opaque, alpha 0.5 is translucent and 0 is clear
</code>```

Honestly, I have not tried that before as I do not require doing so. But when I drag a new UIView from the library, alpha option is in the properties.

Hope this helps.

Body:
Sorry, I do not have enough rep to comment on Rog's answer, so I will post 'Another Answer'.

Try this code and see if it turns out well for you:

UIVIew *view = [[UIView alloc] init];
view.alpha = 0; // alpha 1.0 is opaque, alpha 0.5 is translucent and 0 is clear

Honestly, I have not tried that before as I do not require doing so. But when I drag a new UIView from the library, alpha option is in the properties.

Hope this helps.