问:
How to scale on high-DPI the image of a Windows Form Button?
I cannot find a way to make scale the image in a Windows Form Button. See below what it looks like with the Windows Form designer shown on DPI 200% (I am aware that the Windows Form designer should be only used on DPI 100% / 96, this screenshot just illustrates properly my point).

While the button size get scaled properly (34x33), the image in the button size doesn't get scaled/stretched/zoomed (it remains 16x16). I did many attempt to solve this:

The parent control AutoScaleMode is set to Font, setting it to Dpi doesn't make this work.

Setting button AutoSize to true or false doesn't make it work.

Setting button or parent controlAutoSizeMode to any value doesn't make it work.

there is no Button.ImageLayout that could be set to Stretch or Zoom.

Using the new App.Config setting <add key="EnableWindowsFormsHighDpiAutoResizing" value="true" /> doesn't make it work.

Changing button FlatStyle or ImageAlign doesn't make it work.

How did you get solved this in your app?

答:
Here is a ready to use helper class based on the accepted answer that includes retrieval of the DPI scale, and adds support of PictureBox image scaling:</p>

```<code>public static class HighDpiHelper
{
    public static void AdjustControlImagesDpiScale(Control container)
    {
        var dpiScale = GetDpiScale(container).Value;
        if (CloseToOne(dpiScale))
            return;

        AdjustControlImagesDpiScale(container.Controls, dpiScale);
    }

    private static void AdjustButtonImageDpiScale(ButtonBase button, float dpiScale)
    {
        var image = button.Image;
        if (image == null)
            return;

        button.Image = ScaleImage(image, dpiScale);
    }

    private static void AdjustControlImagesDpiScale(Control.ControlCollection controls, float dpiScale)
    {
        foreach (Control control in controls)
        {
            var button = control as ButtonBase;
            if (button != null)
                AdjustButtonImageDpiScale(button, dpiScale);
            else
            {
                var pictureBox = control as PictureBox;
                if (pictureBox != null)
                    AdjustPictureBoxDpiScale(pictureBox, dpiScale);
            }

            AdjustControlImagesDpiScale(control.Controls, dpiScale);
        }
    }

    private static void AdjustPictureBoxDpiScale(PictureBox pictureBox, float dpiScale)
    {
        var image = pictureBox.Image;
        if (image == null)
            return;

        if (pictureBox.SizeMode == PictureBoxSizeMode.CenterImage)
            pictureBox.Image = ScaleImage(pictureBox.Image, dpiScale);
    }

    private static bool CloseToOne(float dpiScale)
    {
        return Math.Abs(dpiScale - 1) < 0.001;
    }

    private static Lazy<float> GetDpiScale(Control control)
    {
        return new Lazy<float>(() =>
        {
            using (var graphics = control.CreateGraphics())
                return graphics.DpiX / 96.0f;
        });
    }

    private static Image ScaleImage(Image image, float dpiScale)
    {
        var newSize = ScaleSize(image.Size, dpiScale);
        var newBitmap = new Bitmap(newSize.Width, newSize.Height);

        using (var g = Graphics.FromImage(newBitmap))
        {
            // According to this blog post http://blogs.msdn.com/b/visualstudio/archive/2014/03/19/improving-high-dpi-support-for-visual-studio-2013.aspx
            // NearestNeighbor is more adapted for 200% and 200%+ DPI

            var interpolationMode = InterpolationMode.HighQualityBicubic;
            if (dpiScale >= 2.0f)
                interpolationMode = InterpolationMode.NearestNeighbor;

            g.InterpolationMode = interpolationMode;
            g.DrawImage(image, new Rectangle(new Point(), newSize));
        }

        return newBitmap;
    }

    private static Size ScaleSize(Size size, float scale)
    {
        return new Size((int)(size.Width * scale), (int)(size.Height * scale));
    }
}
</code>```

Body:
Here is a ready to use helper class based on the accepted answer that includes retrieval of the DPI scale, and adds support of PictureBox image scaling:

public static class HighDpiHelper
{
    public static void AdjustControlImagesDpiScale(Control container)
    {
        var dpiScale = GetDpiScale(container).Value;
        if (CloseToOne(dpiScale))
            return;

        AdjustControlImagesDpiScale(container.Controls, dpiScale);
    }

    private static void AdjustButtonImageDpiScale(ButtonBase button, float dpiScale)
    {
        var image = button.Image;
        if (image == null)
            return;

        button.Image = ScaleImage(image, dpiScale);
    }

    private static void AdjustControlImagesDpiScale(Control.ControlCollection controls, float dpiScale)
    {
        foreach (Control control in controls)
        {
            var button = control as ButtonBase;
            if (button != null)
                AdjustButtonImageDpiScale(button, dpiScale);
            else
            {
                var pictureBox = control as PictureBox;
                if (pictureBox != null)
                    AdjustPictureBoxDpiScale(pictureBox, dpiScale);
            }

            AdjustControlImagesDpiScale(control.Controls, dpiScale);
        }
    }

    private static void AdjustPictureBoxDpiScale(PictureBox pictureBox, float dpiScale)
    {
        var image = pictureBox.Image;
        if (image == null)
            return;

        if (pictureBox.SizeMode == PictureBoxSizeMode.CenterImage)
            pictureBox.Image = ScaleImage(pictureBox.Image, dpiScale);
    }

    private static bool CloseToOne(float dpiScale)
    {
        return Math.Abs(dpiScale - 1) < 0.001;
    }

    private static Lazy<float> GetDpiScale(Control control)
    {
        return new Lazy<float>(() =>
        {
            using (var graphics = control.CreateGraphics())
                return graphics.DpiX / 96.0f;
        });
    }

    private static Image ScaleImage(Image image, float dpiScale)
    {
        var newSize = ScaleSize(image.Size, dpiScale);
        var newBitmap = new Bitmap(newSize.Width, newSize.Height);

        using (var g = Graphics.FromImage(newBitmap))
        {
            // According to this blog post http://blogs.msdn.com/b/visualstudio/archive/2014/03/19/improving-high-dpi-support-for-visual-studio-2013.aspx
            // NearestNeighbor is more adapted for 200% and 200%+ DPI

            var interpolationMode = InterpolationMode.HighQualityBicubic;
            if (dpiScale >= 2.0f)
                interpolationMode = InterpolationMode.NearestNeighbor;

            g.InterpolationMode = interpolationMode;
            g.DrawImage(image, new Rectangle(new Point(), newSize));
        }

        return newBitmap;
    }

    private static Size ScaleSize(Size size, float scale)
    {
        return new Size((int)(size.Width * scale), (int)(size.Height * scale));
    }
}


来源: stackexchange

问:
String cannot be cast to org.springframework.http.ResponseEntity
While using the following code, I'm getting a ClassCastException: String
cannot be cast to org.springframework.http.ResponseEntity.

```<code>@Autowired
private  ClientService clientService;

public void methodA() {
    String url = ...
    ResponseEntity<String> resEntity = clientService.callService(url);
}
</code>```

答:
The error means:

this statement

```<code>clientService.callService(url);
</code>```

is calling the method callService which is returning an object of the class String, that is not the same type to ResponseEntity there so this is invalid:

```<code>ResponseEntity resEntity = clientService.callService(url);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
While using the following code, I'm getting a ClassCastException: String
cannot be cast to org.springframework.http.ResponseEntity.

@Autowired
private  ClientService clientService;

public void methodA() {
    String url = ...
    ResponseEntity<String> resEntity = clientService.callService(url);
}

Body:
The error means:

this statement

clientService.callService(url);

is calling the method callService which is returning an object of the class String, that is not the same type to ResponseEntity there so this is invalid:

ResponseEntity resEntity = clientService.callService(url);


问:
Question about how to become a good software (a website) tester
I am going to look for a job as a software tester (a SDET maybe), especially for website test. I have some vague impression of this area and got a couple of specific questions as below:

Among so many documents, such as functional spec, design spec, which should I pay more attention to? How to view them in a tester's view?

Any good suggestions about writing test spec?

Any attention should be paid to website test?

These are just some questions I got now, I'll update with more shortly.

I'd like to hear your voice very much. Many thanks.

答:
Credentials:  I'm an SDET with 5 years of experience, 2 of those years testing web applications.

1-  I'd say testerab has a pretty good answer.  There is no single document that you can invariably rely upon across companies or even teams within a single company.  Pay attention to whichever document has information.

I'd augment that answer with this advice:  Don't be surprised if the documentation is insufficient.  Strike up strong relationships with people who help define the product (the dev, the business owner, the program manager, etc.).  You will nearly always be relying on them for some of your specifications, since it is difficult to cover everything on paper (and, as you gain expertise as a tester, you will learn to see things that others don't notice).  Try to write down any "verbal specs" as you hear them, and ideally get any requests for specification clarification in writing or email.  Gathering them all in a public document is wise, and may help to uncover if two people have very different ideas about what the spec "ought" to be.

2-  Testerab has a good answer to this question, also, here: How Do You Keep Automated Tests in Synch With Test Plans

"1) Who reads it? 2) Who should probably read it, but currently you suspect they don't bother? (Do you know why they don't bother?) 3) What information do they need to get from it? Does it give them that info? 4) How do you currently present that information? Does that work for your readers/non-readers? 5) What sort of feedback do you need to get from the readers of your test plan? 6) Do you have any regulatory requirements that you need to satisfy with your test planning? "

Test plans, like product specs, will vary greatly depending on the needs of your group.  If you are in an Agile group you may spend very little time on your test plan, doing little more than outlining the areas you need to cover - or you might not even have a test plan at all, but just a conversation with the team about what will be sufficient testing for everyone to feel confident about making decisions about the product.  Other companies will have very specific guidelines you will need to follow.

Cem Kaner's classic book "Testing Computer Software" is slightly outdated, but still a good place to start and discusses test planning.  I'd recommend you buy a copy quite strongly, unless someone can recommend something as authoritative that is more current.  Last I heard, this was still the software testing book.

3-  I'm having a little trouble understanding this question, but will do my best.  Do you mean, what specifically will you need to know to test websites?  First, what do you mean by websites?  Do you mean web applications?  If so, you will probably need to understand server / client architecture, web services, databases and basic SQL, at least rudimentary security testing, integration testing, functional testing, and will benefit from an understanding or specialization in performance testing, load testing, more security testing, and familiarity with web GUI testing with Selenium or Watir.

Some helpful things for us to know to help you get started:

How much experience do you have, both as a developer and as a tester?  If you are just getting started in your career, what is your educational background?

How much experience do you have working with web applications, and in what roles (dev, test, PM, etc.)?

And, you might want to try asking some of these questions over at http://www.softwaretestingclub.com - this is a site for software testers to build community.  You will get a lot of good advice and support there, so long as you are active in the community, and many of the most influential software test writers hang out there.  If you do stop by there, feel free to look me up!

Hope this helps!

Edit:  Added some info to answer q. #2 and to mention Cem Kaner's book.

ContentLicense: CC BY-SA 2.5


问:
How to set horizontal progress bar based on total number of minutes in android?
Hi I want to set horizontal progress bar width based on total minutes.

For example

Total hours 7hrs 30 minutes - > 450 minutes

Xml

```<code><ProgressBar
   android:id="@+id/progress_bar_total_sleep"
   style="@style/SleepProgressFill"
   android:layout_width="270dp"
   android:layout_height="wrap_content"/>
