问:
Graph API vs iOS SDK in Facebook App
What is actually the advantage/disadvantage of each method? I've used the graph API before and it seems that it can do anything I want in Facebook.</p>

答:
You seem to confuse SDK and API. API is an interface to a service that programmers can use. SDK is a library that uses this API. Facebook iOS SDK is a new version of the Facebook SDK that uses the Graph API and also allows you to call the older REST API.

```<code> You
----------------------
 Various SDKs
----------------------
 REST API | Graph API
----------------------
 Facebook internals
</code>```

An SDK does not have to implement all of an API. And the Graph API in this case does not support all the things that the older REST API supported, like video upload. Hope that helps a bit.

Title: Graph API vs iOS SDK in Facebook App

Body:
You seem to confuse SDK and API. API is an interface to a service that programmers can use. SDK is a library that uses this API. Facebook iOS SDK is a new version of the Facebook SDK that uses the Graph API and also allows you to call the older REST API.

 You
----------------------
 Various SDKs
----------------------
 REST API | Graph API
----------------------
 Facebook internals

An SDK does not have to implement all of an API. And the Graph API in this case does not support all the things that the older REST API supported, like video upload. Hope that helps a bit.


来源: stackexchange

问:
Dynamic cookbook with chef
I'm trying to create a recipe that unzip some files then the behavior is depend on the content of the zipfile.
but I can't figure put how to overcome the Compile vs Converge phase.

The directories are not exists before the recipe is executed so the command to get the sub directories must be inside a ruby block to fetch the data in runtime.

But once the command is inside the ruby block I can't "read" the new values of the variables or attributes.

here is a sample:

```<code>ruby_block 'update patch attributes' do
   block do
      OPatchPath="#{node[:oracle][:rdbms][:ora_home]}/OPatch/#{Patch_No}"
      Subdir_list = Dir.glob("#{OPatchPath}/*/")

      Subdir_list.each do |dir|
         Subdir_list.map! {|dir| dir.sub("#{OPatchPath}/", "")}
         Subdir_list.map! {|dir| dir.sub('/', "")}
      end

      node.set[:oracle][:rdbms][:oracle_patch_list]=Subdir_list
   end
end

## if there are no directories with numberes
if Subdir_list.find { |e| /^\d+$/ =~ e } == nil
   do something
else
   if Subdir_list.count == 2
      do something else
   else
      do some other something
   end
end
</code>```

I did a deep research online and tried a lot of suggestions include using lazy, node.set, node.default node.run_state with no luck.
what am I missing?
any suggestions?

Thanks, Ofir.

答: This is a compile vs. converge issue, you can see https://coderanger.net/two-pass/ for a more detailed overview but tl;dr is that the code inside the ruby_block happens after the code outside the ruby_block even though that may not match the order in the file. You'll probably need to make a custom resource.</p>

ContentLicense: CC BY-SA 3.0

Title: Dynamic cookbook with chef

Body:
I'm trying to create a recipe that unzip some files then the behavior is depend on the content of the zipfile.
but I can't figure put how to overcome the Compile vs Converge phase.

The directories are not exists before the recipe is executed so the command to get the sub directories must be inside a ruby block to fetch the data in runtime.

But once the command is inside the ruby block I can't "read" the new values of the variables or attributes.

here is a sample:

ruby_block 'update patch attributes' do
   block do
      OPatchPath="#{node[:oracle][:rdbms][:ora_home]}/OPatch/#{Patch_No}"
      Subdir_list = Dir.glob("#{OPatchPath}/*/")

      Subdir_list.each do |dir|
         Subdir_list.map! {|dir| dir.sub("#{OPatchPath}/", "")}
         Subdir_list.map! {|dir| dir.sub('/', "")}
      end

      node.set[:oracle][:rdbms][:oracle_patch_list]=Subdir_list
   end
end

## if there are no directories with numberes
if Subdir_list.find { |e| /^\d+$/ =~ e } == nil
   do something
else
   if Subdir_list.count == 2
      do something else
   else
      do some other something
   end
end

I did a deep research online and tried a lot of suggestions include using lazy, node.set, node.default node.run_state with no luck.
what am I missing?
any suggestions?

Thanks, Ofir.


问:
Compilation errors in simple Java program with Scanner
```<code>import java.util.*;
public class strings {
    public static void main (String [] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        int first = keyboard.next();
        System.out.print("Type your seconds integer : ");
        int second = keyboard.next();
        System.out.print("The sum of your two integers are:");
    }
}
</code>```

<p>I dont know why im getting 2 errors on strings cannot converted to int. </p>

答:
This will read the whole line then convert it to an Integer

int first  = Integer.paresInt(keyboard.nextLine());

or

If you are sure input is in digit

int first = keyboard.nextInt();

Body:
import java.util.*;
public class strings {
    public static void main (String [] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        int first = keyboard.next();
        System.out.print("Type your seconds integer : ");
        int second = keyboard.next();
        System.out.print("The sum of your two integers are:");
    }
}

I dont know why im getting 2 errors on strings cannot converted to int.


问:
How do I handle Firebase Adapter RecyclerView empty view?
So the issue is that whenever I set my empty view for the recycler view, it always shows the empty view. I tried following some suggested solutions like the one in this url: FirebaseRecyclerAdapter with empty view, but the problem is that Firebase listeners are asynchronous and runs on its own thread. Before even setting the empty view, the fragment's onCreateView method already returns the view and so the empty view is not set appropriately. Are there any other way to implement the setting of empty view for FirebaseRecyclerAdapter?

Here is the snippet of the code:

```<code>public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    v = inflater.inflate(R.layout.activity_list, container, false);

    initializeFilter();

    Log.d("AttendanceFragment", filter.getTab() + "");

    Firebase.setAndroidContext(getContext());

    //filter(filter);
    handleFilter();

    if(getContext() != null) {
        adapter = new AttendanceAdapter(Attendance.class, R.layout.list_item, AttendanceAdapter.AttendanceViewHolder.class, mDatabase);

        mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Log.d("DATA_CHANGED", dataSnapshot.hasChildren() + "");

                if(!dataSnapshot.hasChildren()){
                    Log.d("SETTING", setEmpty + "");
                    if(filter.getTab() == 1) {
                        empty = (TextView) v.findViewById(R.id.empty_view);
                        empty.setText("No finished attendance yet");
                    }

                    recView.setEmptyView(v.findViewById(R.id.empty_view));
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        Log.d("FIREBASE", recView.getAdapter().getItemCount() + "");
    }

    adapter.setOnItemClickListener(new AttendanceAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(String name) {
            Toast.makeText(getContext(), name, Toast.LENGTH_SHORT).show();
        }
    });

    recView.setAdapter(adapter);

    return v;
}
</code>```

It basically checks if the dataSnapshot does not have any children and if it doesn't have any children, it sets the empty view. The problem again is that setAdapter() is called first before onDataChange().

答: put the recView.setAdapter(adapter) after recView.setEmptyView(v.findViewById(R.id.empty_view)) for a better practice use ProgressBar or ProgressDialog

Body:
So the issue is that whenever I set my empty view for the recycler view, it always shows the empty view. I tried following some suggested solutions like the one in this url: FirebaseRecyclerAdapter with empty view, but the problem is that Firebase listeners are asynchronous and runs on its own thread. Before even setting the empty view, the fragment's onCreateView method already returns the view and so the empty view is not set appropriately. Are there any other way to implement the setting of empty view for FirebaseRecyclerAdapter?

Here is the snippet of the code:

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    v = inflater.inflate(R.layout.activity_list, container, false);

    initializeFilter();

    Log.d("AttendanceFragment", filter.getTab() + "");

    Firebase.setAndroidContext(getContext());

    //filter(filter);
    handleFilter();

    if(getContext() != null) {
        adapter = new AttendanceAdapter(Attendance.class, R.layout.list_item, AttendanceAdapter.AttendanceViewHolder.class, mDatabase);

        mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Log.d("DATA_CHANGED", dataSnapshot.hasChildren() + "");

                if(!dataSnapshot.hasChildren()){
                    Log.d("SETTING", setEmpty + "");
                    if(filter.getTab() == 1) {
                        empty = (TextView) v.findViewById(R.id.empty_view);
                        empty.setText("No finished attendance yet");
                    }

                    recView.setEmptyView(v.findViewById(R.id.empty_view));
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        Log.d("FIREBASE", recView.getAdapter().getItemCount() + "");
    }

    adapter.setOnItemClickListener(new AttendanceAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(String name) {
            Toast.makeText(getContext(), name, Toast.LENGTH_SHORT).show();
        }
    });

    recView.setAdapter(adapter);

    return v;
}

It basically checks if the dataSnapshot does not have any children and if it doesn't have any children, it sets the empty view. The problem again is that setAdapter() is called first before onDataChange().


问:
SQL Code for Circular Reference
I on looking for a sql code (preferably with joins, not with cursors or stored proc or variables).

We have a parent manager-employee relationship in a database table, where the manager erroneously becomes the employee for some of the succeeding verticals/records, Example below:

Pic of sample data

```<code>Reporting Manager   Employee
1                     2
2                     3
3                     4
4                     1   --<< Circular Reference
</code>```

(The last record is wrong, and creates a circular reference with the first record, as 1 cannot report back to 4)

I am looking forward to find these records who pose this kind of a circular reference, any help is really appreciated.

I have attached a pic of how the data looks like.

答:
You should be able to achieve this by joining the table to itself.  See below:</p>

```<code>select b.Parent, b.Child
  from your_table a
  join your_table b
    on b.Child = a.Parent
 where b.Parent > a.Parent;
</code>```

Title: SQL Code for Circular Reference

Body:
I on looking for a sql code (preferably with joins, not with cursors or stored proc or variables).

We have a parent manager-employee relationship in a database table, where the manager erroneously becomes the employee for some of the succeeding verticals/records, Example below:

Pic of sample data

Reporting Manager   Employee
1                     2
2                     3
3                     4
4                     1   --<< Circular Reference

(The last record is wrong, and creates a circular reference with the first record, as 1 cannot report back to 4)

I am looking forward to find these records who pose this kind of a circular reference, any help is really appreciated.

I have attached a pic of how the data looks like.

Body:
You should be able to achieve this by joining the table to itself.  See below:

select b.Parent, b.Child
  from your_table a
  join your_table b
    on b.Child = a.Parent
 where b.Parent > a.Parent;


问:
Poiinters in visual C++
How do I use pointer in visual studio every time I declare a pointer using

```<code>int *pointer;
</code>```

I get a build error leave alone other operations with them. Is there something which must be done to use pointers with VC++

Error code C4101

However when I use the pointer in the code I get an error LNK1168

Edit: issue solved restarting the IDE along with assigning a value to the pointer solves it. Thanks.

答:
C4101 is not an error, but a warning and you get it because you just declared your pointer without referencing something.

So try to initialize the pointer like this:

```<code>// Initialize with the null pointer:
int* i = nullptr;

// Or initialize with a valid address:
int ival = 5;
int* ipoint = &ival ;
</code>```

Anyways, you should think of using references or smart pointers instead of raw pointers.

Title: Poiinters in visual C++

Body:
How do I use pointer in visual studio every time I declare a pointer using

int *pointer;

I get a build error leave alone other operations with them. Is there something which must be done to use pointers with VC++

Error code C4101

However when I use the pointer in the code I get an error LNK1168

Edit: issue solved restarting the IDE along with assigning a value to the pointer solves it. Thanks.

Body:
C4101 is not an error, but a warning and you get it because you just declared your pointer without referencing something.