</code>```

Please give any suggestion

答:
I think you should use try using SeekBar,

```<code><SeekBar
    android:id="@+id/seekbar"
    style="@android:style/Widget.ProgressBar.Horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:indeterminateDrawable="your drawable"
    android:progressDrawable="your drawable"
    android:thumb="your drawable" />
</code>```

you will have to set the duration id you'r getting the duration from mediaPlayer or just get the duration and put it here:

```<code>seekBar.setMax(mediaPlayer.getDuration());
</code>```

and the listener:

```<code>@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean
fromUser) {

}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {

}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {

}
</code>```

This is what you wanted or I didn't understand you...

Body:
Hi I want to set horizontal progress bar width based on total minutes.

For example

Total hours 7hrs 30 minutes - > 450 minutes

Xml

<ProgressBar
   android:id="@+id/progress_bar_total_sleep"
   style="@style/SleepProgressFill"
   android:layout_width="270dp"
   android:layout_height="wrap_content"/>

Please give any suggestion

Body:
I think you should use try using SeekBar,

<SeekBar
    android:id="@+id/seekbar"
    style="@android:style/Widget.ProgressBar.Horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:indeterminateDrawable="your drawable"
    android:progressDrawable="your drawable"
    android:thumb="your drawable" />

you will have to set the duration id you'r getting the duration from mediaPlayer or just get the duration and put it here:

seekBar.setMax(mediaPlayer.getDuration());

and the listener:

@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean
fromUser) {

}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {

}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {

}

This is what you wanted or I didn't understand you...


问:
How to read/write a boolean when implementing the Parcelable interface?
I'm trying to make an ArrayList Parcelable in order to pass to an activity a list of custom object. I start writing a myObjectList class which extends ArrayList<myObject> and implement Parcelable.

Some attributes of MyObject are boolean but Parcel don't have  any method read/writeBoolean.

What is the best way to handle this?

答:
AndroidStudio (using 2.3 atm), after implementing Parcelable on your class, you can simply hold your mouse pointer over your class name and it asks you to add the parcelable implementation:

From the four fields, it generates the following:

```<code>public class YourClass implements Parcelable{

String someString;
int someInt;
boolean someBoolean;
List<String> someList;

protected YourClass(Parcel in) {
    someString = in.readString();
    someInt = in.readInt();
    someBoolean = in.readByte() != 0;
    someList = in.createStringArrayList();
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(someString);
    dest.writeInt(someInt);
    dest.writeByte((byte) (someBoolean ? 1 : 0));
    dest.writeStringList(someList);
}

...
</code>```

Body:
AndroidStudio (using 2.3 atm), after implementing Parcelable on your class, you can simply hold your mouse pointer over your class name and it asks you to add the parcelable implementation:

From the four fields, it generates the following:

public class YourClass implements Parcelable{

String someString;
int someInt;
boolean someBoolean;
List<String> someList;

protected YourClass(Parcel in) {
    someString = in.readString();
    someInt = in.readInt();
    someBoolean = in.readByte() != 0;
    someList = in.createStringArrayList();
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(someString);
    dest.writeInt(someInt);
    dest.writeByte((byte) (someBoolean ? 1 : 0));
    dest.writeStringList(someList);
}

...


问:
How to write multiple sheets in Excel using TSMExportToXls Delphi component
I am using TSMExportToXls component for writing Excel files from data set. I am facing difficulty in writing different sheets in Excel files. It works file for single sheet. I don't know how to write in multiple sheets.
Below is my code. Any help would be appreciated.

```<code>procedure TfrmXLSExport.btnExportClick(Sender: TObject);
begin
  SMExportToXLS1.Header.Add('New Sheet Data');
  SMExportToXLS1.Execute;
end;
</code>```

I've created TTable object, populated the data in it and set it as a DataSet property of TSMExportToXls

答:
I use this code (Delphi):

```<code>procedure TFormMain.ExportExec(aDataSet: TDataSet; aSheetName: string);
var FirstTime : integer;
begin
  Inc(FirstTime);
  //use this code to delete default worksheets but only the first time instead
  //it will delete those newly created
  if FirstTime = 1 then
    XLS.DeleteDefaultSheets := True
  else
    XLS.DeleteDefaultSheets := False;

  XLS.DataSet := aDataSet;
  XLS.KeyGenerator := aSheetName;
  XLS.Execute;
end;
</code>```

And this is how I setted up the TSMExportToExcel component.

Hope this help! :D

Body:
I am using TSMExportToXls component for writing Excel files from data set. I am facing difficulty in writing different sheets in Excel files. It works file for single sheet. I don't know how to write in multiple sheets.
Below is my code. Any help would be appreciated.

procedure TfrmXLSExport.btnExportClick(Sender: TObject);
begin
  SMExportToXLS1.Header.Add('New Sheet Data');
  SMExportToXLS1.Execute;
end;

I've created TTable object, populated the data in it and set it as a DataSet property of TSMExportToXls

Body:
I use this code (Delphi):

procedure TFormMain.ExportExec(aDataSet: TDataSet; aSheetName: string);
var FirstTime : integer;
begin
  Inc(FirstTime);
  //use this code to delete default worksheets but only the first time instead
  //it will delete those newly created
  if FirstTime = 1 then
    XLS.DeleteDefaultSheets := True
  else
    XLS.DeleteDefaultSheets := False;

  XLS.DataSet := aDataSet;
  XLS.KeyGenerator := aSheetName;
  XLS.Execute;
end;

And this is how I setted up the TSMExportToExcel component.

Hope this help! :D


问:
Why is logged value of promise confusing?
Here is the code that I am using:

```<code>let myFirstPromise = new Promise((resolve, reject) => {
  setTimeout(function(){
   // alert("sdf");
    resolve("Success!"); // Yay! Everything went well!
  }, 200);
});

console.log(myFirstPromise);
</code>```

Why does the logged value display like this:

but then when I open it, it shows resolved?

Another case,
Lets say i change the 200 to 2000,
now

if i expand before 2 sec, it shows pending always, even if you expand again after 2 min.

if i expand after 2 sec, it shows resolved, and same there after.

Is there a reason it is so ?

答:
The first line you see is from the time you return the promise.

Its status is pending at that point (since it is not resolved) and it has no resolution value.

When you open it - the dev tools inspect the live promise - which means it shows the current status. Since you pressed it after more than 200ms - it is now fulfilled with the value "Success!".

Body:
Here is the code that I am using:

let myFirstPromise = new Promise((resolve, reject) => {
  setTimeout(function(){
   // alert("sdf");
    resolve("Success!"); // Yay! Everything went well!
  }, 200);
});

console.log(myFirstPromise);

Why does the logged value display like this:

but then when I open it, it shows resolved?

Another case,
Lets say i change the 200 to 2000,
now

if i expand before 2 sec, it shows pending always, even if you expand again after 2 min.

if i expand after 2 sec, it shows resolved, and same there after.

Is there a reason it is so ?


问:
Pyaudio recording wav file with soundcard gives an empty recording
I've been trying to work on a project to detect time shift between two streaming audio signals. I worked with python3, Pyaudio and I'm using a Motux828 sound card with a Neumann KU-100 microphone which takes a stereo input. So when i check my input_device_index I am the correct one which is the 4th one connnected to MOTU soundcard.

However when i record with:

```<code>import time
import pyaudio
import wave

CHUNK = 1024 * 3  # Chunk is the bytes which are currently processed
FORMAT = pyaudio.paInt16
RATE = 44100
RECORD_SECONDS = 2
WAVE_OUTPUT = "temp.wav"
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,channels=2,rate=RATE,input=True,frames_per_buffer=CHUNK,input_device_index=4)

frames = []  # np array storing all the data

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream1.read(CHUNK)
    frames.append(data1)

stream.stop_stream()
stream.close()
p.terminate()

wavef = wave.open(WAVE_OUTPUT, 'wb')  # opening the file
wavef.setnchannels(1)
wavef.setsampwidth(p.get_sample_size(FORMAT))
wavef.setframerate(RATE)
wavef.writeframes(b''.join(frames1))  # writing the data to be saved
wavef.close()
</code>```

I record a wave file with no sound, with almost no noise(naturally)

Also I can record with 3rd party softwares with the specific microphone.
It works completely, fine.

NOTE:
Sound card is 24-bit depth normally, I also tried paInt24 that records a wave file with pure noise

答:
I think u mentioned wrong variable names as i seen your code. The wrong variables are :

```<code>data = stream1.read(CHUNK)
frames.append(data1)
wavef.writeframes(b''.join(frames1))
</code>```

the correct values are :

```<code>data = stream.read(CHUNK)
frames.append(data)
wavef.writeframes(b''.join(frames))
</code>```

Body:
I've been trying to work on a project to detect time shift between two streaming audio signals. I worked with python3, Pyaudio and I'm using a Motux828 sound card with a Neumann KU-100 microphone which takes a stereo input. So when i check my input_device_index I am the correct one which is the 4th one connnected to MOTU soundcard.

However when i record with:

import time
import pyaudio
import wave

CHUNK = 1024 * 3  # Chunk is the bytes which are currently processed
FORMAT = pyaudio.paInt16
RATE = 44100
RECORD_SECONDS = 2
WAVE_OUTPUT = "temp.wav"
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,channels=2,rate=RATE,input=True,frames_per_buffer=CHUNK,input_device_index=4)

frames = []  # np array storing all the data

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream1.read(CHUNK)
    frames.append(data1)

stream.stop_stream()
stream.close()
p.terminate()

wavef = wave.open(WAVE_OUTPUT, 'wb')  # opening the file
wavef.setnchannels(1)
wavef.setsampwidth(p.get_sample_size(FORMAT))
wavef.setframerate(RATE)
wavef.writeframes(b''.join(frames1))  # writing the data to be saved
wavef.close()

I record a wave file with no sound, with almost no noise(naturally)

Also I can record with 3rd party softwares with the specific microphone.
It works completely, fine.

NOTE:
Sound card is 24-bit depth normally, I also tried paInt24 that records a wave file with pure noise

Body:
I think u mentioned wrong variable names as i seen your code. The wrong variables are :

data = stream1.read(CHUNK)
frames.append(data1)
wavef.writeframes(b''.join(frames1))

the correct values are :

data = stream.read(CHUNK)
frames.append(data)
wavef.writeframes(b''.join(frames))


问:
Replace [string : string] at specific index Swift
To replace a string at specific index from

```<code>var stringArray:[String] = ["value1", "value2", "value3", "value4"]
</code>```

We use

```<code>stringArray[2] = "new string"
</code>```

var myNewDictArray = [Dictionary< String, String> ] ()

In my case i have

```<code>key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"
  ▿ 1 key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"
  ▿ 1 key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"
  ▿ 1 key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"
  ▿ 1 key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"
  ▿ 1 key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"
</code>```

In my array

When i try to replace dictionary at specific index say 5,
It shows up error:

Swift:: Error: contextual type '[String : String]' cannot be used with
  array lit eral
          myNewDictArray[index] = ["answer", "option3"]

Code im using is

```<code>for (index, element) in myNewDictArray.enumerated() {

    if(index==5) {

        myNewDictArray[index] = ["answer", "option3"]

    }

}
</code>```

I also tried

```<code>for (index, element) in myNewDictArray.enumerated() {

    if(index==5) {

        myNewDictArray[index].value(forKey:"answer") = "option3"

    }

}
</code>```

Then error is

Swift:: Error: value of type '[String : String]' has no member 'value'
          myNewDictArray[index].value(forKey:"answer") = "option3"

答:
This data structure is not a dictionary. It is an array of dictionaries.

```<code>myNewDictArray[index] = ["answer", "option3"]
</code>```

The above doesn't work because ["answer", "option3"] is an array literal. You are assigning an array to a dictionary. So it of course won't work.

You can make it a dictionary literal by replacing the , with a ::

```<code>myNewDictArray[index] = ["answer": "option3"]
</code>```

But I suggest you to use an array of tuples to store this data:

```<code>var myTupleArray = [(String, String)]()
</code>```

Body:
To replace a string at specific index from

var stringArray:[String] = ["value1", "value2", "value3", "value4"]

We use

stringArray[2] = "new string"

var myNewDictArray = [Dictionary< String, String> ] ()

In my case i have

key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"
  ▿ 1 key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"
  ▿ 1 key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"
  ▿ 1 key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"
  ▿ 1 key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"
  ▿ 1 key/value pair
    ▿ (2 elements)
      - .0: "answer"
      - .1: "0"

In my array

When i try to replace dictionary at specific index say 5,
It shows up error:

Swift:: Error: contextual type '[String : String]' cannot be used with
  array lit eral
          myNewDictArray[index] = ["answer", "option3"]

Code im using is

for (index, element) in myNewDictArray.enumerated() {

    if(index==5) {

        myNewDictArray[index] = ["answer", "option3"]

    }

}

I also tried

for (index, element) in myNewDictArray.enumerated() {

    if(index==5) {

        myNewDictArray[index].value(forKey:"answer") = "option3"

    }

}

Then error is

Swift:: Error: value of type '[String : String]' has no member 'value'
          myNewDictArray[index].value(forKey:"answer") = "option3"

Body:
This data structure is not a dictionary. It is an array of dictionaries.

myNewDictArray[index] = ["answer", "option3"]

The above doesn't work because ["answer", "option3"] is an array literal. You are assigning an array to a dictionary. So it of course won't work.

You can make it a dictionary literal by replacing the , with a ::

myNewDictArray[index] = ["answer": "option3"]

But I suggest you to use an array of tuples to store this data:

var myTupleArray = [(String, String)]()


问:
how to fix bug laravel validator with Post man send API. Validator return redirect uri root path. it not errors json status 422
how to fix bug laravel validator with Post man send API. Validator return redirect uri root path. it not errors json status 422.

Laravel redirect to root on request validation error .

I have a required field in a Laravel Request Class and when that field is not present in the request, the request is redirected to root '/'.

I am sending the request via Postman.

答:
Laravel redirect validator root url "/" by it check ajax == false. if it return true, it run

```<code>If ($ this-> expectsJson ()) {
             Return new JsonResponse ($ errors, 422);
         }
</code>```

I solved the problem by adding  setup POST MAN in Headers:

I hope it will be useful to the next person when the validator does not work as you expect, you need to set it up like sending ajax to the routes api:

```<code>"Key" => "value"

X-Requested-With => XMLHttpRequest
</code>```

Post Man need config setting some ajax

Otherwise laravel will not be able to return error code 422.

```<code>If ($ this-> expectsJson ()) {
             Return new JsonResponse ($ errors, 422);
         }
</code>```

==> return false if not have "X-Requested-With" : "XMLHttpRequest" in headers POST MAN.

ajax or not ajax active other #.

sorry i do not know english.

Body:
Laravel redirect validator root url "/" by it check ajax == false. if it return true, it run

If ($ this-> expectsJson ()) {
             Return new JsonResponse ($ errors, 422);
         }

I solved the problem by adding  setup POST MAN in Headers:

I hope it will be useful to the next person when the validator does not work as you expect, you need to set it up like sending ajax to the routes api:

"Key" => "value"

X-Requested-With => XMLHttpRequest

Post Man need config setting some ajax

Otherwise laravel will not be able to return error code 422.

If ($ this-> expectsJson ()) {
             Return new JsonResponse ($ errors, 422);
         }

==> return false if not have "X-Requested-With" : "XMLHttpRequest" in headers POST MAN.

ajax or not ajax active other #.

sorry i do not know english.


问:
How to extract a range of elements between two specified keys?
I have two arrays, the first one is:

```<code>Array (
  [0] => Mar
  [1] => Jun
)
</code>```

and the second one is:

```<code>Array (
  [Jan] => January
  [Feb] => February
  [Mar] => March
  [Apr] => April
  [May] => May
  [Jun] => June
  [Jul] => July
  [Aug] => August
  [Sep] => September
  [Oct] => October
  [Nov] => November
  [Dec] => December
)
</code>```

I'd like to extract the elements from the first nominated month to the second nominated month in the search array.

My expected result is:

```<code>Array (
  [Mar] => March
  [Apr] => April
  [May] => May
  [Jun] => June
)
</code>```

答:
Please check below answer, May be it will help you:</p>

```<code>$fullArray = [
    'Jan' => 'January',
    'Feb' => 'February',
    'Mar' => 'March',
    'Apr' => 'April',
    'May' => 'May',
    'Jun' => 'June',
    'Jul' => 'July',
    'Aug' => 'August',
    'Sep' => 'September',
    'Oct' => 'October',
    'Nov' => 'November',
    'Dec' => 'December',
];

$arrayToCompare = [
    'Mar', 'Jun'
];

$matchedArray = array();

$matchedFirst = false;
$matchedLast = false;

foreach ($fullArray as $key => $value) {
    if ($key == $arrayToCompare[0]) {
        $matchedFirst = true;
    }

    if ($key == $arrayToCompare[1]) {
        $matchedLast = true;
    }

    if ($matchedFirst == true) {
        $matchedArray[$key] = $value;
    }

    if ($matchedLast == true) {
        $matchedArray[$key] = $value;
        break;
    }

}