So try to initialize the pointer like this:

// Initialize with the null pointer:
int* i = nullptr;

// Or initialize with a valid address:
int ival = 5;
int* ipoint = &ival ;

Anyways, you should think of using references or smart pointers instead of raw pointers.


问:
C# - Communicate with WinUSB device with LIBUSB
I am trying to communicate with a Nokia Lumia phone(RM-917), over USB using LIBUSING and C#. LIBUSB is able to see the device's information(pid,vid,etc). However, I am not able to successfully write to ANY endpoint, even sending the exact command as the Windows Device Recovery Tool.

According to WinUSB, the write endpoint is EP07, however, this endpoint just times out. I have tried every other endpoint, and all of these fail.

```<code>`
public void initDevice()
{

    if(this.lumiaDevice == null)
    {
        throw new Exception("LumiaPhoneManager does not have a selected device");
    }

    UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(0x0421, 0x0661);
    MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);

    IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
    if (!ReferenceEquals(wholeUsbDevice, null))
    {
        // This is a "whole" USB device. Before it can be used,
        // the desired configuration and interface must be selected.

        // Select config #1
        wholeUsbDevice.SetConfiguration(1);

        // Claim interface #0.
        wholeUsbDevice.ClaimInterface(1);
    }

    if (this.writer == null)
    {
        writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep07);
    }

}

    public void readPCode()

{
    currentID++;
    var _x = new jsonPkt();
    ErrorCode ec = ErrorCode.None;
    int bytesWritten;
    _x.id = this.currentID + 1;
    _x.method = "ReadProductCode";

    string value = @"{""jsonrpc"":""<JSONRPC>"",""id"":<ID>,""method"":""<METHOD>"",""params"":null}";
    value = value.Replace("<JSONRPC>", "2.0");
    value = value.Replace("<ID>", currentID.ToString());
    value = value.Replace("<METHOD>", _x.method.ToString());

ec = writer.Write(Encoding.Default.GetBytes(value), 8000, out bytesWritten);
    currentID++;

    if (ec != ErrorCode.None) throw new Exception(UsbDevice.LastErrorString);

    byte[] readBuffer = new byte[1024];
    while (ec == ErrorCode.None)
    {
        int bytesRead;

        // If the device hasn't sent data in the last 100 milliseconds,
        // a timeout error (ec = IoTimedOut) will occur.
        ec = reader.Read(readBuffer, 100, out bytesRead);

     //   if (bytesRead == 0) throw new Exception("No more bytes!");

        // Write that output to the console.
        this.rtb.Text += Encoding.Default.GetString(readBuffer, 0, bytesRead).ToString() + "\n";

    }
}
</code>```

答:
Found the solution

Debugged the OEM software and found the program was using a different path to the USB device. After that I was getting access denied errors, which was solved by moving the project to a different drive. For reasons unknown, when the program runs on c drive, the CreateFile function fails with access denied

Body:
I am trying to communicate with a Nokia Lumia phone(RM-917), over USB using LIBUSING and C#. LIBUSB is able to see the device's information(pid,vid,etc). However, I am not able to successfully write to ANY endpoint, even sending the exact command as the Windows Device Recovery Tool.

According to WinUSB, the write endpoint is EP07, however, this endpoint just times out. I have tried every other endpoint, and all of these fail.

`
public void initDevice()
{

    if(this.lumiaDevice == null)
    {
        throw new Exception("LumiaPhoneManager does not have a selected device");
    }

    UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(0x0421, 0x0661);
    MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);

    IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
    if (!ReferenceEquals(wholeUsbDevice, null))
    {
        // This is a "whole" USB device. Before it can be used,
        // the desired configuration and interface must be selected.

        // Select config #1
        wholeUsbDevice.SetConfiguration(1);

        // Claim interface #0.
        wholeUsbDevice.ClaimInterface(1);
    }

    if (this.writer == null)
    {
        writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep07);
    }

}

    public void readPCode()

{
    currentID++;
    var _x = new jsonPkt();
    ErrorCode ec = ErrorCode.None;
    int bytesWritten;
    _x.id = this.currentID + 1;
    _x.method = "ReadProductCode";

    string value = @"{""jsonrpc"":""<JSONRPC>"",""id"":<ID>,""method"":""<METHOD>"",""params"":null}";
    value = value.Replace("<JSONRPC>", "2.0");
    value = value.Replace("<ID>", currentID.ToString());
    value = value.Replace("<METHOD>", _x.method.ToString());

ec = writer.Write(Encoding.Default.GetBytes(value), 8000, out bytesWritten);
    currentID++;

    if (ec != ErrorCode.None) throw new Exception(UsbDevice.LastErrorString);

    byte[] readBuffer = new byte[1024];
    while (ec == ErrorCode.None)
    {
        int bytesRead;

        // If the device hasn't sent data in the last 100 milliseconds,
        // a timeout error (ec = IoTimedOut) will occur.
        ec = reader.Read(readBuffer, 100, out bytesRead);

     //   if (bytesRead == 0) throw new Exception("No more bytes!");

        // Write that output to the console.
        this.rtb.Text += Encoding.Default.GetString(readBuffer, 0, bytesRead).ToString() + "\n";

    }
}


问:
Subscript out of range error with active column element
I am trying to write code which looks at whether a row in the active column in ("Input Sheet") matches the contents of a cell in a range which is in a different sheet ("Sheet2").

If the contents match, the code will take the contents of the cell directly to the right of the cell in ("Sheet2") & put it into row 39 of the active column in ("Input Sheet").

I know in all likelihood this is going to have something to do with the range part of the code, but am not really getting anywhere with a solution.

Any help would be appreciated.

```<code>Sub yellowgrey()

Dim y As Range

With y = Sheets("Sheet2").Range(Cells(2, 1), Cells(131, 1))

If Sheets("Input Sheet").Cells(38, ActiveCell.Column).Value = Sheets(“Sheet2”).Cells(y, 1) Then

Sheets("Input Sheet").Cells(39, ActiveCell.Column) = Sheets("Sheet2").Cells(y, 2)

End If

End With

End Sub
</code>```