print_r($matchedArray);
die;
</code>```

Body:
I have two arrays, the first one is:

Array (
  [0] => Mar
  [1] => Jun
)

and the second one is:

Array (
  [Jan] => January
  [Feb] => February
  [Mar] => March
  [Apr] => April
  [May] => May
  [Jun] => June
  [Jul] => July
  [Aug] => August
  [Sep] => September
  [Oct] => October
  [Nov] => November
  [Dec] => December
)

I'd like to extract the elements from the first nominated month to the second nominated month in the search array.

My expected result is:

Array (
  [Mar] => March
  [Apr] => April
  [May] => May
  [Jun] => June
)

Body:
Please check below answer, May be it will help you:

$fullArray = [
    'Jan' => 'January',
    'Feb' => 'February',
    'Mar' => 'March',
    'Apr' => 'April',
    'May' => 'May',
    'Jun' => 'June',
    'Jul' => 'July',
    'Aug' => 'August',
    'Sep' => 'September',
    'Oct' => 'October',
    'Nov' => 'November',
    'Dec' => 'December',
];

$arrayToCompare = [
    'Mar', 'Jun'
];

$matchedArray = array();

$matchedFirst = false;
$matchedLast = false;

foreach ($fullArray as $key => $value) {
    if ($key == $arrayToCompare[0]) {
        $matchedFirst = true;
    }

    if ($key == $arrayToCompare[1]) {
        $matchedLast = true;
    }

    if ($matchedFirst == true) {
        $matchedArray[$key] = $value;
    }

    if ($matchedLast == true) {
        $matchedArray[$key] = $value;
        break;
    }

}

print_r($matchedArray);
die;


问:
Sort NSArray with a specific key
I'm have requested an array from server and now I wanna filter all data which have "status_read": 1 in an new array. How can I do it? This is my data response:

```<code>{
  "status": "success",
  "message": "success",
  "data": [
    {
      "logo": "http://**.com/timepicker/images/default_o.jpg",
      "title": "Title 1",
      "icon": "https://**.com/admin/dashboard/dist/img/a.png",
      "type": 1,
      "link_detail": "",
      "id_call": 12,
      "status_read": 1
    },
    {
      "logo": "http://**.com/timepicker/images/default_go.jpg",
      "title": "Title 2",
      "icon": "https://**.com/admin/dashboard/dist/img/b.png",
      "type": 0,
      "link_detail": "http://google.com",
      "id_call": 0,
      "status_read": 0
    }
  ]
}
</code>```

Here is my code for filter array:

```<code>NSString *dictionaryKey = @"status_read";
NSInteger predicateValue = 1;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K == %i", dictionaryKey, predicateValue];
NSArray *filteredArr = [readNotif filteredArrayUsingPredicate:predicate];
generalArray = filteredArr;
[self.notifTableView reloadData];
</code>```

答:
```<code>NSString *jsonStr = @"{\"status\":\"success\",\"message\":\"success\",\"data\":[{\"logo\":\"http://**.com/timepicker/images/default_o.jpg\",\"title\":\"Title 1\",\"icon\":\"https://**.com/admin/dashboard/dist/img/a.png\",\"type\":1,\"link_detail\":\"\",\"id_call\":12,\"status_read\":1},{\"logo\":\"http://**.com/timepicker/images/default_go.jpg\",\"title\":\"Title 2\",\"icon\":\"https://**.com/admin/dashboard/dist/img/b.png\",\"type\":0,\"link_detail\":\"http://google.com\",\"id_call\":0,\"status_read\":0}]}";

NSData *data = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

//orignal array
NSArray *array = jsonDict[@"data"];
//create predicate to filter the array
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"status_read == 1"];