答:
As was mentioned in comments, you need to qualify implicit references to the ActiveSheet and ActiveWorkbook. Rubberduck (disclaimer: I'm heavily involved in the development of this [free & open-source] VBE add-in) would have identified that problem:

Member 'Cells' implicitly references ActiveSheet

This means:

```<code>Sheets("Sheet2").Range(Cells(2, 1), Cells(131, 1))
</code>```

Is really doing this:

```<code>ActiveWorkbook.Sheets("Sheet2").Range(ActiveSheet.Cells(2, 1), ActiveSheet.Cells(131, 1))
</code>```

And that's how your code breaks down whenever Sheet2 isn't the active sheet.

Then there's these other issues:

I'd like to bring your attention to the Local variable '“Sheet2”' is not declared inspection result. Notice the double quotes are parsed as part of the identifier name - you're using curly quotes for some reason. VBA string literals must be delimited ASCII 34, i.e. " - anything else is not picked up as a string literal delimiter.

Variable y being a Range, its reference needs to be assigned with the Set keyword.

```<code>With ThisWorkbook.Worksheets("Sheet2")

    Set y = .Range(.Cells(2, 1), .Cells(131, 1)
    '...

End With
</code>```

When you later use y like this:

```<code>Sheets("Sheet2").Cells(y, 2)
</code>```

You're passing the value of the cell/range represented by y, because the .Cells call takes that y parameter as the RowIndex parameter, and since y is a Range, VBA implicitly fetches its default property (i.e. Range.Value), which makes the assignment completely dependent on what y contains... except y isn't just one cell, so it's completely unclear what you're trying to achieve here.

Body:
I am trying to write code which looks at whether a row in the active column in ("Input Sheet") matches the contents of a cell in a range which is in a different sheet ("Sheet2").

If the contents match, the code will take the contents of the cell directly to the right of the cell in ("Sheet2") & put it into row 39 of the active column in ("Input Sheet").

I know in all likelihood this is going to have something to do with the range part of the code, but am not really getting anywhere with a solution.

Any help would be appreciated.

Sub yellowgrey()

Dim y As Range

With y = Sheets("Sheet2").Range(Cells(2, 1), Cells(131, 1))

If Sheets("Input Sheet").Cells(38, ActiveCell.Column).Value = Sheets(“Sheet2”).Cells(y, 1) Then

Sheets("Input Sheet").Cells(39, ActiveCell.Column) = Sheets("Sheet2").Cells(y, 2)

End If

End With

End Sub

Body:
As was mentioned in comments, you need to qualify implicit references to the ActiveSheet and ActiveWorkbook. Rubberduck (disclaimer: I'm heavily involved in the development of this [free & open-source] VBE add-in) would have identified that problem:

Member 'Cells' implicitly references ActiveSheet

This means:

Sheets("Sheet2").Range(Cells(2, 1), Cells(131, 1))

Is really doing this:

ActiveWorkbook.Sheets("Sheet2").Range(ActiveSheet.Cells(2, 1), ActiveSheet.Cells(131, 1))

And that's how your code breaks down whenever Sheet2 isn't the active sheet.

Then there's these other issues:

I'd like to bring your attention to the Local variable '“Sheet2”' is not declared inspection result. Notice the double quotes are parsed as part of the identifier name - you're using curly quotes for some reason. VBA string literals must be delimited ASCII 34, i.e. " - anything else is not picked up as a string literal delimiter.

Variable y being a Range, its reference needs to be assigned with the Set keyword.

With ThisWorkbook.Worksheets("Sheet2")

    Set y = .Range(.Cells(2, 1), .Cells(131, 1)
    '...

End With

When you later use y like this:

Sheets("Sheet2").Cells(y, 2)

You're passing the value of the cell/range represented by y, because the .Cells call takes that y parameter as the RowIndex parameter, and since y is a Range, VBA implicitly fetches its default property (i.e. Range.Value), which makes the assignment completely dependent on what y contains... except y isn't just one cell, so it's completely unclear what you're trying to achieve here.


问:
How to make sure my while loop does not break my condition?
I'm practicing a simple while loop. Buy a phone for the cost of 200 only until my bank account hits 500, but because it buys the phone first it only knows you dropped below 500 after it buys the phone.

In my code, it's buying until it takes the bankaccountmoney variable to 400:

var bankaccountmoney = 2000;
var phonesbought = 0;
var phonecost = 200;

while (bankaccountmoney > 500) {
  phonesbought = phonesbought + 1;
  bankaccountmoney = bankaccountmoney - phonecost;
  console.log("money: " + bankaccountmoney + " phonesbought: " + phonesbought);
}```

答:
var bankaccountmoney = 2000;
var phonesbought = 0;
var phonecost = 200;

while (bankaccountmoney >= (500 + phonecost)) {
  phonesbought++;
  bankaccountmoney -= phonecost;
  console.log("money left: " + bankaccountmoney + " phonesbought: " + phonesbought);
}```
</div>
</div>
</p>

<p>and here's a snippet if you instead have 100 as phone cost</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 bankaccountmoney = 2000;
var phonesbought = 0;
var phonecost = 100;

while (bankaccountmoney >= (500 + phonecost)) {
  phonesbought++;
  bankaccountmoney -= phonecost;
  console.log("money left: " + bankaccountmoney + " phonesbought: " + phonesbought);
}</code>```

Body:
var bankaccountmoney = 2000;
var phonesbought = 0;
var phonecost = 200;

while (bankaccountmoney >= (500 + phonecost)) {
  phonesbought++;
  bankaccountmoney -= phonecost;
  console.log("money left: " + bankaccountmoney + " phonesbought: " + phonesbought);
}

and here's a snippet if you instead have 100 as phone cost

var bankaccountmoney = 2000;
var phonesbought = 0;
var phonecost = 100;

while (bankaccountmoney >= (500 + phonecost)) {
  phonesbought++;
  bankaccountmoney -= phonecost;
  console.log("money left: " + bankaccountmoney + " phonesbought: " + phonesbought);
}


问:
How can I install and use ack library on Windows?
I have never used Perl, but I am really impressed by the ack, which I would like to use for source code searching, etc.

Can anyone guide me of how to make use of this excellent library on Windows?

答:
Not all the tests pass on all versions of Windows. You can most likely get 100% functionality from ack even if the install tests fail.  Here is the command to force installation if failing tests prevent a normal install:</p>

```<code>perl -MCPAN -e "CPAN::Shell->force(qw(install App::Ack));"
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Not all the tests pass on all versions of Windows. You can most likely get 100% functionality from ack even if the install tests fail.  Here is the command to force installation if failing tests prevent a normal install:

perl -MCPAN -e "CPAN::Shell->force(qw(install App::Ack));"


问:
How to add "Build path" option in Eclipse, when clicking on a project with right button?
As in a topic. I can not find solution, how to add that option to right button list.</p>

答: Right click on the project -> Search Project Facets -> Convert to faceted project -> Enable the builder (ex. Java)</p>


问:
Visual studio fatal error C1510: Cannot load language resource clui.dll. When installing pandas
I am trying to pip install pandas and i keep receiving this error:

```<code>      fatal error C1510: Cannot load language resource clui.dll.
      error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio
      14.0\\VC\\BIN\\amd64\\cl.exe' failed with exit status 4
</code>```

I tired uninstalling and repair but it still prompt me this error. Is there any ways i can fix this?

答:
I have a feeling that you must be using an old version of PIP.

It may sound simple but please try this code.

```<code>python -m pip install --upgrade pip
</code>```

Body:
I am trying to pip install pandas and i keep receiving this error:

      fatal error C1510: Cannot load language resource clui.dll.
      error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio
      14.0\\VC\\BIN\\amd64\\cl.exe' failed with exit status 4

I tired uninstalling and repair but it still prompt me this error. Is there any ways i can fix this?

Body:
I have a feeling that you must be using an old version of PIP.

It may sound simple but please try this code.

python -m pip install --upgrade pip


问:
Link not opening in system browser in ionic
I am in process of making an ionic application and trying to open a link in app using cordova.InAppBrowser but I get this error when I click it

```<code>Application Error
net::ERR_FILE_NOT_FOUND (file:///android_assets/www/(item.url))
</code>```

MY Code

```<code> <div ng-repeat="item in object.torrents" class="button-bar bar-dark" >
  <a onclick="window.open('(item.url)', '_system' );" class="button">Open</a>

</div>
</code>```

答:
```<code>Html Code
<a ng-click = openUrl(item.url); class="button">button</a>

js Code

$scope.openUrl = function(url) {
    //alert(url);
    window.open(url, '_blank', 'location=no');
  }
</code>```

Body:
I am in process of making an ionic application and trying to open a link in app using cordova.InAppBrowser but I get this error when I click it

Application Error
net::ERR_FILE_NOT_FOUND (file:///android_assets/www/(item.url))

MY Code

  Open


问:
Countdown timer, not displaying time
I currently have a countdown timer that resets every 24 hours but for some now it displays "NaN" instead of the time. I have a feeling it may be to do with the variables ?

Can someone please help me rectify what the issue may be ?

```<code>// Set the date we're counting down to
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var today = new Date();
var day = today.getDate();
var month = today.getMonth() ;
var year = today.getFullYear();
//alert(year); You can check the year from here
var countDownDate = new Date( monthNames[month] + day + "2017 24:00:00").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

// Get todays date and time
var now = new Date().getTime();

// Find the distance between now an the count down date
var distance = countDownDate - now;

// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);

if(hours < 10){
var hours = "0" + hours;

}
if(minutes<10){
var minutes = "0" + minutes;

}
if(seconds <10){
var seconds = "0" + seconds;
}

// Output the result in an element with id="demo"
document.getElementById("H_one").innerHTML = hours ;
document.getElementById("M_one").innerHTML = minutes;
document.getElementById("s_one").innerHTML = seconds ;

// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</code>```

答:
You need add spaces between monthNames[month], day and "2017 24:00:00"

Just use that example:

```<code>var countDownDate = new Date( monthNames[month] + " " + day + " 2017 24:00:00").getTime();
</code>```

Title: Countdown timer, not displaying time

Body:
I currently have a countdown timer that resets every 24 hours but for some now it displays "NaN" instead of the time. I have a feeling it may be to do with the variables ?

Can someone please help me rectify what the issue may be ?

// Set the date we're counting down to
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var today = new Date();
var day = today.getDate();
var month = today.getMonth() ;
var year = today.getFullYear();
//alert(year); You can check the year from here
var countDownDate = new Date( monthNames[month] + day + "2017 24:00:00").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

// Get todays date and time
var now = new Date().getTime();

// Find the distance between now an the count down date
var distance = countDownDate - now;

// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);

if(hours < 10){
var hours = "0" + hours;

}
if(minutes<10){
var minutes = "0" + minutes;

}
if(seconds <10){
var seconds = "0" + seconds;
}

// Output the result in an element with id="demo"
document.getElementById("H_one").innerHTML = hours ;
document.getElementById("M_one").innerHTML = minutes;
document.getElementById("s_one").innerHTML = seconds ;

// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);

Body:
You need add spaces between monthNames[month], day and "2017 24:00:00"

Just use that example:

var countDownDate = new Date( monthNames[month] + " " + day + " 2017 24:00:00").getTime();


问:
Does Jackson deserialise the second character to lowercase for a property
We've defined a model in our service code as -

```<code>@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class SomeData {

    public boolean tnAvailable;

    @NonNull
    public String sTempChange;

    public boolean isTnAvailable() {
       return faAvailable;
    }

    public void setTnAvailable(boolean faAvailable) {
        this.faAvailable = faAvailable;
    }

    @Nonnull
    public String getSTempChange() {
        return sTempChange;
    }

    public void setSTempChange(@Nonnull String sTempChange) {
        this.sTempChange = sTempChange;
    }

}
</code>```

When the api including the above model in response is queried , we get the response as -

```<code>"someData": {
    "tnAvailable": true,
    "stempChange": "trial_001"
}
</code>```

What surprised us was the stempChange(notice lowercase t) instead of sTempChange in the attributes of the response.

Suspecting the cause to be Jackson com.fasterxml.jackson.core:jackson-core:2.5.2 while serializing and deserializing of the objects during API calls since we do not alter the attribute using any other getter-setter ot wrapper.
Why would this so happen and is serialization/deserialization the correct direction to look for this?

Edit - From the comment by @Windle, trying to explain what's different here. I re-iterate "The question though there relates pretty much to the same situation. Yet I 'm looking forward to the reason's for such implementation and documentation in fasterxml as well."

答:
Yeah it looks like it's getting confused on the method name. You can force the serialized name with the @JsonGetter annotation</p>

```<code>@JsonGetter("sTempChange")
public String getSTempChange() {
    return sTempChange;
}
</code>```

Body:
We've defined a model in our service code as -

@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class SomeData {

    public boolean tnAvailable;

    @NonNull
    public String sTempChange;

    public boolean isTnAvailable() {
       return faAvailable;
    }

    public void setTnAvailable(boolean faAvailable) {
        this.faAvailable = faAvailable;
    }

    @Nonnull
    public String getSTempChange() {
        return sTempChange;
    }

    public void setSTempChange(@Nonnull String sTempChange) {
        this.sTempChange = sTempChange;
    }

}

When the api including the above model in response is queried , we get the response as -

"someData": {
    "tnAvailable": true,
    "stempChange": "trial_001"
}

What surprised us was the stempChange(notice lowercase t) instead of sTempChange in the attributes of the response.

Suspecting the cause to be Jackson com.fasterxml.jackson.core:jackson-core:2.5.2 while serializing and deserializing of the objects during API calls since we do not alter the attribute using any other getter-setter ot wrapper.
Why would this so happen and is serialization/deserialization the correct direction to look for this?

Edit - From the comment by @Windle, trying to explain what's different here. I re-iterate "The question though there relates pretty much to the same situation. Yet I 'm looking forward to the reason's for such implementation and documentation in fasterxml as well."

Body:
Yeah it looks like it's getting confused on the method name. You can force the serialized name with the @JsonGetter annotation

@JsonGetter("sTempChange")
public String getSTempChange() {
    return sTempChange;
}


问:
(C#) Unable to get the lowest value from an array containing doubles
I am still pretty new to C#, this is my second day coding.
I am unable to get the lowest Value from an array containing doubles.

for example:

```<code>double [] arr = { 5.5 , 6.5 , 8.19 };
double max = (arr.Min);
</code>```

This Code doesn't seem to work for me.

Any suggestions?

答:
```<code>double [] arr = { 5.5 , 6.5 , 8.19 };
double minimum = arr.Min();
</code>```

Note that this will give you an error if the array is empty. You can check first and then decide what to do if the array is empty:

```<code>double [] arr = { 5.5 , 6.5 , 8.19 };
double minimum = 0;

if (arr.Length > 0)
{
    minimum = arr.Min();
}
else
{
    // Add code to do something if the array is empty
}
</code>```

Body:
I am still pretty new to C#, this is my second day coding.
I am unable to get the lowest Value from an array containing doubles.

for example:

double [] arr = { 5.5 , 6.5 , 8.19 };
double max = (arr.Min);

This Code doesn't seem to work for me.

Any suggestions?

Body:
double [] arr = { 5.5 , 6.5 , 8.19 };
double minimum = arr.Min();

Note that this will give you an error if the array is empty. You can check first and then decide what to do if the array is empty:

double [] arr = { 5.5 , 6.5 , 8.19 };
double minimum = 0;

if (arr.Length > 0)
{
    minimum = arr.Min();
}
else
{
    // Add code to do something if the array is empty
}


问:
Filebeat: Outputting to different outputs depending on the document type
So I'm reading in several different file types using Filebeat. I set the document_type for each kind of file I am harvesting. My problem is that I want to send most of these file types to Logstash, but there are certain types I wish to send directly to Elasticsearch.

Is it possible to select the output depending on file type? I know multiple outputs are allowed, but this sends all the data into both elasticsearch and logstash so it's going to get inserted into Elasticsearch twice, which will take up too much space. Thanks!

答: Filebeat ships events to one endpoint, all routing should be done in Logstash.</p>


问:
How to display SPECIFIC laravel validation error in view, not all of them
The problem I am having is I have multiple validation rules on my date of birth field.

```<code>        @if($errors->has('dob'))
            <span id="helpBlock" class="help-block error">
                @foreach($errors->get('dob') as $message)
                    {{ $message }}
                @endforeach
            </span>
            <script>$('#dob').addClass('formError');</script>
        @endif
</code>```

This will print out ALL of the errors.

I only want to print out the 'required' validation rule if it gets triggered, I am handleing the other validation in the front end.

答:
I had this same issue a while back. You can only access the error message bag via its public methods, $errors->all(), $errors->get(), $errors->first() etc.The first two methods return numeric arrays of the messages. Therefore, there's no way to filter by the validation name. So the best thing is to know the order of the messages based on your validation rules. So if for example, 'required' is the second rule defined for that field, you can access it by using it's index. Like this.

```<code>@if($errors->has('dob'))
        <span id="helpBlock" class="help-block error">
                {{ $errors->get('dob')[1] }}
        </span>
        <script>$('#dob').addClass('formError');</script>
    @endif
</code>```

Sorry for bad english. Hope you understand. Have a nice day.

Body:
The problem I am having is I have multiple validation rules on my date of birth field.

        @if($errors->has('dob'))

                @foreach($errors->get('dob') as $message)
                    {{ $message }}
                @endforeach

        @endif

This will print out ALL of the errors.

I only want to print out the 'required' validation rule if it gets triggered, I am handleing the other validation in the front end.

Body:
I had this same issue a while back. You can only access the error message bag via its public methods, $errors->all(), $errors->get(), $errors->first() etc.The first two methods return numeric arrays of the messages. Therefore, there's no way to filter by the validation name. So the best thing is to know the order of the messages based on your validation rules. So if for example, 'required' is the second rule defined for that field, you can access it by using it's index. Like this.

@if($errors->has('dob'))
        <span id="helpBlock" class="help-block error">
                {{ $errors->get('dob')[1] }}
        </span>
        <script>$('#dob').addClass('formError');</script>
    @endif

Sorry for bad english. Hope you understand. Have a nice day.


问:
In a rails migration, how can you remove the limit of a field
Is the following correct?</p>

```<code> change_column :tablename, :fieldname, :limit => null
</code>```

答:
I was the same boat today, trying to remove a limit I'd added to a text field and it wouldn't take. Tried several migrations.

Rails 4.2.7.1
Ruby 2.3.1p112

In the end, the only thing that worked was specifying a limit of 255. Trying to adjust to anything else wouldn't work for me.

Body:
Is the following correct?

 change_column :tablename, :fieldname, :limit => null


问:
What is the difference between global_max_pool/global_avg_pool and avg_pool_2d/1d/3d?
I've tried to compare the tutorial code for text classification from tflearn : https://github.com/tflearn/tflearn/blob/master/examples/nlp/cnn_sentence_classification.py

And the one from dennybritz :
https://github.com/dennybritz/cnn-text-classification-tf

These 2 codes shows different result, i understand that it can be because the tflearn tutorial use 1d convolution, but there is one line of code that i don't understand:

network = global_max_pool(network)

What is the difference between global_max_pool and max_pool_2d?

答:
Looking at the code, they make different calls to the tensor flow library:

2d_max_pool

Does broadly what you would expect and returns (as well as doing some other things):

```<code>tf.nn.max_pool(incoming, kernel, strides, padding)
</code>```

With the specified arguments. This is a 4d tensor, similar to the input one

global_max_pool

Actually performs a pretty drastic reduction in the input tensor. The input tensor is of dimension:

```<code>[batch, height, width, in_channels]
</code>```

The function global_max_pool then returns (as well as doing some other things)

```<code>tf.reduce_max(incoming, [1, 2])
</code>```

I think gives the maximum value of each tensor along all of each of the in_channels

Body:
Looking at the code, they make different calls to the tensor flow library:

2d_max_pool

Does broadly what you would expect and returns (as well as doing some other things):

tf.nn.max_pool(incoming, kernel, strides, padding)

With the specified arguments. This is a 4d tensor, similar to the input one

global_max_pool

Actually performs a pretty drastic reduction in the input tensor. The input tensor is of dimension:

[batch, height, width, in_channels]

The function global_max_pool then returns (as well as doing some other things)

tf.reduce_max(incoming, [1, 2])

I think gives the maximum value of each tensor along all of each of the in_channels


问:
Double versus float
I have a constant for pi in my code:

const float PI = acos(-1);

Would it be better to declare it as a double?  An answer to another question on this site said floating point operations aren't exactly precise, and I'd like the constant to be accurate.

答:
"precise" is not a boolean concept. float provides a certain amount of precision. Whether or not that amount is sufficient for your application depends on, well, your application.

most applications don't need more precision than float provides, though many prefer to use double to (try and) gloss over problems with unstable algorithms or "just because" due to misconceptions like "floating point operations aren't exactly precise".

In most cases when a float is "not precise enough", the problem is not float, it's the code that uses it.

Edit: That being said, most modern CPUs only do calculations in double precision or greater anyway, so you might as well use double unless you're working with large arrays and memory usage is an issue.

Title: Double versus float


问:
Illegal string offset value in PHP - only two fields fail
I have two scripts, one which scrubs some HTML output from my system and returns an array of data (tournaments in this example).

When I var_dump this array you get the following output.

```<code>array(66) {
 [0]=>
  array(4) {
    ["date"]=>
    string(14) "2 January 2017"
    ["tournament"]=>
    string(43) "Brisbane International presented by Suncorp"
    ["surface"]=>
    string(10) "Hard Court"
    ["venue"]=>
    string(8) "Brisbane"
  }
 [1]=>
  array(4) {
   ["date"]=>
   string(14) "2 January 2017"
   ["tournament"]=>
   string(19) "Aircel Chennai Open"
   ["surface"]=>
   string(10) "Hard Court"
   ["venue"]=>
   string(7) "Chennai"
  }
</code>```

Here is the script that gets that data

```<code>function processTournamentHTML($url) {
    $domOb = new DomDocument();
    $html = $domOb->loadHTMLFile($url);
    $domOb->preserveWhiteSpace = false;
    $container = $domOb->getElementsByTagName('tr');

    $tournaments = array(); // BLANK ARRAY TO POPULATE

    // PROCESS THE TOURNAMENT HTML INTO A PHP ARRAY
    foreach($container as $row) {
        $items = $row->getElementsByTagName('td');
        $tournaments[] = array(
            "date" => $items->item(0)->nodeValue,
            "tournament" => $items->item(1)->nodeValue,
            "surface" => $items->item(2)->nodeValue,
            "venue" => $items->item(3)->nodeValue
        );
    }
    echo "Processing the following URL: " . $url;
    return $tournaments;
}
</code>```

And the script that inserts said data into my DB (all sample data).

```<code>function processTournaments($tournaments, $tour) {
    // OPEN CONNECTION
    $conn = mysqli_connect("test", "test", "test", "test");

    foreach($tournaments as $tournament) {
        $date = $tournament["date"];
        $tournament = $tournament["tournament"];
        $surface = $tournament["surface"];
        $venue = $tournament["venue"];
        $sql = "INSERT INTO data_table (date, tournament, surface, venue, tour) VALUES ($date, $tournament, $surface, $venue, $tour)";
        $query = mysqli_query($conn, $sql);
    }
    // CLOSE DB CONNECTION
    mysqli_close($conn);
    return "Finished processing for " . $tour;
}
</code>```

I run my code in URL/TO/FILE.php

```<code>$tournaments = processTournamentHTML($url);
processTournaments($tournaments, "tournament_code");
</code>```

As you can see my sample data has 66 records and I get these errors 66 times:

```<code>Warning: Illegal string offset 'surface' in URL/TO/FILE.PHP on line 47

Warning: Illegal string offset 'venue' in URL/TO/FILE.PHP on line 48
</code>```

And the sample HTML being processed

```<code><tr>
<td rowspan="3" width="133">2 January 2017</td>
<td width="294">Brisbane International presented by Suncorp</td>
<td width="90">Hard Court</td>
<td width="121">Brisbane</td>
</tr>
<tr>
<td rowspan="3" width="133">2 January 2017</td>
<td width="294">Shenzhen Open</td>
<td width="90">Hard Court</td>
<td width="121">Shenzhen</td>
</tr>
</code>```

SOLVED

I eventually solved this because I was using the following code:

```<code>foreach($tournaments as $tournament) {
  $date = $tournament["date"];
  $tournament = $tournament["tournament"]; // WHEN YOU SEE IT
  $surface = $tournament["surface"];
  $venue = $tournament["venue"];
}
</code>```

When you see it, its so annoying. I was using $tournament as a variable inside my foreach and it was overwriting the $tournament index I was on. -_-

答:
You have

"surface" => $items->item(2)->nodeValue,
 "venue" => $items->item(3)->nodeValue

but you dont have anything in the position item[2] and item[3] which you can see from your var dump

```<code>array(66) {
[0]=>
array(4) {
["date"]=>
string(14) "2 January 2017"
["tournament"]=>
string(43) "Brisbane International presented by Suncorp"
["surface"]=>
string(10) "Hard Court"
["venue"]=>
string(8) "Brisbane"
}
[1]=>
array(4) {
["date"]=>
string(14) "2 January 2017"
["tournament"]=>
string(19) "Aircel Chennai Open"
["surface"]=>
string(10) "Hard Court"
["venue"]=>
string(7) "Chennai"
}
</code>```

In the above array you have only two indexes. There is no [2] and [3]

Body:
I have two scripts, one which scrubs some HTML output from my system and returns an array of data (tournaments in this example).

When I var_dump this array you get the following output.

array(66) {
 [0]=>
  array(4) {
    ["date"]=>
    string(14) "2 January 2017"
    ["tournament"]=>
    string(43) "Brisbane International presented by Suncorp"
    ["surface"]=>
    string(10) "Hard Court"
    ["venue"]=>
    string(8) "Brisbane"
  }
 [1]=>
  array(4) {
   ["date"]=>
   string(14) "2 January 2017"
   ["tournament"]=>
   string(19) "Aircel Chennai Open"
   ["surface"]=>
   string(10) "Hard Court"
   ["venue"]=>
   string(7) "Chennai"
  }

Here is the script that gets that data

function processTournamentHTML($url) {
    $domOb = new DomDocument();
    $html = $domOb->loadHTMLFile($url);
    $domOb->preserveWhiteSpace = false;
    $container = $domOb->getElementsByTagName('tr');

    $tournaments = array(); // BLANK ARRAY TO POPULATE

    // PROCESS THE TOURNAMENT HTML INTO A PHP ARRAY
    foreach($container as $row) {
        $items = $row->getElementsByTagName('td');
        $tournaments[] = array(
            "date" => $items->item(0)->nodeValue,
            "tournament" => $items->item(1)->nodeValue,
            "surface" => $items->item(2)->nodeValue,
            "venue" => $items->item(3)->nodeValue
        );
    }
    echo "Processing the following URL: " . $url;
    return $tournaments;
}

And the script that inserts said data into my DB (all sample data).

function processTournaments($tournaments, $tour) {
    // OPEN CONNECTION
    $conn = mysqli_connect("test", "test", "test", "test");

    foreach($tournaments as $tournament) {
        $date = $tournament["date"];
        $tournament = $tournament["tournament"];
        $surface = $tournament["surface"];
        $venue = $tournament["venue"];
        $sql = "INSERT INTO data_table (date, tournament, surface, venue, tour) VALUES ($date, $tournament, $surface, $venue, $tour)";
        $query = mysqli_query($conn, $sql);
    }
    // CLOSE DB CONNECTION
    mysqli_close($conn);
    return "Finished processing for " . $tour;
}

I run my code in URL/TO/FILE.php

$tournaments = processTournamentHTML($url);
processTournaments($tournaments, "tournament_code");

As you can see my sample data has 66 records and I get these errors 66 times:

Warning: Illegal string offset 'surface' in URL/TO/FILE.PHP on line 47

Warning: Illegal string offset 'venue' in URL/TO/FILE.PHP on line 48

And the sample HTML being processed

2 January 2017
Brisbane International presented by Suncorp
Hard Court
Brisbane

2 January 2017
Shenzhen Open
Hard Court
Shenzhen

SOLVED

I eventually solved this because I was using the following code:

foreach($tournaments as $tournament) {
  $date = $tournament["date"];
  $tournament = $tournament["tournament"]; // WHEN YOU SEE IT
  $surface = $tournament["surface"];
  $venue = $tournament["venue"];
}

When you see it, its so annoying. I was using $tournament as a variable inside my foreach and it was overwriting the $tournament index I was on. -_-

Body:
You have

"surface" => $items->item(2)->nodeValue,
 "venue" => $items->item(3)->nodeValue

but you dont have anything in the position item[2] and item[3] which you can see from your var dump

array(66) {
[0]=>
array(4) {
["date"]=>
string(14) "2 January 2017"
["tournament"]=>
string(43) "Brisbane International presented by Suncorp"
["surface"]=>
string(10) "Hard Court"
["venue"]=>
string(8) "Brisbane"
}
[1]=>
array(4) {
["date"]=>
string(14) "2 January 2017"
["tournament"]=>
string(19) "Aircel Chennai Open"
["surface"]=>
string(10) "Hard Court"
["venue"]=>
string(7) "Chennai"
}

In the above array you have only two indexes. There is no [2] and [3]


问:
Boolean use for decision making
Basically I want to do a method that is used to make decision, which when the HitshipPercentage is less than 50 and the shots is not equal to zero, it will use the method public space fire(). I am not sure how to use the boolean  in the correct way.

```<code>public Space fire()
{
 System.out.println("Hi");
}

     public boolean hitRateAnalysis()
 {

     if (HitShipPercentage < 50 && Shots!=0)

      return true;

     else{
     return false;
     }
 }
</code>```

答:
Your code has a few errors in it, the fire() method is of type Space which means it's supposed to return a Space.  I don't think this is what you want, my guess is fire isn't supposed to return anything in which case it should be void.

```<code>public void fire() {
    System.out.println("Hi");
}

public boolean hitRateAnalysis() {
    if (HitShipPercentage < 50 && Shots!=0)  {
        fire();
        return true;
    }
    return false;
}
</code>```

Title: Boolean use for decision making

Body:
Basically I want to do a method that is used to make decision, which when the HitshipPercentage is less than 50 and the shots is not equal to zero, it will use the method public space fire(). I am not sure how to use the boolean  in the correct way.

public Space fire()
{
 System.out.println("Hi");
}

     public boolean hitRateAnalysis()
 {

     if (HitShipPercentage < 50 && Shots!=0)

      return true;

     else{
     return false;
     }
 }

Body:
Your code has a few errors in it, the fire() method is of type Space which means it's supposed to return a Space.  I don't think this is what you want, my guess is fire isn't supposed to return anything in which case it should be void.

public void fire() {
    System.out.println("Hi");
}

public boolean hitRateAnalysis() {
    if (HitShipPercentage < 50 && Shots!=0)  {
        fire();
        return true;
    }
    return false;
}


问:
Creating a bleed margin with a PDF with Imagemagick
Is there a way that I can use the convert from imagemagick command to create a bleed margin in a PDF or even view one?

答:
Bleed is a very common print technique, and ImageMagick offers the concept of "Virtual Pixels" which are the pixels located on the plane outside of "Authentic Pixels".

For example...

Take the following image

```<code>convert rose: rose.png
</code>```

Set new viewport, and bleed virtual pixel across edge.

```<code>convert rose.png -set option:distort:viewport 90x66-10-10 \
        -virtual-pixel Edge -filter point \
        -distort SRT 0 +repage output.png
</code>```

I bit more creativity (and maths) to include trim lines.

```<code>convert \( \
   -size 110x86 xc:white -fill none -strokewidth 1 -stroke black \
   -draw "path 'M 20 0 V 85 M 89 0 V 85 M 0 20 H 110 M 0 65 H 110'" \) \
   \( output.png -repage +10+10 \) -layers merge \
   output_with_trim.png
</code>```

Body:
Bleed is a very common print technique, and ImageMagick offers the concept of "Virtual Pixels" which are the pixels located on the plane outside of "Authentic Pixels".

For example...

Take the following image

convert rose: rose.png

Set new viewport, and bleed virtual pixel across edge.

convert rose.png -set option:distort:viewport 90x66-10-10 \
        -virtual-pixel Edge -filter point \
        -distort SRT 0 +repage output.png

I bit more creativity (and maths) to include trim lines.

convert \( \
   -size 110x86 xc:white -fill none -strokewidth 1 -stroke black \
   -draw "path 'M 20 0 V 85 M 89 0 V 85 M 0 20 H 110 M 0 65 H 110'" \) \
   \( output.png -repage +10+10 \) -layers merge \
   output_with_trim.png


问:
how to rename sql server tabs
I used to be able to  rename the tabs in sql server in my old company. The sql server looks the same in my current company, but i'm not able to completely rename the tabs, and it gets confusing when many tabs are open.

(I'm able to add new names to the name that's already there. e.g. the tab is now called "SQLQuery20.sqlComputernameuser". And I'm able to rename it to "NewnameSQLQuery20.sqlComputernameuser". But I would like it to just be called "Newname" instead.)

Thank you!

答:
Short answer: you can sort of do this still, but with SSMS 2012 and later, you're limited to using the sql file name, db name, etc. and you can't just type in the name directly anymore.  The solution linked to below still should be helpful for you!

See this question I found titled Manually Rename Tabs in SSMS

Good luck! Please mark this as the answer if it's sufficient for you :)

Title: how to rename sql server tabs


问:
Why can't I share my ShinyApp with shinyapps.io?
I have created a ShinyApp in R, which works fine locally. But when I try to put it on shinyapps.io, it points to the line where I read in a CSV file and says
"Paths should be to files within the project directory".

The CSV file and the app.R file are in my working directory.

答:
When you upload a shiny app to shinyapps.io, all companion files need to be inside a folder named "data" in the same directory where the app.R file is.

Solution:

Create a "data" folder where your app.R file is

Copy your CSV file there

Update your code accordingly i.e. mydata <- read.csv('data/mydata.csv')

Try uploading to shinyapps.io again


问:
GMP gives wrong result of a series expansion
I am using the GMP package to implement the product of two functions which I express as a cauchy product of two convergent series.

In more detail: I am looking for a way to calculate f(x)=g(x)*h(x) where g(x) is the exponential function and h(x) is a special hypergeometric function (see below), both expressed as series.

My problem is that this works and agrees with my own approximation and wolframalpha's results for x<29, but fails for x>29. In practice I need values of about x=10^6.

The 3 formulas I used are depicted in the image below:

The Code

```<code>void invfak(mpf_t invn, unsigned int n) //Calculates inverse factorial, !/n!
{
        unsigned int i;
        mpf_t k;

        mpf_init_set_d(k,1.0);
        mpf_init_set_d(invn,0.0);
        i=2;

        for (i = 2; i <= n; ++i) {
            mpf_mul_ui(k, k, i);
        }

        mpf_ui_div(invn,1.0,k);
        mpf_clear(k);
}

 void E2F2E(mpf_t result, long double x, unsigned int N)
{
        mpf_t Q1,Q2;          ///gives Nth term in series expansion of exp(x)

        mpf_init_set_d(Q1,x);
        mpf_init_set_d(Q2,0.0);
        mpf_init_set_d(result,0.0);

        mpf_pow_ui(Q1,Q1,N); /// Q1=Q1^N=x^N
        invfak(Q2,N);       /// Q2=1/N!

        mpf_mul(result,Q1,Q2); ///result= Q1*Q2 = x^N/N!

        mpf_clear(Q1);
        mpf_clear(Q2);

}

void E2F2F(mpf_t result, long double x, unsigned int N)
{
        mpf_t Q1,Q2,Q3;         ///gives Nth term in series expansion of 2F2

        mpf_init_set_d(Q1,(N+x)*(N+x));
        mpf_init_set_d(Q2,-x);
        mpf_init_set_d(Q3,0.0);
        mpf_init_set_d(result,0.0);

        mpf_pow_ui(Q2,Q2,N+2);    /// Q2=Q2^(N+2)=(-x)^(N+2)
        invfak(Q3,N);             /// Q3=1/N!
        mpf_mul(Q2,Q2,Q3);        /// Q2=Q2*Q3

        mpf_div(result,Q2,Q1); ///result= Q2/Q1 = .../(N+x)^2

        mpf_clear(Q1);    mpf_clear(Q3);    mpf_clear(Q2)
    }

void Exp2F2gmp(mpf_t result, long double x, unsigned int N)
{
       mpf_t Q1,Qexp,Q2F2,Qsum;
       mpf_init_set_d(Q1,0.0);
       mpf_init_set_d(Qexp,0.0);
       mpf_init_set_d(Q2F2,0.0);
       mpf_init_set_d(Qsum,0.0);

       mpf_init_set_d(result,0.0);

       for(unsigned i = 0; i <= N; ++i){
               mpf_set_d(Qsum,0.0);
               mpf_set_d(Qexp,0.0);
               mpf_set_d(Q2F2,0.0);

               for(unsigned l = 0; l <= i; ++l){ /// a_l und b_i-l
                   E2F2E(Qexp,x,l);
                   E2F2F(Q2F2,x,i-l);
                   mpf_mul(Q1,Qexp,Q2F2);
                   mpf_add(Qsum,Qsum,Q1);
               }
               mpf_add(result,result,Qsum);
               mpf_abs(Qsum,Qsum);
              //if(mpf_cmp_d(Qsum,0.00000001)==-1){ cout << "reached precision at i="<<i; break;}
       }
       cout <<  "\n\n Result = " << result << endl;
       mpf_clear(Q1);
       mpf_clear(Qexp);
       mpf_clear(Q2F2);
       mpf_clear(Qsum);

}
</code>```

The function f(x) should approximately go as f(x)=1.05x+1 and also, f(x)>0 for x>0.

But the implementation gives this:

Exp2F2gmp(Q,10,1000) = 12.3707

Exp2F2gmp(Q,20,1000) = 23.1739

Exp2F2gmp(Q,30,1000) = -35195.1

Exp2F2gmp(Q,40,1000) = -2.92079e+13

The first two values agree with Wolframalpha, the second two obviously dont.

Any kind of help would be appreciated, thank you!

答:
This is a textbook example of catastrophic cancellation.

The terms in the 2F2 series grow to a maximum size of about exp(x), but the magnitude of the 2F2 function is about exp(-x). This means that you need to use at least log_2(exp(2x)) ~= 2.886*x extra bits of precision to compute the 2F2 series accurately, and possibly slightly more depending on how the terms are computed.

So for example, if x = 29, you need about 83 bits of precision. Your code uses the default precision of the MPF type, which I believe is something like 64 bits. You need to change the code to set the precision of all MPF variables to 64 + 2.886*x bits to get 64 accurate bits (see the GMP manual for how to do this).

In practice, the series evaluation as you have implemented is not very efficient, and will probably be too slow for x = 1e6.

One possibility is to use the Arb library (which I develop). This supports computing generalized hypergeometric functions out of the box and uses a much more efficient series evaluation strategy (in this case, using binary splitting). It also uses interval arithmetic, so you get error bounds for free and can set the precision automatically instead of predicting the needed precision in advance (but in this case predicting the precision is easy, and faster).

Here is code demonstrating how to use it:

```<code>#include "acb_hypgeom.h"

int main()
{
    acb_t z, t;
    acb_struct a[2];
    acb_struct b[2];
    double x;

    acb_init(z); acb_init(t);
    acb_init(a + 0); acb_init(a + 1);
    acb_init(b + 0); acb_init(b + 1);

    for (x = 10.0; x <= 1000000; x *= 10)
    {
        acb_set_d(a + 0, x);
        acb_set_d(a + 1, x);
        acb_set_d(b + 0, x + 1);
        acb_set_d(b + 1, x + 1);
        acb_set_d(z, -x);
        acb_hypgeom_pfq(t, a, 2, b, 2, z, 0, 64 + 2.886 * x);
        acb_neg(z, z);
        acb_exp(z, z, 64);
        acb_mul(t, t, z, 64);
        printf("f(%f) = ", x); acb_printn(t, 20, 0); printf("\n");
    }

    acb_clear(z); acb_clear(t);
    acb_clear(a + 0); acb_clear(a + 1);
    acb_clear(b + 0); acb_clear(b + 1);
}
</code>```

Here is the output:

```<code>f(10.000000) = [12.37067931727649929 +/- 5.38e-18]
f(100.000000) = [106.6161729468899444 +/- 4.93e-17]
f(1000.000000) = [1020.154983574938368 +/- 3.54e-16]
f(10000.000000) = [10063.00061277849954 +/- 2.57e-15]
f(100000.000000) = [100198.5001942224819 +/- 6.28e-14]
f(1000000.000000) = [1000626.990558714621 +/- 4.59e-13]
</code>```

At x = 1e6, the evaluation takes about 20 seconds (your code would take far, far longer) as a result of 2.9 million bits being used. If this is still too slow, you need to find a better formula to compute f(x), ideally an asymptotic expansion valid when x -> infinity, or perhaps an integral representation (if there is one without cancellation issues).

Now, if your 2F2 function only depended on x in the final argument and had the first four parameters fixed, there would be a standard formula for this asymptotic expansion, but with the growing parameters involved, I'm not exactly sure how to do it. Since the upper and lower parameters almost "cancel out", it might work to treat them as constants and use the standard asymptotic series with respect to the argument, but I did not check this. Someone with more expertise in asymptotic analysis would have to comment.

It's also possible that you could use contiguous relations to reduce the 2F2 function to something with small parameters, but I'm not sure if this would be an improvement in practice.

Body:
I am using the GMP package to implement the product of two functions which I express as a cauchy product of two convergent series.

In more detail: I am looking for a way to calculate f(x)=g(x)*h(x) where g(x) is the exponential function and h(x) is a special hypergeometric function (see below), both expressed as series.

My problem is that this works and agrees with my own approximation and wolframalpha's results for x<29, but fails for x>29. In practice I need values of about x=10^6.

The 3 formulas I used are depicted in the image below:

The Code

void invfak(mpf_t invn, unsigned int n) //Calculates inverse factorial, !/n!
{
        unsigned int i;
        mpf_t k;

        mpf_init_set_d(k,1.0);
        mpf_init_set_d(invn,0.0);
        i=2;

        for (i = 2; i <= n; ++i) {
            mpf_mul_ui(k, k, i);
        }

        mpf_ui_div(invn,1.0,k);
        mpf_clear(k);
}

 void E2F2E(mpf_t result, long double x, unsigned int N)
{
        mpf_t Q1,Q2;          ///gives Nth term in series expansion of exp(x)

        mpf_init_set_d(Q1,x);
        mpf_init_set_d(Q2,0.0);
        mpf_init_set_d(result,0.0);

        mpf_pow_ui(Q1,Q1,N); /// Q1=Q1^N=x^N
        invfak(Q2,N);       /// Q2=1/N!

        mpf_mul(result,Q1,Q2); ///result= Q1*Q2 = x^N/N!

        mpf_clear(Q1);
        mpf_clear(Q2);

}

void E2F2F(mpf_t result, long double x, unsigned int N)
{
        mpf_t Q1,Q2,Q3;         ///gives Nth term in series expansion of 2F2

        mpf_init_set_d(Q1,(N+x)*(N+x));
        mpf_init_set_d(Q2,-x);
        mpf_init_set_d(Q3,0.0);
        mpf_init_set_d(result,0.0);

        mpf_pow_ui(Q2,Q2,N+2);    /// Q2=Q2^(N+2)=(-x)^(N+2)
        invfak(Q3,N);             /// Q3=1/N!
        mpf_mul(Q2,Q2,Q3);        /// Q2=Q2*Q3

        mpf_div(result,Q2,Q1); ///result= Q2/Q1 = .../(N+x)^2

        mpf_clear(Q1);    mpf_clear(Q3);    mpf_clear(Q2)
    }

void Exp2F2gmp(mpf_t result, long double x, unsigned int N)
{
       mpf_t Q1,Qexp,Q2F2,Qsum;
       mpf_init_set_d(Q1,0.0);
       mpf_init_set_d(Qexp,0.0);
       mpf_init_set_d(Q2F2,0.0);
       mpf_init_set_d(Qsum,0.0);

       mpf_init_set_d(result,0.0);

       for(unsigned i = 0; i <= N; ++i){
               mpf_set_d(Qsum,0.0);
               mpf_set_d(Qexp,0.0);
               mpf_set_d(Q2F2,0.0);

               for(unsigned l = 0; l <= i; ++l){ /// a_l und b_i-l
                   E2F2E(Qexp,x,l);
                   E2F2F(Q2F2,x,i-l);
                   mpf_mul(Q1,Qexp,Q2F2);
                   mpf_add(Qsum,Qsum,Q1);
               }
               mpf_add(result,result,Qsum);
               mpf_abs(Qsum,Qsum);
              //if(mpf_cmp_d(Qsum,0.00000001)==-1){ cout << "reached precision at i="<<i; break;}
       }
       cout <<  "\n\n Result = " << result << endl;
       mpf_clear(Q1);
       mpf_clear(Qexp);
       mpf_clear(Q2F2);
       mpf_clear(Qsum);

}

The function f(x) should approximately go as f(x)=1.05x+1 and also, f(x)>0 for x>0.

But the implementation gives this:

Exp2F2gmp(Q,10,1000) = 12.3707

Exp2F2gmp(Q,20,1000) = 23.1739

Exp2F2gmp(Q,30,1000) = -35195.1

Exp2F2gmp(Q,40,1000) = -2.92079e+13

The first two values agree with Wolframalpha, the second two obviously dont.

Any kind of help would be appreciated, thank you!

Body:
This is a textbook example of catastrophic cancellation.

The terms in the 2F2 series grow to a maximum size of about exp(x), but the magnitude of the 2F2 function is about exp(-x). This means that you need to use at least log_2(exp(2x)) ~= 2.886*x extra bits of precision to compute the 2F2 series accurately, and possibly slightly more depending on how the terms are computed.

So for example, if x = 29, you need about 83 bits of precision. Your code uses the default precision of the MPF type, which I believe is something like 64 bits. You need to change the code to set the precision of all MPF variables to 64 + 2.886*x bits to get 64 accurate bits (see the GMP manual for how to do this).

In practice, the series evaluation as you have implemented is not very efficient, and will probably be too slow for x = 1e6.

One possibility is to use the Arb library (which I develop). This supports computing generalized hypergeometric functions out of the box and uses a much more efficient series evaluation strategy (in this case, using binary splitting). It also uses interval arithmetic, so you get error bounds for free and can set the precision automatically instead of predicting the needed precision in advance (but in this case predicting the precision is easy, and faster).

Here is code demonstrating how to use it:

#include "acb_hypgeom.h"

int main()
{
    acb_t z, t;
    acb_struct a[2];
    acb_struct b[2];
    double x;

    acb_init(z); acb_init(t);
    acb_init(a + 0); acb_init(a + 1);
    acb_init(b + 0); acb_init(b + 1);

    for (x = 10.0; x <= 1000000; x *= 10)
    {
        acb_set_d(a + 0, x);
        acb_set_d(a + 1, x);
        acb_set_d(b + 0, x + 1);
        acb_set_d(b + 1, x + 1);
        acb_set_d(z, -x);
        acb_hypgeom_pfq(t, a, 2, b, 2, z, 0, 64 + 2.886 * x);
        acb_neg(z, z);
        acb_exp(z, z, 64);
        acb_mul(t, t, z, 64);
        printf("f(%f) = ", x); acb_printn(t, 20, 0); printf("\n");
    }

    acb_clear(z); acb_clear(t);
    acb_clear(a + 0); acb_clear(a + 1);
    acb_clear(b + 0); acb_clear(b + 1);
}

Here is the output:

f(10.000000) = [12.37067931727649929 +/- 5.38e-18]
f(100.000000) = [106.6161729468899444 +/- 4.93e-17]
f(1000.000000) = [1020.154983574938368 +/- 3.54e-16]
f(10000.000000) = [10063.00061277849954 +/- 2.57e-15]
f(100000.000000) = [100198.5001942224819 +/- 6.28e-14]
f(1000000.000000) = [1000626.990558714621 +/- 4.59e-13]

At x = 1e6, the evaluation takes about 20 seconds (your code would take far, far longer) as a result of 2.9 million bits being used. If this is still too slow, you need to find a better formula to compute f(x), ideally an asymptotic expansion valid when x -> infinity, or perhaps an integral representation (if there is one without cancellation issues).

Now, if your 2F2 function only depended on x in the final argument and had the first four parameters fixed, there would be a standard formula for this asymptotic expansion, but with the growing parameters involved, I'm not exactly sure how to do it. Since the upper and lower parameters almost "cancel out", it might work to treat them as constants and use the standard asymptotic series with respect to the argument, but I did not check this. Someone with more expertise in asymptotic analysis would have to comment.

It's also possible that you could use contiguous relations to reduce the 2F2 function to something with small parameters, but I'm not sure if this would be an improvement in practice.


问:
How to fill the primeng
 with FirebaseObservableList?
I´m trying to fill my datatable () with my firebase database content. But I don´t know how to use the *ngFor like I used in a normal table.
The normal way is done:

```<code><tr *ngFor="let docu of documentos | async">
  <td>{{docu.nombre}}</td>
  <td>{{docu.tipoDocumento}}</td>
  <td  >{{docu.usuario}}</td>
  <td  >{{docu.grupo}}</td>
  <td width="20%"><a class="btn btn-success" target="_blank" href="{{docu.enlaceDescarga}}">Ver</a></td>
</tr>
</code>```

It fills perfectly.
But now I want to use PrimeNG

```<code><p-dataTable [value]="" *ngFor='let docu of documentos | async'>
<p-column field={{docu.nombre}} header="Nombre"></p-column>
<p-column field="year" header="Tipo"></p-column>
<p-column field="brand" header="Permiso de usuario"></p-column>
<p-column field="color" header="Permiso de grupo"></p-column>
<p-column field="color" header="Enlace"></p-column></p-dataTable>
</code>```

My problen is [value], I don´t know how to fill an array with a FirebaseObservableList.
I retrieve the the list with this:

```<code>documentos: FirebaseListObservable<any> = af.database.list('/Documentos');
</code>```

af is my AngularFire on constructor.

Some ideas?

答:
```<code>  <p-dataTable [value]="documentos | async" align="center" [rows]="10" [paginator]="true" [globalFilter]="gb" #dt>
<p-column field="nombre" header="Nombre" [sortable]=true [filter]="true" filterPlaceholder="Buscar"></p-column>
<p-column field="tipoDocumento" header="Tipo documento" [sortable]=true></p-column>
<p-column field="usuario" header="Permisos de usuario" [sortable]=true [filter]="true" filterPlaceholder="Buscar"></p-column>
<p-column field="grupo" header="Permisos de grupo " [sortable]=true [filter]="true" filterPlaceholder="Buscar"></p-column>
<p-column field="enlaceDescarga" header="Enlace"></p-column>
</code>```

Title: How to fill the primeng <p-datatable> with FirebaseObservableList?

Body:
I´m trying to fill my datatable () with my firebase database content. But I don´t know how to use the *ngFor like I used in a normal table.
The normal way is done:

  {{docu.nombre}}
  {{docu.tipoDocumento}}
  {{docu.usuario}}
  {{docu.grupo}}
  Ver

It fills perfectly.
But now I want to use PrimeNG

My problen is [value], I don´t know how to fill an array with a FirebaseObservableList.
I retrieve the the list with this:

documentos: FirebaseListObservable<any> = af.database.list('/Documentos');

af is my AngularFire on constructor.

Some ideas?


问:
How to query a table with multiple values in one column with join
Table 1:

```<code>A       B       C
Test    1       This
Test1   1;4     That
Test2   7       What
Test3   6;2     Which
Test4   1;2;7   Where
</code>```

Table 2:

```<code>X       Z
1       Sun
2       Mon
3       Tue
4       Wed
5       Thu
6       Fri
7       Sat
</code>```

Sql:

```<code>Select
    t1.A,
    t2.Z
from
    [dbo].[Table 1] t1
    inner join [dbo].[Table2] t2
    on t1.B = t2.X
</code>```

It works only for the rows that has only 1 entry in B column but fails at the 2 or more entries.

How can I modify the Sql so that it gives me the result like this:

```<code>A       Z
Test    Sun
Test1   Sun;Wed
Test2   Sat
Test3   Fri;Mon
Test4   Sun;Mon;Sat
</code>```

答:
You really should not store multiple values in the same column, it will only lead to poor performance whenever you actually have to do something with those values.

Using a CSV Splitter table valued function by Jeff Moden and the using the stuff() with select ... for xml path ('') method of string concatenation. :

```<code>select
    t1.a
  , z = stuff((
      select ';'+t2.Z
      from t1 i
        cross apply dbo.delimitedsplit8K(i.b,';') s
        inner join t2
          on s.Item = t2.x
      where i.a = t1.a
      order by s.ItemNumber
      for xml path(''),type).value('(./text())[1]','nvarchar(max)')
    ,1,1,'')
from t1
</code>```

rextester demo:

returns: http://rextester.com/HNNP95095

```<code>+-------+-------------+
|   a   |      z      |
+-------+-------------+
| Test  | Sun         |
| Test1 | Sun;Wed     |
| Test2 | Sat         |
| Test3 | Fri;Mon     |
| Test4 | Sun;Mon;Sat |
+-------+-------------+
</code>```

splitting strings reference:

Tally OH! An Improved SQL 8K “CSV Splitter” Function - Jeff Moden

Splitting Strings : A Follow-Up - Aaron Bertrand

Split strings the right way – or the next best way - Aaron Bertrand

string_split() in SQL Server 2016 : Follow-Up #1 - Aaron Bertrand

The function by Jeff Moden used for the demo:

```<code>create function [dbo].[delimitedsplit8K] (
      @pstring varchar(8000)
    , @pdelimiter char(1)
  )
returns table with schemabinding as
 return
  with e1(N) as (
    select 1 union all select 1 union all select 1 union all
    select 1 union all select 1 union all select 1 union all
    select 1 union all select 1 union all select 1 union all select 1
  )
  , e2(N) as (select 1 from e1 a, e1 b)
  , e4(N) as (select 1 from e2 a, e2 b)
  , ctetally(N) as (
    select top (isnull(datalength(@pstring),0))
      row_number() over (order by (select null)) from e4
  )
  , ctestart(N1) as (
    select 1 union all
    select t.N+1 from ctetally t where substring(@pstring,t.N,1) = @pdelimiter
  )
  , ctelen(N1,L1) as (
    select s.N1,
      isnull(nullif(charindex(@pdelimiter,@pstring,s.N1),0)-s.N1,8000)
    from ctestart s
  )
 select itemnumber = row_number() over(order by l.N1)
      , item       = substring(@pstring, l.N1, l.L1)
   from ctelen l
;
go
</code>```

Body:
Table 1:

A       B       C
Test    1       This
Test1   1;4     That
Test2   7       What
Test3   6;2     Which
Test4   1;2;7   Where

Table 2:

X       Z
1       Sun
2       Mon
3       Tue
4       Wed
5       Thu
6       Fri
7       Sat

Sql:

Select
    t1.A,
    t2.Z
from
    [dbo].[Table 1] t1
    inner join [dbo].[Table2] t2
    on t1.B = t2.X

It works only for the rows that has only 1 entry in B column but fails at the 2 or more entries.

How can I modify the Sql so that it gives me the result like this:

A       Z
Test    Sun
Test1   Sun;Wed
Test2   Sat
Test3   Fri;Mon
Test4   Sun;Mon;Sat

Body:
You really should not store multiple values in the same column, it will only lead to poor performance whenever you actually have to do something with those values.

Using a CSV Splitter table valued function by Jeff Moden and the using the stuff() with select ... for xml path ('') method of string concatenation. :

select
    t1.a
  , z = stuff((
      select ';'+t2.Z
      from t1 i
        cross apply dbo.delimitedsplit8K(i.b,';') s
        inner join t2
          on s.Item = t2.x
      where i.a = t1.a
      order by s.ItemNumber
      for xml path(''),type).value('(./text())[1]','nvarchar(max)')
    ,1,1,'')
from t1

rextester demo:

returns: http://rextester.com/HNNP95095

+-------+-------------+
|   a   |      z      |
+-------+-------------+
| Test  | Sun         |
| Test1 | Sun;Wed     |
| Test2 | Sat         |
| Test3 | Fri;Mon     |
| Test4 | Sun;Mon;Sat |
+-------+-------------+

splitting strings reference:

Tally OH! An Improved SQL 8K “CSV Splitter” Function - Jeff Moden

Splitting Strings : A Follow-Up - Aaron Bertrand

Split strings the right way – or the next best way - Aaron Bertrand

string_split() in SQL Server 2016 : Follow-Up #1 - Aaron Bertrand

The function by Jeff Moden used for the demo:

create function [dbo].[delimitedsplit8K] (
      @pstring varchar(8000)
    , @pdelimiter char(1)
  )
returns table with schemabinding as
 return
  with e1(N) as (
    select 1 union all select 1 union all select 1 union all
    select 1 union all select 1 union all select 1 union all
    select 1 union all select 1 union all select 1 union all select 1
  )
  , e2(N) as (select 1 from e1 a, e1 b)
  , e4(N) as (select 1 from e2 a, e2 b)
  , ctetally(N) as (
    select top (isnull(datalength(@pstring),0))
      row_number() over (order by (select null)) from e4
  )
  , ctestart(N1) as (
    select 1 union all
    select t.N+1 from ctetally t where substring(@pstring,t.N,1) = @pdelimiter
  )
  , ctelen(N1,L1) as (
    select s.N1,
      isnull(nullif(charindex(@pdelimiter,@pstring,s.N1),0)-s.N1,8000)
    from ctestart s
  )
 select itemnumber = row_number() over(order by l.N1)
      , item       = substring(@pstring, l.N1, l.L1)
   from ctelen l
;
go


问:
Selecting a random value from a subsection of an enum
Given a Swift enum as such:

```<code>enum PerformerPosition: Int {

    case String_Violin1
    case String_Violin2
    case String_Viola
    case String_Cello
    case String_CB

    case Wind_Oboe
    case Wind_Clarinet
    case Wind_Flute
    ...

}
</code>```

(For the needs of the project, I am not able to have a nested enum.) I would like to randomly select an enum value with the String_ prefix, only.

The only way I know so far is to do a random enum value from all the available cases, as such:

```<code>private static let _count: PerformerPosition.RawValue = {
    // find the maximum enum value
    var maxValue: Int = 0
    while let _ = PerformerPosition(rawValue: maxValue) {
        maxValue += 1
    }
    return maxValue
}()

static func randomPerformer() -> PerformerPosition {
    // pick and return a new value
    let rand = arc4random_uniform(UInt32(count))
    return PlayerPosition(rawValue: Int(rand))!
}
</code>```

How could I make it so I am able to pick a random value based on the String_ prefix only without having to resort to hard-coding an upper value (for example, new String_ prefix positions may be added)? Thanks

答:
I made this in PlayGround:</p>

```<code>func randomPerformer() -> PerformerPosition {
    // pick and return a new value
    let rand = arc4random_uniform(_count)
    let string = String(describing:PerformerPosition(rawValue: rand))
    if(string.contains("String_")){
            return PerformerPosition(rawValue: rand)!
    }else{
            return randomPerformer()
    }
}
</code>```

Body:
Given a Swift enum as such:

enum PerformerPosition: Int {

    case String_Violin1
    case String_Violin2
    case String_Viola
    case String_Cello
    case String_CB

    case Wind_Oboe
    case Wind_Clarinet
    case Wind_Flute
    ...

}

(For the needs of the project, I am not able to have a nested enum.) I would like to randomly select an enum value with the String_ prefix, only.

The only way I know so far is to do a random enum value from all the available cases, as such:

private static let _count: PerformerPosition.RawValue = {
    // find the maximum enum value
    var maxValue: Int = 0
    while let _ = PerformerPosition(rawValue: maxValue) {
        maxValue += 1
    }
    return maxValue
}()

static func randomPerformer() -> PerformerPosition {
    // pick and return a new value
    let rand = arc4random_uniform(UInt32(count))
    return PlayerPosition(rawValue: Int(rand))!
}

How could I make it so I am able to pick a random value based on the String_ prefix only without having to resort to hard-coding an upper value (for example, new String_ prefix positions may be added)? Thanks

Body:
I made this in PlayGround:

func randomPerformer() -> PerformerPosition {
    // pick and return a new value
    let rand = arc4random_uniform(_count)
    let string = String(describing:PerformerPosition(rawValue: rand))
    if(string.contains("String_")){
            return PerformerPosition(rawValue: rand)!
    }else{
            return randomPerformer()
    }
}


问:
How to run the commands inside the mininet prompt using python scripts from outside
I am new to mininet. I want to run the mininet commands to run from the python scripts like "nodes","dump". I can create the topology but cannot use these commands through my script. I am using Ubuntu 14.04.

```<code>import subprocess as sb
import os
print "Single Switch and 4 Hosts per switch topology"
print "Creation of topology"
os.system(" sudo mn --topo = single,4",shell=True)
os.system("nodes")
</code>```

Error:

```<code>sh: 1: nodes: not found
32512
</code>```

I do not want to create a topology through python script, I only want to use the mininet commands.

答: Glad I found this question. I have a sub-question of a very similar nature. I understand that you can execute a command into the mininet CLI from python using e.g. h1.cmd('ifconfig') , but is there a way to do the same from python to the mininet> prompt ? i.e. not pointing it to a specific host in the topology (I am simulating faults so some hosts are disconnected). Something like net.cmd('python module.py') ? @Abhimanyu singh  @nir0s

Body:
I am new to mininet. I want to run the mininet commands to run from the python scripts like "nodes","dump". I can create the topology but cannot use these commands through my script. I am using Ubuntu 14.04.

import subprocess as sb
import os
print "Single Switch and 4 Hosts per switch topology"
print "Creation of topology"
os.system(" sudo mn --topo = single,4",shell=True)
os.system("nodes")

Error:

sh: 1: nodes: not found
32512

I do not want to create a topology through python script, I only want to use the mininet commands.


问:
.Net windows services: install from referenced assembly
There are lots of examples how to install windows service in one line:

```<code>    ManagedInstallClass.InstallHelper(
      new[] { Assembly.GetExecutingAssembly().Location });
</code>```

That works fine until service class is declared in exe module.
But the same code doesn't work for me if service class is in referrenced assembly (not declared in executable, but in linked dll).

In such a case service is registered as well but can't be started as it is registered with dll path and points to dll ("service is not a win32 executable" message appears in event log when I try to start that)

If I change GetExecutingAssembly().Location to executable path, then no installers are found and service is not registered at all.

Is it possible to put service class into referenced assembly and still have ability to register service with minimum effort?

Thank you in advance!

答:
here is some C# code that allows you to install/uninstall a service" manually" (without the need to declare custom RunInstaller attributes):</p>

```<code>static void InstallService(string path, string name, string displayName, string description)
{
    ServiceInstaller si = new ServiceInstaller();
    ServiceProcessInstaller spi = new ServiceProcessInstaller();
    si.Parent = spi;
    si.DisplayName = displayName;
    si.Description = description;
    si.ServiceName = name;
    si.StartType = ServiceStartMode.Manual;

    // update this if you want a different log
    si.Context = new InstallContext("install.log", null);
    si.Context.Parameters["assemblypath"] = path;

    IDictionary stateSaver = new Hashtable();
    si.Install(stateSaver);
}

static void UninstallService(string name)
{
    ServiceInstaller si = new ServiceInstaller();
    ServiceProcessInstaller spi = new ServiceProcessInstaller();
    si.Parent = spi;
    si.ServiceName = name;

    // update this if you want a different log
    si.Context = new InstallContext("uninstall.log", null);
    si.Uninstall(null);
}
</code>```

Body:
There are lots of examples how to install windows service in one line:

    ManagedInstallClass.InstallHelper(
      new[] { Assembly.GetExecutingAssembly().Location });

That works fine until service class is declared in exe module.
But the same code doesn't work for me if service class is in referrenced assembly (not declared in executable, but in linked dll).

In such a case service is registered as well but can't be started as it is registered with dll path and points to dll ("service is not a win32 executable" message appears in event log when I try to start that)

If I change GetExecutingAssembly().Location to executable path, then no installers are found and service is not registered at all.

Is it possible to put service class into referenced assembly and still have ability to register service with minimum effort?

Thank you in advance!

Body:
here is some C# code that allows you to install/uninstall a service" manually" (without the need to declare custom RunInstaller attributes):

static void InstallService(string path, string name, string displayName, string description)
{
    ServiceInstaller si = new ServiceInstaller();
    ServiceProcessInstaller spi = new ServiceProcessInstaller();
    si.Parent = spi;
    si.DisplayName = displayName;
    si.Description = description;
    si.ServiceName = name;
    si.StartType = ServiceStartMode.Manual;

    // update this if you want a different log
    si.Context = new InstallContext("install.log", null);
    si.Context.Parameters["assemblypath"] = path;

    IDictionary stateSaver = new Hashtable();
    si.Install(stateSaver);
}

static void UninstallService(string name)
{
    ServiceInstaller si = new ServiceInstaller();
    ServiceProcessInstaller spi = new ServiceProcessInstaller();
    si.Parent = spi;
    si.ServiceName = name;

    // update this if you want a different log
    si.Context = new InstallContext("uninstall.log", null);
    si.Uninstall(null);
}


问:
Printing a barcode font on a POS printer
I am trying to use CreateFont to load a Code 128 font so I can output a barcode on a slip. CreateFont is not returning NULL but seems to be failing to find the correct font and is loading something else as I get the code printed as plain text.

This is the barcode function.

```<code>void EpicSlipPrinter::addBarcode ( const QString& text )
{
  HFONT tempFont = CreateFont ( 60 , 0 , 0 , 0 , 0 ,0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , L"Code 128" );
  oFont = (HFONT)SelectObject ( mPrinterHandle , tempFont );

  INT ixPosition = iPaperWidth / 2;

  SIZE sz = getTextDimensions ( text , 3 , 3 , 600 , 0 , 0 );

  SetTextAlign ( mPrinterHandle , TA_CENTER );

  TextOut ( mPrinterHandle , ixPosition , iyPosition , text , text.length () );

  SelectObject ( mPrinterHandle , oFont );
  DeleteObject( tempFont );
}
</code>```

The text parameter is definitely correct so what I think is happening is that CreateFont can't find the specified font and is defaulting to something else. The font is correctly loaded and can be selected from Windows applications, if I type the code into Word then I  get a barcode that can be read from a scanner.

My question is does anyone know why CreateFont is not loading Code 128 or if there is another problem I am missing?

答: You've specified 0 for the fdwCharSet, which corresponds to ANSI_CHARSET, so the font mapper is looking for something that supports the current code page.  Try using SYMBOL_CHARSET for these kinds of specialty fonts.</p>

Body:
I am trying to use CreateFont to load a Code 128 font so I can output a barcode on a slip. CreateFont is not returning NULL but seems to be failing to find the correct font and is loading something else as I get the code printed as plain text.

This is the barcode function.

void EpicSlipPrinter::addBarcode ( const QString& text )
{
  HFONT tempFont = CreateFont ( 60 , 0 , 0 , 0 , 0 ,0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , L"Code 128" );
  oFont = (HFONT)SelectObject ( mPrinterHandle , tempFont );

  INT ixPosition = iPaperWidth / 2;

  SIZE sz = getTextDimensions ( text , 3 , 3 , 600 , 0 , 0 );

  SetTextAlign ( mPrinterHandle , TA_CENTER );

  TextOut ( mPrinterHandle , ixPosition , iyPosition , text , text.length () );

  SelectObject ( mPrinterHandle , oFont );
  DeleteObject( tempFont );
}

The text parameter is definitely correct so what I think is happening is that CreateFont can't find the specified font and is defaulting to something else. The font is correctly loaded and can be selected from Windows applications, if I type the code into Word then I  get a barcode that can be read from a scanner.

My question is does anyone know why CreateFont is not loading Code 128 or if there is another problem I am missing?


问:
Azure Files: System error 64 has occurred
I have Azure Files Preview enabled to my Azure account. I have created a new storage account, created a share following the instructions.

Now when I try to map the share to a network drive (just as the aforementioned article says), I get the following error:

```<code>net use z: \\mystorageaccount.file.core.windows.net\share /u:mystorageaccount mystorageaccountkey
</code>```

System error 64 has occurred.

The specified network name is no longer available.

What causes this?

答:
To update the current answer, one can now map from OnPremise if the OS supports SMB 3.0. As per Get started with Azure File storage on Windows - Mount the file share it states (emphasis mine):

With support for SMB 3.0, File storage now supports encryption and
  persistent handles from SMB 3.0 clients. Support for encryption means
  that SMB 3.0 clients can mount a file share from anywhere, including
  from:

An Azure virtual machine in the same region (also supported by SMB
  2.1)

An Azure virtual machine in a different region (SMB 3.0 only)

An on-premises client application (SMB 3.0 only)

and lists the OS's and their SMB versions.

Body:
I have Azure Files Preview enabled to my Azure account. I have created a new storage account, created a share following the instructions.

Now when I try to map the share to a network drive (just as the aforementioned article says), I get the following error:

net use z: \\mystorageaccount.file.core.windows.net\share /u:mystorageaccount mystorageaccountkey

System error 64 has occurred.

The specified network name is no longer available.

What causes this?


问:
How to secure assets files in Android
I need to store audio files in the application. Access to these files should be restricted. How can I safely store these files?

I tried to store in the assets folder, but when unpacking the apk, these files can be obtained.

Also I used the extension files as a zip archive, however, this file can be assigned and the files can be retrieved by the user.

Is there a way to store files so that the user can not get them?

答:
Is there a way to store files so that the user can not get them?

What commonware answered doesn't solve the problem. hackers can reverse engineer it to get url where you download the assets or else get the file data from the memory by runtime hooking or debugging.

In fact there is no solution for this, but what security experts tries to do is just make it costs a lot then the data will bring.

If your application's asset is very important then I suggests following things.

Encrypt the asset file with symmetric cryptography such as AES

Make key in the way hackers cannot simply identifies it. ( consider White-box Cryptography )

You can use obfuscation software to confuse reverse engineer ( such as proguard, dexguard etc... )

Every time you use it, decrypt it.

To defend hooking and debugging, implement some debugging check, rooting check and integrity check as a security.

I know above methods are hard to implement, if the assets worth it, you should consider these approach.

Title: How to secure assets files in Android


问:
Read 'n' lines from file and assign each line to distinct variable
I generate a text file based on nodes in the cluster.

```<code>cat primary_nodes.txt
clusterNodea
clusterNodeb
..
....
clusterNoden
</code>```

While I try to generate variable for each line, it gives me following output

```<code>while read PRIMARY_NODE$((i++)); do
echo $PRIMARY_NODE1
echo $PRIMARY_NODE2
done < primary_node.txt

clusterNodea
clusterNodea
clusterNodeb
</code>```

What I want is:

It should return total no.of nodes

Each line should be assigned to PRIMARY_NODE1...n variable incrementally

Return all variable with its value.

答:
The Right Thing: An Array

In bash 4:

```<code>readarray -t primary_node <primary_node.txt
</code>```

Thereafter:

```<code>echo "${primary_node[0]}" # clusterNodea
echo "${primary_node[1]}" # clusterNodeb
</code>```

Or to iterate over the values:

```<code>for node in "${primary_node[@]}"; do
  echo "Processing node $node"
done
</code>```

The Wrong Thing: Distinct Variables

```<code>i=0
while IFS= read -r line; do
  printf -v "primary_node$((i++))" '%s' "$line"
done <primary_node.txt

echo "$primary_node1"
</code>```

References

BashFAQ #1 - "How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?"

BashFAQ #5 - "How can I use array variables?"

BashFAQ #6 - "How can I use variable variables (indirect variables, pointers, references) or associative arrays?"

Body:
I generate a text file based on nodes in the cluster.

cat primary_nodes.txt
clusterNodea
clusterNodeb
..
....
clusterNoden

While I try to generate variable for each line, it gives me following output

while read PRIMARY_NODE$((i++)); do
echo $PRIMARY_NODE1
echo $PRIMARY_NODE2
done < primary_node.txt

clusterNodea
clusterNodea
clusterNodeb

What I want is:

It should return total no.of nodes

Each line should be assigned to PRIMARY_NODE1...n variable incrementally

Return all variable with its value.

Body:
The Right Thing: An Array

In bash 4:

readarray -t primary_node <primary_node.txt

Thereafter:

echo "${primary_node[0]}" # clusterNodea
echo "${primary_node[1]}" # clusterNodeb

Or to iterate over the values:

for node in "${primary_node[@]}"; do
  echo "Processing node $node"
done

The Wrong Thing: Distinct Variables

i=0
while IFS= read -r line; do
  printf -v "primary_node$((i++))" '%s' "$line"
done <primary_node.txt

echo "$primary_node1"

References

BashFAQ #1 - "How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?"

BashFAQ #5 - "How can I use array variables?"

BashFAQ #6 - "How can I use variable variables (indirect variables, pointers, references) or associative arrays?"