NSArray *filteredArray = [array filteredArrayUsingPredicate:predicate];
NSLog(@"Filtered Array: %@",filteredArray);
</code>```

Title: Sort NSArray with a specific key

Body:
I'm have requested an array from server and now I wanna filter all data which have "status_read": 1 in an new array. How can I do it? This is my data response:

{
  "status": "success",
  "message": "success",
  "data": [
    {
      "logo": "http://**.com/timepicker/images/default_o.jpg",
      "title": "Title 1",
      "icon": "https://**.com/admin/dashboard/dist/img/a.png",
      "type": 1,
      "link_detail": "",
      "id_call": 12,
      "status_read": 1
    },
    {
      "logo": "http://**.com/timepicker/images/default_go.jpg",
      "title": "Title 2",
      "icon": "https://**.com/admin/dashboard/dist/img/b.png",
      "type": 0,
      "link_detail": "http://google.com",
      "id_call": 0,
      "status_read": 0
    }
  ]
}

Here is my code for filter array:

NSString *dictionaryKey = @"status_read";
NSInteger predicateValue = 1;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K == %i", dictionaryKey, predicateValue];
NSArray *filteredArr = [readNotif filteredArrayUsingPredicate:predicate];
generalArray = filteredArr;
[self.notifTableView reloadData];


问:
Grammar question, problem with FIRST
Consider following grammar:

```<code>A → BC
B → Ba | epsilon
C → bD | epsilon
D → …
…
</code>```

The problem here is that rule B can derive epsilon and left-recursive as well.

In order to find FIRST(A) I am searching FIRST(B).

But I stuck on FIRST(B), because it is left-recursive.

So what is FIRST(B)?  And FIRST(A)?

My version is:

```<code>FIRST(B) → {a, epsilon}
FIRST(A) → {a, b, epsilon}
</code>```

Is that correct?

答:
Yes, you have it right. A left-recursion does not contribute to FIRST, because when Ba is matched for B, the B in Ba must start with something that B can start with - because it's a B, after all. :)

You could also instead factor out the left-recursion first.

Title: Grammar question, problem with FIRST

Body:
Consider following grammar:

A → BC
B → Ba | epsilon
C → bD | epsilon
D → …
…

The problem here is that rule B can derive epsilon and left-recursive as well.

In order to find FIRST(A) I am searching FIRST(B).

But I stuck on FIRST(B), because it is left-recursive.

So what is FIRST(B)?  And FIRST(A)?

My version is:

FIRST(B) → {a, epsilon}
FIRST(A) → {a, b, epsilon}

Is that correct?


答:
Try this way

```<code>progressBar.setLayoutParams(new LinearLayout.LayoutParams(100, 10));
</code>```

here 100 is width and 10 is height

instead of 100 give your total minutes as integer

Title: How to set horizontal progress bar based on total number of minutes in android?

Body:
Try this way

progressBar.setLayoutParams(new LinearLayout.LayoutParams(100, 10));

here 100 is width and 10 is height

instead of 100 give your total minutes as integer


问:
How to convert a JSON data read from a file as JSON object
I want to pass a JSON object which is read from a file to a POST api. However, I am seeing that when it is read from the file then it is not working. However when the hardcoded JSON data is passed it is working. To make you understand better, I am giving the below code example :

```<code>var json_content = {};
fs.readfile(file, function(err, data) {
        json_content = data;
        console.log("typeof json_variable  = "+ typeof json_content + "| json_content ="+json_content);
        if(err) {
            console.log("file reading error is = "+err);
            return;
        }
}
</code>```

The output of the above console.log statement is below :

typeof json_variable= object| json_content = {'title' : 'adventure', 'name': 'Homes'}

When I am sending this above json_content to my post call as a body using superagent, it is not working. In fact in the server it is received as undefined if I do req.body.title

However instead of above mechanism wherein I am reading it from a file and sending, if I set the json_content variable a hardcoded value, then it is working fine. Below is the code and output :

```<code>json_content = {'title' : 'adventure', 'name': 'Homes'};
console.log("typeof json_variable  = "+ typeof json_content + "| json_content ="+json_content);
</code>```

The output is different this time as below :

typeof json_variable = object |json_content =[object Object]

Please notice the difference in the output as the json_content is now printed as [object Object] unlike earlier case where it was printing the whole JSON.

Could you please suggest, how do I need to change the first approach when I am reading it from a file and sending it to post to get the similar kind of effect which I am getting while hard coding the json ?

答:
The only difference between them is that one is a string representation of object while second one is javascript object.

var json_content = '[{"key":"value"}]';
console.log("json_content"+json_content);

var json_content = [{"key":"value"}];
console.log("json_content"+json_content);```
</div>
</div>
</p>

<p>One more thing is happening in your code is that you are using concatenation <code>+</code> in your <code>console.log()</code> statements.<br>
To me you should avoid using such way and try with <code>,</code> instead:  </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var json_content = '[{"key":"value"}]';
console.log("json_content", json_content);

var json_content = [{"key":"value"}];
console.log("json_content", json_content);</code>```

For your last comment:

var json_content = '[{"key":"value"}]';
json_content = JSON.parse('[{"key":"value"}]');
console.log("json_content"+json_content);```

Body:
I want to pass a JSON object which is read from a file to a POST api. However, I am seeing that when it is read from the file then it is not working. However when the hardcoded JSON data is passed it is working. To make you understand better, I am giving the below code example :

var json_content = {};
fs.readfile(file, function(err, data) {
        json_content = data;
        console.log("typeof json_variable  = "+ typeof json_content + "| json_content ="+json_content);
        if(err) {
            console.log("file reading error is = "+err);
            return;
        }
}

The output of the above console.log statement is below :

typeof json_variable= object| json_content = {'title' : 'adventure', 'name': 'Homes'}

When I am sending this above json_content to my post call as a body using superagent, it is not working. In fact in the server it is received as undefined if I do req.body.title

However instead of above mechanism wherein I am reading it from a file and sending, if I set the json_content variable a hardcoded value, then it is working fine. Below is the code and output :

json_content = {'title' : 'adventure', 'name': 'Homes'};
console.log("typeof json_variable  = "+ typeof json_content + "| json_content ="+json_content);

The output is different this time as below :

typeof json_variable = object |json_content =[object Object]

Please notice the difference in the output as the json_content is now printed as [object Object] unlike earlier case where it was printing the whole JSON.

Could you please suggest, how do I need to change the first approach when I am reading it from a file and sending it to post to get the similar kind of effect which I am getting while hard coding the json ?

Body:
The only difference between them is that one is a string representation of object while second one is javascript object.

var json_content = '[{"key":"value"}]';
console.log("json_content"+json_content);

var json_content = [{"key":"value"}];
console.log("json_content"+json_content);

One more thing is happening in your code is that you are using concatenation + in your console.log() statements.

To me you should avoid using such way and try with , instead:

var json_content = '[{"key":"value"}]';
console.log("json_content", json_content);

var json_content = [{"key":"value"}];
console.log("json_content", json_content);

For your last comment:

var json_content = '[{"key":"value"}]';
json_content = JSON.parse('[{"key":"value"}]');
console.log("json_content"+json_content);


问:
Custom title for map annotation
In my map app, the user can enter an address in a search bar, and the location is displayed with a red pin. Is it possible within my code to let the user enter a custom title and subtitle before the pin is placed on the map? The title and subtitle should show up in the callout bubble. How is this done? Right now, all my pin titles are "My Place."

```<code>- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar

{

    if (!self.geocoder)
    {
        self.geocoder = [[CLGeocoder alloc] init];
    }

    NSString *address = [NSString stringWithFormat:@"%@", self.searchBar.text];

    [self.geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) {
        if ([placemarks count] > 0)
        {
            CLPlacemark *placemark = [placemarks objectAtIndex:0];
            CLLocation *location = placemark.location;
            CLLocationCoordinate2D coordinate = location.coordinate;

            NSLog (@"%f %f", coordinate.latitude, coordinate.longitude);

            MKCoordinateRegion region;
            MKCoordinateSpan span;
            span.latitudeDelta = 0.01;
            span.longitudeDelta = 0.01;
            region.span = span;
            region.center = coordinate;

            MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
            [annotation setCoordinate:coordinate];
            [annotation setTitle:@"My Place"];
            [[self mapView] addAnnotation:annotation];

            [self.mapView setRegion:region animated:TRUE];
            [self.mapView regionThatFits:region];

            [self.searchBar resignFirstResponder];
            self.searchBar.text = @"";

        }
    }];

}
</code>```

Also, how can all of my pins be saved to NSUserDefault, so that they show up when the app is restarted? Would this work, or will this only save one pin?

```<code>NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                [defaults setDouble:coordinate.latitude forKey:allPins_latitude];
                [defaults setDouble:coordinate.longitude forKey:allPins_longitude];
                [defaults setBool:YES forKey:allPins_coordinates];
                [defaults synchronize];
</code>```

I would appreciate any help! Thanks!

答:
@petter I think below code will help you
 //swift 3 </p>

```<code>func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

       let Userlocation : CLLocation = locations[0]

       let center = CLLocationCoordinate2D(latitude: Userlocation.coordinate.latitude
           , longitude: Userlocation.coordinate.longitude)

        let annotation = MKPointAnnotation()
        annotation.coordinate = center
        annotation.title = "title"
        Annotation.subtitle = “Subtitle”
        mapView.addAnnotation(annotation)
        let region = MKCoordinateRegion(center: center, span:  MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

      mapView.setRegion(region, animated: true)

   }
</code>```

Title: Custom title for map annotation

Body:
In my map app, the user can enter an address in a search bar, and the location is displayed with a red pin. Is it possible within my code to let the user enter a custom title and subtitle before the pin is placed on the map? The title and subtitle should show up in the callout bubble. How is this done? Right now, all my pin titles are "My Place."

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar

{

    if (!self.geocoder)
    {
        self.geocoder = [[CLGeocoder alloc] init];
    }

    NSString *address = [NSString stringWithFormat:@"%@", self.searchBar.text];

    [self.geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) {
        if ([placemarks count] > 0)
        {
            CLPlacemark *placemark = [placemarks objectAtIndex:0];
            CLLocation *location = placemark.location;
            CLLocationCoordinate2D coordinate = location.coordinate;

            NSLog (@"%f %f", coordinate.latitude, coordinate.longitude);

            MKCoordinateRegion region;
            MKCoordinateSpan span;
            span.latitudeDelta = 0.01;
            span.longitudeDelta = 0.01;
            region.span = span;
            region.center = coordinate;

            MKPointAnnotation *annotation = [[MKPointAnnotation alloc] init];
            [annotation setCoordinate:coordinate];
            [annotation setTitle:@"My Place"];
            [[self mapView] addAnnotation:annotation];

            [self.mapView setRegion:region animated:TRUE];
            [self.mapView regionThatFits:region];

            [self.searchBar resignFirstResponder];
            self.searchBar.text = @"";

        }
    }];

}

Also, how can all of my pins be saved to NSUserDefault, so that they show up when the app is restarted? Would this work, or will this only save one pin?

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                [defaults setDouble:coordinate.latitude forKey:allPins_latitude];
                [defaults setDouble:coordinate.longitude forKey:allPins_longitude];
                [defaults setBool:YES forKey:allPins_coordinates];
                [defaults synchronize];

I would appreciate any help! Thanks!

Body:
@petter I think below code will help you
 //swift 3

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

       let Userlocation : CLLocation = locations[0]

       let center = CLLocationCoordinate2D(latitude: Userlocation.coordinate.latitude
           , longitude: Userlocation.coordinate.longitude)

        let annotation = MKPointAnnotation()
        annotation.coordinate = center
        annotation.title = "title"
        Annotation.subtitle = “Subtitle”
        mapView.addAnnotation(annotation)
        let region = MKCoordinateRegion(center: center, span:  MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

      mapView.setRegion(region, animated: true)

   }


问:
Handle swift throw in closure in objective-c
I've an objective-c function that looks like below

+ (void) invokeSortingWithClassName: (NSString*) className functionName: (NSString*) functionName closure: (id(^)(NSArray* arr))closure;

and I've to call this method from a swift class. The swift code that calls this method looks like below

```<code>SortHandler.invokeSorting(withClassName: className, functionName: functionName, closure:
{
    args in
    let something = unwrap(args!)
    do
    {
        let returnValue = try closure(something as NSArray!) //this is another closure coming as a parameter in the function in which this code is written and this throws
        return returnValue;
    }
    catch
    {
        throw error

    }
    return "-1" as! T
})
</code>```

At the start of closure definition, I get this attached error

Essentially, this closure throws an error and I am not sure, how to handle this error in objective-c definition of this function. Please help me fix this error

答:
While a closure can be declared with throws, this closure has not been declared with throws, so your closure cannot throw - this is exactly what the error message is telling you.

Since the function is declared in Objective-C, the function signature can't be changed to include throws as Objective-C doesn't know anything about Swift exceptions.

The standard way in which error handling is translated between Swift and Objective-C is for the Objective-C block to receive an &NSError parameter.

If you have the ability to change the Objective-C method signature, it should be declared as

```<code>+(void) invokeSortingWithClassName: (NSString* _Nullable) className functionName: (NSString* _Nullable) functionName closure: (id _Nullable (^_Nullable)(NSArray* _Nullable arr, NSError* _Nullable * _Nullable error))closure;
</code>```

This will allow you to throw from swift with the error being received via the error parameter in Objctive-C.

If you cannot change the method signature, then you will need to catch the exception in your closure and simply return an 'error' value, such as nil

Body:
I've an objective-c function that looks like below

+ (void) invokeSortingWithClassName: (NSString*) className functionName: (NSString*) functionName closure: (id(^)(NSArray* arr))closure;

and I've to call this method from a swift class. The swift code that calls this method looks like below

SortHandler.invokeSorting(withClassName: className, functionName: functionName, closure:
{
    args in
    let something = unwrap(args!)
    do
    {
        let returnValue = try closure(something as NSArray!) //this is another closure coming as a parameter in the function in which this code is written and this throws
        return returnValue;
    }
    catch
    {
        throw error

    }
    return "-1" as! T
})

At the start of closure definition, I get this attached error

Essentially, this closure throws an error and I am not sure, how to handle this error in objective-c definition of this function. Please help me fix this error

Body:
While a closure can be declared with throws, this closure has not been declared with throws, so your closure cannot throw - this is exactly what the error message is telling you.

Since the function is declared in Objective-C, the function signature can't be changed to include throws as Objective-C doesn't know anything about Swift exceptions.

The standard way in which error handling is translated between Swift and Objective-C is for the Objective-C block to receive an &NSError parameter.

If you have the ability to change the Objective-C method signature, it should be declared as

+(void) invokeSortingWithClassName: (NSString* _Nullable) className functionName: (NSString* _Nullable) functionName closure: (id _Nullable (^_Nullable)(NSArray* _Nullable arr, NSError* _Nullable * _Nullable error))closure;

This will allow you to throw from swift with the error being received via the error parameter in Objctive-C.

If you cannot change the method signature, then you will need to catch the exception in your closure and simply return an 'error' value, such as nil


问:
" where in " mysql clause
i used a mysql query where there is "where id in ("22,20,21") "
but when i get the result its like array ordered in asecending order ie  20,21,20

but i need it in the same order as i gave the clause

答:
As mentioned... WHERE clause doesn't do anything with ordering of result set. Use MySQL built-in FIELD function in ORDER BY clause to specify how the result set should be ordered:

```<code>... WHERE id IN (22, 20, 21) ORDER BY FIELD(id, 22, 20, 21) ...
</code>```

Title: " where in " mysql clause

Body:
As mentioned... WHERE clause doesn't do anything with ordering of result set. Use MySQL built-in FIELD function in ORDER BY clause to specify how the result set should be ordered:

... WHERE id IN (22, 20, 21) ORDER BY FIELD(id, 22, 20, 21) ...


问:
Android Support Repo 46.0.0 with Android Studio 2.3
I updated today my support repository to 46.0.0 as the Android Studio notification popped up.

I go the error below :

Error:Execution failed for task ':app:processDevDebugManifest'.

Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(25.3.0) from
    [com.android.support:support-v13:25.3.0] AndroidManifest.xml:27:9-31
      is also present at [com.android.support:preference-v7:26.0.0-alpha1]
    AndroidManifest.xml:24:9-38 value=(26.0.0-alpha1).    Suggestion: add
    'tools:replace="android:value"' to  element at
    AndroidManifest.xml:25:5-27:34 to override.

I updated all my dependencies to use Revision 26.0.0 Alpha 1 from 25.3.0, but it turns out I need to bump the compileSdk from 25 to 26.
You can't do that if you have AS 2.3, you need to get the unstable alpha/beta version from canary.

This link shows the changes:
https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-0-alpha1

And concerning migrating to the new android O, that's the link:
https://developer.android.com/preview/migration.html

It seems using AS stable version will not work with new repository.

How can I go back to the Android Studio Repository Version 45 instead of the new 46?

** Update: The merged manifest shows one of the generated library manifest contains

```<code><meta-data
        android:name="android.support.VERSION"
        android:value="26.0.0-alpha1" />
</code>```

But since it's a generated file editing is useless, that's why for now I'd stick to rev 45 until the new AS is in stable build

答:
I think the best solution is to just revert the Android Support Library to version 45.

To do this, open this link (change version to whatever suits your needs)

https://dl-ssl.google.com/android/repository/android_m2repository_r45.zip

When downloaded, unzip and copy m2repository to android-sdk-root-folder\extras\android. Make sure to delete the existing m2repository prior to unzipping to avoid problems.

Body:
I updated today my support repository to 46.0.0 as the Android Studio notification popped up.

I go the error below :

Error:Execution failed for task ':app:processDevDebugManifest'.

Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(25.3.0) from
    [com.android.support:support-v13:25.3.0] AndroidManifest.xml:27:9-31
      is also present at [com.android.support:preference-v7:26.0.0-alpha1]
    AndroidManifest.xml:24:9-38 value=(26.0.0-alpha1).    Suggestion: add
    'tools:replace="android:value"' to  element at
    AndroidManifest.xml:25:5-27:34 to override.

I updated all my dependencies to use Revision 26.0.0 Alpha 1 from 25.3.0, but it turns out I need to bump the compileSdk from 25 to 26.
You can't do that if you have AS 2.3, you need to get the unstable alpha/beta version from canary.

This link shows the changes:
https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-0-alpha1

And concerning migrating to the new android O, that's the link:
https://developer.android.com/preview/migration.html

It seems using AS stable version will not work with new repository.

How can I go back to the Android Studio Repository Version 45 instead of the new 46?

** Update: The merged manifest shows one of the generated library manifest contains

<meta-data
        android:name="android.support.VERSION"
        android:value="26.0.0-alpha1" />

But since it's a generated file editing is useless, that's why for now I'd stick to rev 45 until the new AS is in stable build


问:
Redux, Reselect and ImmutableJS causing unnecessary renders on child components
Based on all the Redux and Reselect docs I have just read and re-read the below selector should only do the thing.toJS() processing if the Immutable Map that getThing() returns is not equal to the previous one.

...

// Selector

import { createSelector } from 'reselect'

const getThing = (state, thingId) => {
    return state.entities.getIn(['things', thingId])
}

const makeThingSelector = () => {
    return createSelector(
        [getThing],
        (thing) => {
            return thing.toJS()
        }
    )
}

export default makeThingSelector

...

// Container

const makeMapStateToProps = () => {
    return (state, ownProps) => {
        const { thingId } = ownProps
        const things = select.makeThingsSelector()(state, thingId)

        return {
            hasNoThings: things.length === 0,
            things
        }
    }
}

const Container = connect(
    makeMapStateToProps,
    mapDispatchToProps
)(Component)
...
```

This holds true unless I have a child 'smart' component. In this case, when the parent triggers a render, the selector called in the child component's container always processes the value regardless of whether the result is new or not.

I have been trying to encapsulate the ImmutableJS API inside my selectors but this means to avoid a re render on these nested components every time their parents update I have to do a deep equality check in the shouldComponentUpdate function. This is expensive and doesn't seem like a decent solution.

The app state is normalised so the updated part of the state tree is not a hierarchical parent to the part of the state that the child component is dependent on.

Am I missing something key here?

答:
On every store update react-redux performs following steps (putting all internal complexities aside):

Calls mapStateToProps and mapDispatchToProps.

Shallowly comparing resulted props

Re-renders Component In case new props differs from previous one.

This way mapStateToProps will be called on every store update by-design. So will following line of code:

```<code>...
const things = select.makeThingsSelector()(state, visitId)
...
</code>```

As you can see new reselect selector will be created every time effectively preventing any memoization (there are no global state in reselect, memoization happens per selector).

What you have to do is change your code so that one and the same selector will be used on every invocation of mapStateToProps:

```<code>const thingSelector = select.makeThingsSelector();

...

const makeMapStateToProps = () => {
    return (state, ownProps) => {
        const { visitId } = ownProps
        const things = thingSelector(state, visitId)

        return {
            hasNoThings: things.length === 0,
            things
        }
    }
}
</code>```

UPDATE: Also I don't see any reason to use factory-style makeThingsSelector and makeMapStateToProps. Why not just go with something like:

```<code>...

// Selector

export default createSelector(
  [getThing],
  (thing) => thing.toJS()
);

...

// Container

const mapStateToProps = (state, ownProps) => {
  const { visitId } = ownProps
  const things = select.thingsSelector(state, visitId)
  return {
    hasNoThings: things.length === 0,
    things
  }
}

const Container = connect(
    mapStateToProps,
    mapDispatchToProps
)(Component)
...
</code>```

Body:
Based on all the Redux and Reselect docs I have just read and re-read the below selector should only do the thing.toJS() processing if the Immutable Map that getThing() returns is not equal to the previous one.

...

// Selector

import { createSelector } from 'reselect'

const getThing = (state, thingId) => {
    return state.entities.getIn(['things', thingId])
}

const makeThingSelector = () => {
    return createSelector(
        [getThing],
        (thing) => {
            return thing.toJS()
        }
    )
}

export default makeThingSelector

...

// Container

const makeMapStateToProps = () => {
    return (state, ownProps) => {
        const { thingId } = ownProps
        const things = select.makeThingsSelector()(state, thingId)

        return {
            hasNoThings: things.length === 0,
            things
        }
    }
}

const Container = connect(
    makeMapStateToProps,
    mapDispatchToProps
)(Component)
...

This holds true unless I have a child 'smart' component. In this case, when the parent triggers a render, the selector called in the child component's container always processes the value regardless of whether the result is new or not.

I have been trying to encapsulate the ImmutableJS API inside my selectors but this means to avoid a re render on these nested components every time their parents update I have to do a deep equality check in the shouldComponentUpdate function. This is expensive and doesn't seem like a decent solution.

The app state is normalised so the updated part of the state tree is not a hierarchical parent to the part of the state that the child component is dependent on.

Am I missing something key here?

Body:
On every store update react-redux performs following steps (putting all internal complexities aside):

Calls mapStateToProps and mapDispatchToProps.

Shallowly comparing resulted props

Re-renders Component In case new props differs from previous one.

This way mapStateToProps will be called on every store update by-design. So will following line of code:

...
const things = select.makeThingsSelector()(state, visitId)
...

As you can see new reselect selector will be created every time effectively preventing any memoization (there are no global state in reselect, memoization happens per selector).

What you have to do is change your code so that one and the same selector will be used on every invocation of mapStateToProps:

const thingSelector = select.makeThingsSelector();

...

const makeMapStateToProps = () => {
    return (state, ownProps) => {
        const { visitId } = ownProps
        const things = thingSelector(state, visitId)

        return {
            hasNoThings: things.length === 0,
            things
        }
    }
}

UPDATE: Also I don't see any reason to use factory-style makeThingsSelector and makeMapStateToProps. Why not just go with something like:

...

// Selector

export default createSelector(
  [getThing],
  (thing) => thing.toJS()
);

...

// Container

const mapStateToProps = (state, ownProps) => {
  const { visitId } = ownProps
  const things = select.thingsSelector(state, visitId)
  return {
    hasNoThings: things.length === 0,
    things
  }
}

const Container = connect(
    mapStateToProps,
    mapDispatchToProps
)(Component)
...


问:
How do I use or insert the Access-Control-Allow-Origin' header into my AngularJS code or am I trying to use the wrong code for my situation?
I have the following bit of script in AngularJS pulling a JSON array from a url.

```<code><script>
var app = angular.module('myApp', []);
app.controller('recordsCtrl', function($scope, $http) {
  $http.get("https://{erased section}.amazonaws.com/prod/load/1").then(function (response) {
      $scope.records = response.data;
  });
});
</script>
</code>```

It works fine. But note that at the end of the url is a 1. It's the first of ten files. Most of them work fine and I can get the data and work with it. But on the 3rd, 5th and 6th files it just displays nothing when in the above code.

when I put it in the browser in the debugger I found it saying: "no 'Access-Control-Allow-Origin' header is present on the URL requested source". I've looked at several posts regarding this error message and I've tried to implement them in Angular code, I've even gone and implemented them in ASP.NET WebForms where I saw code for that:

```<code><customHeaders>
    <add name="Access-Control-Allow-Origin" value="*"/>
    <add name="Access-Control-Allow-Headers" value="Content-Type"/>
  </customHeaders>
</code>```

But I think I must be doing something wrong as far as how or where I am inserting the code into my own, or maybe missing some other aspect, as while no other errors show up and in Visual Studio it builds and runs, I'm still not receiving the JSON file from the url.

Any help would be greatly appreciated.

答: I think you miss: <add name="Access-Control-Allow-Methods" value="GET"/>

Body:
I have the following bit of script in AngularJS pulling a JSON array from a url.

It works fine. But note that at the end of the url is a 1. It's the first of ten files. Most of them work fine and I can get the data and work with it. But on the 3rd, 5th and 6th files it just displays nothing when in the above code.

when I put it in the browser in the debugger I found it saying: "no 'Access-Control-Allow-Origin' header is present on the URL requested source". I've looked at several posts regarding this error message and I've tried to implement them in Angular code, I've even gone and implemented them in ASP.NET WebForms where I saw code for that:

<customHeaders>
    <add name="Access-Control-Allow-Origin" value="*"/>
    <add name="Access-Control-Allow-Headers" value="Content-Type"/>
  </customHeaders>

But I think I must be doing something wrong as far as how or where I am inserting the code into my own, or maybe missing some other aspect, as while no other errors show up and in Visual Studio it builds and runs, I'm still not receiving the JSON file from the url.

Any help would be greatly appreciated.


问:
How to convert a string to an integer in JavaScript
How do I convert a string to an integer in JavaScript?</p>

答:
All of the previous answers are correct. Please be sure before that this is a number in a string by doing "typeot x === 'number'". Otherwise, it will return NaN.</p>
```<code> var num = "fsdfsdf242342";
 typeof num => 'string';

 var num1 = "12423";
 typeof num1 => 'number';
 +num1 = > 12423`
</code>```

ContentLicense: CC BY-SA 4.0

Body:
All of the previous answers are correct. Please be sure before that this is a number in a string by doing "typeot x === 'number'". Otherwise, it will return NaN.

 var num = "fsdfsdf242342";
 typeof num => 'string';

 var num1 = "12423";
 typeof num1 => 'number';
 +num1 = > 12423`


问:
Is there a way to disable JSDoc generation in VS Code?
It looks like V1.10 added auto JSDoc generation when typing /**.

Is there a ways to disable this functionality so it just generates a normal comment block and does not add the parsed params?

答:
You can't disable this in the current release but the next update (April) will have a new option in settings - jsDocCompletion.enabled.

Right now, because this feature is using template expansion, you can just hit Esc after typing /** when the autocomplete hint appears and before pressing Enter.


问:
How do you add enum labels using sequelize?
I have a table called characters. Each character has an enum called "state", which can be "sad" or "happy". How do I add a new state "confused" to my column? I tried this migration but it failed:

```<code>migration.describeTable('characters').success(function (attributes) {
    migration.changeColumn('characters', 'state',
        {
            type: DataTypes.ENUM,
            values: ['sad', 'happy', 'confused']
        })
        .complete(done);
});
</code>```

It complained that error: type "enum_characters_state" already exists.

答:
You need to remove the type, if you want to re-add it. Useful in down migrations if nothing else.</p>

```<code>queryInterface.sequelize.query('DROP TYPE enum_characters_state;')
</code>```

Body:
I have a table called characters. Each character has an enum called "state", which can be "sad" or "happy". How do I add a new state "confused" to my column? I tried this migration but it failed:

migration.describeTable('characters').success(function (attributes) {
    migration.changeColumn('characters', 'state',
        {
            type: DataTypes.ENUM,
            values: ['sad', 'happy', 'confused']
        })
        .complete(done);
});

It complained that error: type "enum_characters_state" already exists.

Body:
You need to remove the type, if you want to re-add it. Useful in down migrations if nothing else.

queryInterface.sequelize.query('DROP TYPE enum_characters_state;')


问:
Merging two data tables by code but recognize where it was scanned first
I'm working on some data which contains rejected and accepted data. These are separated in two separated log files. I want to merge them with R-code.

But if a code was rejected it could be accepted later on. And the other way around. If you used the code already it should be rejected later on.

I want to make a merge between these two tables cause when you're code is rejected I also get a code why it was rejected in the first place when someone used the code at the wrong day or at the wrong store and uses it later on at the right place and time I can find it back in the accepted log file.

my code looks like this:

```<code>head(ACCEPTED)

code   Overruled device      date
1 29    FALSE   05       2017-02-23 16:27:56
2 30    FALSE   05       2017-02-23 16:27:58
3 09    FALSE   05       2017-02-23 16:28:31
4 06    FALSE   08       2017-02-23 16:28:34
5 27    FALSE   08       2017-02-23 16:28:39
6 07    FALSE   08       2017-02-23 16:28:59

head(REJECTED)
code   CODE device         date
1 29    1   01        2017-02-22 12:47:49
2 07    5   01        2017-02-23 16:48:25
3 00    2   01        2017-02-23 12:50:00
4 09    3   01        2017-02-23 16:51:23
5 87    1   07        2017-02-23 16:25:29
6 98    1   03        2017-02-23 16:25:47
</code>```

I already merged them by barcode but then I didn't include the fact that I wanted to know the origin where the code was first used.

So for code 29 it was first rejected on the 22 and accepted on the 23.

But code 09 was first accepted and then rejected (someone tried to use the code later on, but failed because it was already used)

Some code is not in both tables because it either was accepted or rejected and not used again.

I want a table that can work with chord  visualisation tool from Microsoft power BI

the new data frame should look like this:

```<code> code   from   to
 29     01     05 # because the code was first seen at 01 and then scanned at 05
 09     05     01
 07     08     01
</code>```

If the code doesn't exist in the other table it should not appear in the new table. Normal merging works by code but it should be in order of appearance of the code.
Any help will be appreciated.

答:
You can join tables by means of Power Query:

Edit Queries

Right Click under Queries -> New Query -> Combine -> Megre Queries as New

select the two tables and then code column under each.

specify Join Kind.

expand NewColumn

Once you join the two tables:

```<code>code   Overruled device.ac   date.ac          CODE.rej  device.rej     date.rej
29      FALSE       05    2017-02-23 16:27:56   1          01   2017-02-22 12:47:49
09      FALSE       05    2017-02-23 16:28:31   3          01   2017-02-23 16:51:23
07      FALSE       08    2017-02-23 16:28:59   5          01   2017-02-23 16:48:25
</code>```

You can then add calculated columns:

```<code>from = IF(new[date.ac]<new[date.rej],new[device.ac],new[device.rej])
to = IF(new[date.ac]>new[date.rej],new[device.ac],new[device.rej])
</code>```

Results in:

```<code>code from to
7    8    1
9    5    1
29   1    5
</code>```

Body:
I'm working on some data which contains rejected and accepted data. These are separated in two separated log files. I want to merge them with R-code.

But if a code was rejected it could be accepted later on. And the other way around. If you used the code already it should be rejected later on.

I want to make a merge between these two tables cause when you're code is rejected I also get a code why it was rejected in the first place when someone used the code at the wrong day or at the wrong store and uses it later on at the right place and time I can find it back in the accepted log file.

my code looks like this:

head(ACCEPTED)

code   Overruled device      date
1 29    FALSE   05       2017-02-23 16:27:56
2 30    FALSE   05       2017-02-23 16:27:58
3 09    FALSE   05       2017-02-23 16:28:31
4 06    FALSE   08       2017-02-23 16:28:34
5 27    FALSE   08       2017-02-23 16:28:39
6 07    FALSE   08       2017-02-23 16:28:59

head(REJECTED)
code   CODE device         date
1 29    1   01        2017-02-22 12:47:49
2 07    5   01        2017-02-23 16:48:25
3 00    2   01        2017-02-23 12:50:00
4 09    3   01        2017-02-23 16:51:23
5 87    1   07        2017-02-23 16:25:29
6 98    1   03        2017-02-23 16:25:47

I already merged them by barcode but then I didn't include the fact that I wanted to know the origin where the code was first used.

So for code 29 it was first rejected on the 22 and accepted on the 23.

But code 09 was first accepted and then rejected (someone tried to use the code later on, but failed because it was already used)

Some code is not in both tables because it either was accepted or rejected and not used again.

I want a table that can work with chord  visualisation tool from Microsoft power BI

the new data frame should look like this:

 code   from   to
 29     01     05 # because the code was first seen at 01 and then scanned at 05
 09     05     01
 07     08     01

If the code doesn't exist in the other table it should not appear in the new table. Normal merging works by code but it should be in order of appearance of the code.
Any help will be appreciated.

Body:
You can join tables by means of Power Query:

Edit Queries

Right Click under Queries -> New Query -> Combine -> Megre Queries as New

select the two tables and then code column under each.

specify Join Kind.

expand NewColumn

Once you join the two tables:

code   Overruled device.ac   date.ac          CODE.rej  device.rej     date.rej
29      FALSE       05    2017-02-23 16:27:56   1          01   2017-02-22 12:47:49
09      FALSE       05    2017-02-23 16:28:31   3          01   2017-02-23 16:51:23
07      FALSE       08    2017-02-23 16:28:59   5          01   2017-02-23 16:48:25

You can then add calculated columns:

from = IF(new[date.ac]<new[date.rej],new[device.ac],new[device.rej])
to = IF(new[date.ac]>new[date.rej],new[device.ac],new[device.rej])

Results in:

code from to
7    8    1
9    5    1
29   1    5


答: In general, the database system returns the results in whatever order it feels like. If you want it to be ordered, you have to tell it. This blog post provides one method for doing so; you may be able to find other solutions online.</p>

Title: " where in " mysql clause

Body:
i used a mysql query where there is "where id in ("22,20,21") "
but when i get the result its like array ordered in asecending order ie  20,21,20

but i need it in the same order as i gave the clause


问:
Given this string input how could I make this given output?
```<code>s = """
ID# VALUE_1 VALUE_2
  1      0.1          300
  2   0.2             400 (11 - this text is part of C in row 2 but needs to be ignored / removed)
  3          0.9          600"""
</code>```

I am wanting to convert the above string into the formatted dictionary below. The spacing and extra text is like that on purpose. The spacing & noted text should be removed / stripped.

```<code>print(my_dict)
{'1': {'VALUE_1': '0.1', 'VALUE_2': '300'}, '2': {'VALUE_1': '0.2', 'VALUE_2': '400'}, '3': {'VALUE_1': '0.9', 'VALUE_2': '600'}}
</code>```

What I've tried so far:

```<code>s = """
ID# VALUE_1 VALUE_2
  1      0.1          300
  2   0.2             400 (11 - this text is part of C in row 2 but needs to be ignored / removed)
  3          0.9          600"""

#Get the columns and assign them to a variable.
columns = s.lstrip().splitlines()[0] #Print the first line of the string

dct = {}

rows = s.lstrip().splitlines()

for data in rows[1:]:
    row = data.split()
    dct[row[0]] = dict(zip(columns[1:], row[1:]))

print(dct)
</code>```

This ends up outputting an ugly unformatted looking dictionary :

```<code>{'1': {'D': '0.1', '#': '300'}, '2': {'D': '0.2', '#': '400', ' ': 'in', 'V': 'row', 'A': '2', 'L': 'but', 'U': 'needs', 'E': 'to', '_': 'be', '1': 'C', '2': 'ignored'}, '3': {'D': '0.9', '#': '600'}}
</code>```

I've been unable to incorporate a way to successfully strip out the spaces and extra chunk of data on row2 with my current loop process.

答:
There's a small bug in your code.

```<code>columns = s.lstrip().splitlines()[0]
</code>```

does not give a list. Use:

```<code>columns = s.lstrip().splitlines()[0].split()
</code>```

After making this modification, your code should run fine.

Moreover, improvising on it, you shouldn't use columns at all. Just replace it with rows[0].

Body:
s = """
ID# VALUE_1 VALUE_2
  1      0.1          300
  2   0.2             400 (11 - this text is part of C in row 2 but needs to be ignored / removed)
  3          0.9          600"""

I am wanting to convert the above string into the formatted dictionary below. The spacing and extra text is like that on purpose. The spacing & noted text should be removed / stripped.

print(my_dict)
{'1': {'VALUE_1': '0.1', 'VALUE_2': '300'}, '2': {'VALUE_1': '0.2', 'VALUE_2': '400'}, '3': {'VALUE_1': '0.9', 'VALUE_2': '600'}}

What I've tried so far:

s = """
ID# VALUE_1 VALUE_2
  1      0.1          300
  2   0.2             400 (11 - this text is part of C in row 2 but needs to be ignored / removed)
  3          0.9          600"""

#Get the columns and assign them to a variable.
columns = s.lstrip().splitlines()[0] #Print the first line of the string

dct = {}

rows = s.lstrip().splitlines()

for data in rows[1:]:
    row = data.split()
    dct[row[0]] = dict(zip(columns[1:], row[1:]))

print(dct)

This ends up outputting an ugly unformatted looking dictionary :

{'1': {'D': '0.1', '#': '300'}, '2': {'D': '0.2', '#': '400', ' ': 'in', 'V': 'row', 'A': '2', 'L': 'but', 'U': 'needs', 'E': 'to', '_': 'be', '1': 'C', '2': 'ignored'}, '3': {'D': '0.9', '#': '600'}}

I've been unable to incorporate a way to successfully strip out the spaces and extra chunk of data on row2 with my current loop process.

Body:
There's a small bug in your code.

columns = s.lstrip().splitlines()[0]

does not give a list. Use:

columns = s.lstrip().splitlines()[0].split()

After making this modification, your code should run fine.

Moreover, improvising on it, you shouldn't use columns at all. Just replace it with rows[0].


问:
How to overcome "No repositories found" error in IntelliJ
I'm getting "No repository found" errors in IntelliJ not only for our own repository, but even for the majority of the repositories listed by default under Maven configuration. Only jfrog.org and jboss.org are reported OK with artifacts.

The rest of the repositories are online and contain artifacts if accessed with a browser or with Maven from command line.

There's a bug report on JetBrains site: http://youtrack.jetbrains.com/issue/IDEA-122332, submitted three months ago.

Is there a workaround?

答: Adding /service/local/ helped me with sonatype nexus.


问:
Using jaydebeapi3 to connect to Apache Phoenix
I have a program, in which I have been using the phoenixdb package developed by Lukas Lalinsky but during the past few days it seems to have become very unstable. I think this is due to the size of the database (as it is constantly growing). By unstable I mean that around half my queries are failing with a runtime exception.

So I have moved on and tried to find a more stable way to connect with my Phoenix "server". Therefore I want to try out a JDBC connection. As far as I have understood Phoenix should have great integration with JDBC.

I do however have problems with understanding how to set up the initial connection.

I read the following Usage section of the JayDeBeApi package, but I don't know what the Driver Class is or where it is located? If I have to download it myself? How to set it up? And so forth.

I was hoping someone in here would know and hopefully explain it in detail.

Thanks!

EDIT:

I've managed to figure out that my connect statement should be something along this:

```<code>import jaybedeapi as jdbc
conn = jdbc.connect('org.apache.phoenix.jdbc.PhoenixDriver', ['jdbc:phoenix:<ip>:<port>:', '', ''], '<location-of-phoenix-client.jar>')
</code>```

However I still don't know where to get my hands on that phoenix-client.jar file and how to reference to it.

答:
I managed to find the solution after having set up a Java project and testing out JDBC in that development environment and getting a successful connection.

To get the JDBC connection working in Java I used the JDBC driver found in the Phoenix distribution from Apache here. I used the driver that matched my Phoenix and HBase versions - phoenix-4.9.0-HBase-1.2-client.jar

Once that setup was completed and I could connect to Phoenix using Java I started trying to set it up using Python. I started a connection to Phoenix with the following:

```<code>import jaydebeapi as jdbc
import os
cwd = os.getcwd()
jar = cwd + '/phoenix-4.9.0-HBase-1.2-client.jar'
drivername = 'org.apache.phoenix.jdbc.PhoenixDriver'
url = 'jdbc:phoenix:<ip>:<port>/'
conn = jdbc.connect(drivername, url, jar)
</code>```

Now I had a successful connection through JDBC to Phoenix using Python. Hope someone else out there can use this question in the future.

I created a cursor using the following and could issue commands like in the following:

```<code>cursor = conn.cursor()
sql = """SELECT ...."""
cursor.execute(sql)
resp = cursor.fetchone() # could use .fetchall() or .fetchmany() if needed
</code>```

I hope this helps someone out there!

Body:
I have a program, in which I have been using the phoenixdb package developed by Lukas Lalinsky but during the past few days it seems to have become very unstable. I think this is due to the size of the database (as it is constantly growing). By unstable I mean that around half my queries are failing with a runtime exception.

So I have moved on and tried to find a more stable way to connect with my Phoenix "server". Therefore I want to try out a JDBC connection. As far as I have understood Phoenix should have great integration with JDBC.

I do however have problems with understanding how to set up the initial connection.

I read the following Usage section of the JayDeBeApi package, but I don't know what the Driver Class is or where it is located? If I have to download it myself? How to set it up? And so forth.

I was hoping someone in here would know and hopefully explain it in detail.

Thanks!

EDIT:

I've managed to figure out that my connect statement should be something along this:

import jaybedeapi as jdbc
conn = jdbc.connect('org.apache.phoenix.jdbc.PhoenixDriver', ['jdbc:phoenix:<ip>:<port>:', '', ''], '<location-of-phoenix-client.jar>')

However I still don't know where to get my hands on that phoenix-client.jar file and how to reference to it.

Body:
I managed to find the solution after having set up a Java project and testing out JDBC in that development environment and getting a successful connection.

To get the JDBC connection working in Java I used the JDBC driver found in the Phoenix distribution from Apache here. I used the driver that matched my Phoenix and HBase versions - phoenix-4.9.0-HBase-1.2-client.jar

Once that setup was completed and I could connect to Phoenix using Java I started trying to set it up using Python. I started a connection to Phoenix with the following:

import jaydebeapi as jdbc
import os
cwd = os.getcwd()
jar = cwd + '/phoenix-4.9.0-HBase-1.2-client.jar'
drivername = 'org.apache.phoenix.jdbc.PhoenixDriver'
url = 'jdbc:phoenix:<ip>:<port>/'
conn = jdbc.connect(drivername, url, jar)

Now I had a successful connection through JDBC to Phoenix using Python. Hope someone else out there can use this question in the future.

I created a cursor using the following and could issue commands like in the following:

cursor = conn.cursor()
sql = """SELECT ...."""
cursor.execute(sql)
resp = cursor.fetchone() # could use .fetchall() or .fetchmany() if needed

I hope this helps someone out there!


问:
Warning: File listed in ass.cabal file does not exist: README.md
I've just started to learn haskell and I faced this proble while trying to         stack build.
What's the way to solve it?
Thank you in advance.

答:
You don't have README.md in your project. Just create that file and the warning will go off:

```<code>$ touch README.md
</code>```

Note that you have to create the file inside the project's folder.

Body:
You don't have README.md in your project. Just create that file and the warning will go off:

$ touch README.md

Note that you have to create the file inside the project's folder.


问:
Cannot use EF Core Migration
I am using EF Core code first in a window service with Autofac DI and when I run Add-Migration TestDD1InitialMigration I get error

```<code>No parameterless constructor was found on 'ClientsContext'. Either add a parameterless constructor to 'ClientsContext' or add an implementation of 'IDbContextFactory<ClientsContext>' in the same assembly as 'ClientsContext'.
</code>```

How can I avoid this error?

Thanks in advance

答:
You need a context factory so EF Core can create a DbContext for migrations:

```<code>public class MyDbContextFactory : IDbContextFactory<MyDbContext>
{
    private IConfigurationRoot _configuration;

    public MyDbContextFactory()
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(System.AppContext.BaseDirectory)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

        _configuration = builder.Build();
    }

    public MyDbContext Create()
    {
        var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
        optionsBuilder.UseSqlServer(_configuration.GetConnectionString("DefaultConnection"), m => { m.EnableRetryOnFailure(); });

        return new MyDbContext(optionsBuilder.Options);
    }
}
</code>```

And an appsettings.json file where you put your connection string:

```<code>{
    "ConnectionStrings": {
        "DefaultConnection": "<your_connection_string>"
    }
}
</code>```

Title: Cannot use EF Core Migration

Body:
I am using EF Core code first in a window service with Autofac DI and when I run Add-Migration TestDD1InitialMigration I get error

No parameterless constructor was found on 'ClientsContext'. Either add a parameterless constructor to 'ClientsContext' or add an implementation of 'IDbContextFactory<ClientsContext>' in the same assembly as 'ClientsContext'.

How can I avoid this error?

Thanks in advance

Body:
You need a context factory so EF Core can create a DbContext for migrations:

public class MyDbContextFactory : IDbContextFactory<MyDbContext>
{
    private IConfigurationRoot _configuration;

    public MyDbContextFactory()
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(System.AppContext.BaseDirectory)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);

        _configuration = builder.Build();
    }

    public MyDbContext Create()
    {
        var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
        optionsBuilder.UseSqlServer(_configuration.GetConnectionString("DefaultConnection"), m => { m.EnableRetryOnFailure(); });

        return new MyDbContext(optionsBuilder.Options);
    }
}

And an appsettings.json file where you put your connection string:

{
    "ConnectionStrings": {
        "DefaultConnection": "<your_connection_string>"
    }
}


问:
How to have Ellipsis effect on Text
I'm having a long text in my app and I need to truncate it and add three dots to the end.

How can I do that in React Native Text element?

Thanks

答:
You can use ellipsizeMode and numberOfLines.
e.g

<Text ellipsizeMode='tail' numberOfLines={2}>
  This very long text should be truncated with dots in the beginning.
</Text>
```

https://facebook.github.io/react-native/docs/text.html

Title: How to have Ellipsis effect on Text

Body:
You can use ellipsizeMode and numberOfLines.
e.g

<Text ellipsizeMode='tail' numberOfLines={2}>
  This very long text should be truncated with dots in the beginning.
</Text>

https://facebook.github.io/react-native/docs/text.html