问:
Condition Variables C#/.NET
In my quest to build a condition variable class I stumbled on a trivially simple way of doing it and I'd like to share this with the stack overflow community. I was googling for the better part of an hour and was unable to actually find a good tutorial or .NET-ish example that felt right, hopefully this can be of use to other people out there.</p>

答:
i think i found "The WAY" on the tipical problem of a

```<code>List<string> log;
</code>```

used by multiple thread, one tha fill it and the other processing and the other one empting

avoiding empty

```<code>    while(true){
    //stuff
    Thread.Sleep(100)
    }
</code>```

variables used in Program

```<code>    public static readonly List<string> logList = new List<string>();

    public static EventWaitHandle evtLogListFilled = new AutoResetEvent(false);
</code>```

the processor work like

```<code>private void bw_DoWorkLog(object sender, DoWorkEventArgs e)
    {
        StringBuilder toFile = new StringBuilder();
        while (true)
        {
            try
            {
                {
                    //waiting form a signal
                    Program.evtLogListFilled.WaitOne();
                    try
                    {
                        //critical section
                        Monitor.Enter(Program.logList);
                        int max = Program.logList.Count;
                        for (int i = 0; i < max; i++)
                        {
                            SetText(Program.logList[0]);
                            toFile.Append(Program.logList[0]);
                            toFile.Append("\r\n");
                            Program.logList.RemoveAt(0);
                        }
                    }
                    finally
                    {
                        Monitor.Exit(Program.logList);
                        // end critical section
                    }

                    try
                    {
                        if (toFile.Length > 0)
                        {
                            Logger.Log(toFile.ToString().Substring(0, toFile.Length - 2));
                            toFile.Clear();
                        }
                    }
                    catch
                    {

                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log(System.Reflection.MethodBase.GetCurrentMethod(), ex);
            }
            Thread.Sleep(100);

        }
    }
</code>```

On the filler thread we have

```<code>public static void logList_add(string str)
    {
        try
        {
            try
            {
                //critical section
                Monitor.Enter(Program.logList);
                Program.logList.Add(str);
            }
            finally
            {
                Monitor.Exit(Program.logList);
                //end critical section
            }
            //set start
            Program.evtLogListFilled.Set();

        }
        catch{}

    }
</code>```

this solution is fully tested, the istruction Program.evtLogListFilled.Set(); may release the lock on Program.evtLogListFilled.WaitOne() and also the next future lock.

I think this is the simpliest way.

Title: Condition Variables C#/.NET

Body:
i think i found "The WAY" on the tipical problem of a

List<string> log;

used by multiple thread, one tha fill it and the other processing and the other one empting

avoiding empty

    while(true){
    //stuff
    Thread.Sleep(100)
    }

variables used in Program

    public static readonly List<string> logList = new List<string>();

    public static EventWaitHandle evtLogListFilled = new AutoResetEvent(false);

the processor work like

private void bw_DoWorkLog(object sender, DoWorkEventArgs e)
    {
        StringBuilder toFile = new StringBuilder();
        while (true)
        {
            try
            {
                {
                    //waiting form a signal
                    Program.evtLogListFilled.WaitOne();
                    try
                    {
                        //critical section
                        Monitor.Enter(Program.logList);
                        int max = Program.logList.Count;
                        for (int i = 0; i < max; i++)
                        {
                            SetText(Program.logList[0]);
                            toFile.Append(Program.logList[0]);
                            toFile.Append("\r\n");
                            Program.logList.RemoveAt(0);
                        }
                    }
                    finally
                    {
                        Monitor.Exit(Program.logList);
                        // end critical section
                    }

                    try
                    {
                        if (toFile.Length > 0)
                        {
                            Logger.Log(toFile.ToString().Substring(0, toFile.Length - 2));
                            toFile.Clear();
                        }
                    }
                    catch
                    {

                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log(System.Reflection.MethodBase.GetCurrentMethod(), ex);
            }
            Thread.Sleep(100);

        }
    }

On the filler thread we have

public static void logList_add(string str)
    {
        try
        {
            try
            {
                //critical section
                Monitor.Enter(Program.logList);
                Program.logList.Add(str);
            }
            finally
            {
                Monitor.Exit(Program.logList);
                //end critical section
            }
            //set start
            Program.evtLogListFilled.Set();

        }
        catch{}

    }

this solution is fully tested, the istruction Program.evtLogListFilled.Set(); may release the lock on Program.evtLogListFilled.WaitOne() and also the next future lock.

I think this is the simpliest way.


来源: stackexchange

问:
Javascript sum of arrays and average
I have an issue with getting the sum of two arrays and combining their averages while rounding off.

I don't want to hardcode but rather pass two random arrays.
so here is the code but it keeps returning NaN

function sumAverage(arr) {
  var result = 0;
  // Your code here
  // set an array
  arr = [];
  a = [];
  b = [];
  arr[0] = a;
  arr[1] = b;

  var sum = 0;

  // compute sum of elements in the array
  for (var j = 0; j < a.length; j++) {
    sum += a[j];
  }

  // get the  average of elements in the array
  var total = 0;
  total += sum / a.length;

  var add = 0;

  for (var i = 0; i < b.length; i++)
    add += b[i];

  var math = 0;
  math += add / b.length;

  result += math + total;

  Math.round(result);

  return result;
}
console.log(sumAverage([
  [2, 3, 4, 5],
  [6, 7, 8, 9]
]));```

答:
I suggest to use two nested loops, one for the outer array and one for the inner arrays. Then sum values, calculate the average and add averages.

function sumAverage(array) {
    var result = 0,
        sum,
        i, j;

    for (i = 0; i < array.length; i++) {
        sum = 0;
        for (j = 0; j < array[i].length; j++) {
            sum += array[i][j];
        }
        result += Math.round(sum / array[i].length);
    }
    return result;
}

console.log(sumAverage([[2, 3, 4, 5], [6, 7, 8, 9]])); // 12```

ContentLicense: CC BY-SA 3.0

Title: Javascript sum of arrays and average


问:
Java orm problem
There is a big table business_apply in our system. It's used to store business apply information, and contains hundreds of columns.

When business type differs, a column may mean different things.

What kind of orm framework can make our life easier? Hibernate, iBatis or something else?

答: JPA - any implementation will do. Use a single-table inheritance strategy to fit all the classes in a single table. You will need to identify a discriminator column. You should be able to use the same column in multiple subclasses to mean different things (maybe - it's worth a go, anyway).</p>

ContentLicense: CC BY-SA 2.5

Title: Java orm problem


问:
Selenium - Chrome binary ignored
I prefer to use old Selenium 2.53.1 with old version of Chromium 52.0 and chromedriver 2.24. I'm running following on Windows 7:

```<code>start java -jar selenium-server-standalone-2.53.1.jar -Dwebdriver.chrome.driver=C:\dev\selenium\chromedriver.exe -Dwebdriver.chrome.binary=C:\dev\selenium\chrome-win32\chrome.exe -Dwebdriver.chrome.chrome_binary=C:\dev\selenium\chrome-win32\chrome.exe -Dwebdriver.chrome.capabilities.binary=C:\dev\selenium\chrome-win32\chrome.exe -Dwebdriver.chrome.capabilities.chrome_binary=C:\dev\selenium\chrome-win32\chrome.exe -browser browserName="chrome",version=ANY,platform=WINDOWS,maxInstances=1,binary="C:\dev\selenium\chrome-win32\chrome.exe",chrome_binary="C:\dev\selenium\chrome-win32\chrome.exe" -host 0.0.0.0 -port 4444
</code>```

As you can see I have tried a lot of variants trying both binary and chrome_binary. But Selenium Server ignores those options and starts a default Chrome Browser. How to make it run the binary I specified C:\dev\selenium\chrome-win32\chrome.exe?

```<code>09:22:53.149 INFO - Launching a standalone Selenium Server
Setting system property webdriver.chrome.driver to C:\dev\selenium\chromedriver.exe
Setting system property webdriver.chrome.binary to C:\dev\selenium\chrome-win32\chrome.exe
Setting system property webdriver.chrome.chrome_binary to C:\dev\selenium\chrome-win32\chrome.exe
Setting system property webdriver.chrome.capabilities.binary to C:\dev\selenium\chrome-win32\chrome.exe
Setting system property webdriver.chrome.capabilities.chrome_binary to C:\dev\selenium\chrome-win32\chrome.exe
09:22:53.480 INFO - Java: Oracle Corporation 25.65-b01
09:22:53.480 INFO - OS: Windows 7 6.1 amd64
09:22:53.490 INFO - v2.53.1, with Core v2.53.1. Built from revision a36b8b1
09:22:53.569 INFO - Driver class not found: com.opera.core.systems.OperaDriver
09:22:53.569 INFO - Driver provider com.opera.core.systems.OperaDriver is not registered
09:22:53.579 INFO - Driver provider org.openqa.selenium.safari.SafariDriver registration is skipped:
registration capabilities Capabilities [{browserName=safari, version=, platform=MAC}] does not match the current platform VISTA
09:22:53.579 INFO - Driver class not found: org.openqa.selenium.htmlunit.HtmlUnitDriver
09:22:53.579 INFO - Driver provider org.openqa.selenium.htmlunit.HtmlUnitDriver is not registered
09:22:53.928 INFO - RemoteWebDriver instances should connect to: http://127.0.0.1:4444/wd/hub
09:22:53.928 INFO - Selenium Server is up and running
09:22:54.331 INFO - Executing: [new session: Capabilities [{acceptSslCerts=false, browserName=chrome, platform=ANY}]])
09:22:54.345 INFO - Creating a new session for Capabilities [{acceptSslCerts=false, browserName=chrome, platform=ANY}]
Starting ChromeDriver 2.24.417431 (9aea000394714d2fbb20850021f6204f2256b9cf) onport 4923
Only local connections are allowed.
09:22:55.137 INFO - Done: [new session: Capabilities [{acceptSslCerts=false, browserName=chrome, platform=ANY}]]
</code>```

Related (unaswered):

How to specify the Chrome binary location via the selenium server standalone command line?

答:
Seems using Selenium Grid everything works:</p>

```<code>start java -Dwebdriver.server.session.timeout=900 -jar selenium-server-standalone-2.53.1.jar -role hub -host 0.0.0.0 -port 4444
start java -Dwebdriver.chrome.driver=C:\dev\selenium\chromedriver.exe -jar selenium-server-standalone-2.53.1.jar -role node -browser browserName="chrome",version=ANY,platform=WINDOWS,maxInstances=1,chrome_binary="C:\dev\selenium\chrome-win32\chrome.exe" -hub http://127.0.0.1:4444/grid/register -port 5555
</code>```

Title: Selenium - Chrome binary ignored

Body:
I prefer to use old Selenium 2.53.1 with old version of Chromium 52.0 and chromedriver 2.24. I'm running following on Windows 7:

start java -jar selenium-server-standalone-2.53.1.jar -Dwebdriver.chrome.driver=C:\dev\selenium\chromedriver.exe -Dwebdriver.chrome.binary=C:\dev\selenium\chrome-win32\chrome.exe -Dwebdriver.chrome.chrome_binary=C:\dev\selenium\chrome-win32\chrome.exe -Dwebdriver.chrome.capabilities.binary=C:\dev\selenium\chrome-win32\chrome.exe -Dwebdriver.chrome.capabilities.chrome_binary=C:\dev\selenium\chrome-win32\chrome.exe -browser browserName="chrome",version=ANY,platform=WINDOWS,maxInstances=1,binary="C:\dev\selenium\chrome-win32\chrome.exe",chrome_binary="C:\dev\selenium\chrome-win32\chrome.exe" -host 0.0.0.0 -port 4444

As you can see I have tried a lot of variants trying both binary and chrome_binary. But Selenium Server ignores those options and starts a default Chrome Browser. How to make it run the binary I specified C:\dev\selenium\chrome-win32\chrome.exe?

09:22:53.149 INFO - Launching a standalone Selenium Server
Setting system property webdriver.chrome.driver to C:\dev\selenium\chromedriver.exe
Setting system property webdriver.chrome.binary to C:\dev\selenium\chrome-win32\chrome.exe
Setting system property webdriver.chrome.chrome_binary to C:\dev\selenium\chrome-win32\chrome.exe
Setting system property webdriver.chrome.capabilities.binary to C:\dev\selenium\chrome-win32\chrome.exe
Setting system property webdriver.chrome.capabilities.chrome_binary to C:\dev\selenium\chrome-win32\chrome.exe
09:22:53.480 INFO - Java: Oracle Corporation 25.65-b01
09:22:53.480 INFO - OS: Windows 7 6.1 amd64
09:22:53.490 INFO - v2.53.1, with Core v2.53.1. Built from revision a36b8b1
09:22:53.569 INFO - Driver class not found: com.opera.core.systems.OperaDriver
09:22:53.569 INFO - Driver provider com.opera.core.systems.OperaDriver is not registered
09:22:53.579 INFO - Driver provider org.openqa.selenium.safari.SafariDriver registration is skipped:
registration capabilities Capabilities [{browserName=safari, version=, platform=MAC}] does not match the current platform VISTA
09:22:53.579 INFO - Driver class not found: org.openqa.selenium.htmlunit.HtmlUnitDriver
09:22:53.579 INFO - Driver provider org.openqa.selenium.htmlunit.HtmlUnitDriver is not registered
09:22:53.928 INFO - RemoteWebDriver instances should connect to: http://127.0.0.1:4444/wd/hub
09:22:53.928 INFO - Selenium Server is up and running
09:22:54.331 INFO - Executing: [new session: Capabilities [{acceptSslCerts=false, browserName=chrome, platform=ANY}]])
09:22:54.345 INFO - Creating a new session for Capabilities [{acceptSslCerts=false, browserName=chrome, platform=ANY}]
Starting ChromeDriver 2.24.417431 (9aea000394714d2fbb20850021f6204f2256b9cf) onport 4923
Only local connections are allowed.
09:22:55.137 INFO - Done: [new session: Capabilities [{acceptSslCerts=false, browserName=chrome, platform=ANY}]]

Related (unaswered):

How to specify the Chrome binary location via the selenium server standalone command line?

Body:
Seems using Selenium Grid everything works:

start java -Dwebdriver.server.session.timeout=900 -jar selenium-server-standalone-2.53.1.jar -role hub -host 0.0.0.0 -port 4444
start java -Dwebdriver.chrome.driver=C:\dev\selenium\chromedriver.exe -jar selenium-server-standalone-2.53.1.jar -role node -browser browserName="chrome",version=ANY,platform=WINDOWS,maxInstances=1,chrome_binary="C:\dev\selenium\chrome-win32\chrome.exe" -hub http://127.0.0.1:4444/grid/register -port 5555


问:
Flower Http Api get Celery task details
I have a working celery flower project.

Now I want some celery failed task details using flower http api, but  my celery is using --basic-auth for authentication and when I make a request at flower http api on http://localhost:5555/api/tasks it timeouts and does not show any results.

I did not understand if this is an auth problem or something else. I look to flower docs but i did not get any idea. Thanks for you time. Below is the code that is not working for me.

```<code>import requests

params = (('state', 'FAILURE'),('limit', '5'),)

requests.get('http://localhost:5555/api/tasks', params=params)
</code>```

答:
Then you should make your request with your credentials:

Import HTTPBasicAuth (since you are using --basic-auth):

```<code>from requests.auth import HTTPBasicAuth
</code>```

Make an authenticated request:

```<code>requests.get(
    'http://localhost:5555/api/tasks',
    auth=HTTPBasicAuth('your_user', 'your_pass'),
    params=params
)
</code>```

Good luck :)

Title: Flower Http Api get Celery task details

Body:
I have a working celery flower project.

Now I want some celery failed task details using flower http api, but  my celery is using --basic-auth for authentication and when I make a request at flower http api on http://localhost:5555/api/tasks it timeouts and does not show any results.

I did not understand if this is an auth problem or something else. I look to flower docs but i did not get any idea. Thanks for you time. Below is the code that is not working for me.

import requests

params = (('state', 'FAILURE'),('limit', '5'),)

requests.get('http://localhost:5555/api/tasks', params=params)

Body:
Then you should make your request with your credentials:

Import HTTPBasicAuth (since you are using --basic-auth):

from requests.auth import HTTPBasicAuth

Make an authenticated request:

requests.get(
    'http://localhost:5555/api/tasks',
    auth=HTTPBasicAuth('your_user', 'your_pass'),
    params=params
)

Good luck :)


问:
Java Eclipse Paho Implementation - Auto reconnect
I'm trying to implement eclipse.paho in my project to connect Mqtt Broker (Both subscribing and publishing purpose). The problem is, when I using the subscribing feature (Implementing MqttCallback interface), I couldn't figure our how can I reconnect if the connection lost. MqttCallback interface has a connectionLost method, but it is useful for the debug what causes the connection lost. I searched but couldn't find a way to establish auto reconnect. Can you suggest a way or document about this problem?

答:
To use auto reconnect, just set setAutomaticReconnect(true) on the MqttConnectOptions object.

```<code>MqttAndroidClient mqttClient = new MqttAndroidClient(context, mqttUrl, clientId);

MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setAutomaticReconnect(true);

mqttClient.connect(mqttConnectOptions, null, mqttActionListener());
</code>```

ContentLicense: CC BY-SA 4.0

Body:
To use auto reconnect, just set setAutomaticReconnect(true) on the MqttConnectOptions object.

MqttAndroidClient mqttClient = new MqttAndroidClient(context, mqttUrl, clientId);

MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setAutomaticReconnect(true);

mqttClient.connect(mqttConnectOptions, null, mqttActionListener());


问:
Assigning text to a local variable in Typescript
In Typescript I am trying to read an XML file with some javascript code and add the text content to a local variable with the following code:

```<code>import { Injectable } from '@angular/core';

@Injectable()
export class JsonreaderService {

private jsonText: string;

constructor() {
  this.readTextFile("../../assets/content.json");
}

readTextFile(file)
{
  let jsonText: string;
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", file, false);
  rawFile.onreadystatechange = function ()
  {
    if(rawFile.readyState === 4)
    {
      if(rawFile.status === 200 || rawFile.status == 0)
      {
        this.jsonText = rawFile.responseText;
      }
    }
  }
  rawFile.send(null);
}
}
</code>```

I am trying to assign the text within the json file to my private local variable jsonText: this.jsonText = rawFile.responseText; which are both of the type 'string'.

When I try this I get the error:

Property 'jsonText' does not exist on type 'XMLHttpRequest'

Does somebody know how I can do this within typescript? When I remove this. - the responseText can be defined to the jsonText variable which is within the function readTextFile(file)

答:
Use an arrow function to save the scope of this:

```<code>readTextFile(file)
{
  let jsonText: string;
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", file, false);
  rawFile.onreadystatechange = () =>
  {
    if(rawFile.readyState === 4)
    {
      if(rawFile.status === 200 || rawFile.status == 0)
      {
        this.jsonText = rawFile.responseText;
      }
    }
  }
  rawFile.send(null);
}
</code>```

Body:
In Typescript I am trying to read an XML file with some javascript code and add the text content to a local variable with the following code:

import { Injectable } from '@angular/core';

@Injectable()
export class JsonreaderService {

private jsonText: string;

constructor() {
  this.readTextFile("../../assets/content.json");
}

readTextFile(file)
{
  let jsonText: string;
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", file, false);
  rawFile.onreadystatechange = function ()
  {
    if(rawFile.readyState === 4)
    {
      if(rawFile.status === 200 || rawFile.status == 0)
      {
        this.jsonText = rawFile.responseText;
      }
    }
  }
  rawFile.send(null);
}
}

I am trying to assign the text within the json file to my private local variable jsonText: this.jsonText = rawFile.responseText; which are both of the type 'string'.

When I try this I get the error:

Property 'jsonText' does not exist on type 'XMLHttpRequest'

Does somebody know how I can do this within typescript? When I remove this. - the responseText can be defined to the jsonText variable which is within the function readTextFile(file)

Body:
Use an arrow function to save the scope of this:

readTextFile(file)
{
  let jsonText: string;
  var rawFile = new XMLHttpRequest();
  rawFile.open("GET", file, false);
  rawFile.onreadystatechange = () =>
  {
    if(rawFile.readyState === 4)
    {
      if(rawFile.status === 200 || rawFile.status == 0)
      {
        this.jsonText = rawFile.responseText;
      }
    }
  }
  rawFile.send(null);
}


问:
Excel VBA: Merging a range inside a loop

I want to merge that repeating Chapters into just one cell by Chapter.

Here is how my code does the looping.

```<code>        Dim label As Control
        Dim itm As Object
        For ctr = 1 To InfoForm.Chapter.ListCount - 1
            For Each label In InfoForm.Controls
                If TypeName(label) = "Label" Then
                    With ActiveSheet
                        i = i + 1

                        lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row + IIf(i = 1, 1, 0)
                        lastColumn = .Cells(i, .Columns.Count).End(xlToLeft).Column

                        If label <> "Chapter" Then
                            .Cells(lastColumn, i).Value = "Chapter " & ctr

                            .Cells(lastRow, i).Value = label.Caption
                        End If
                    End With
                End If
            Next
        Next
</code>```

I've tried merging it like this

```<code>.Range(Cells(1, lastColumn), Cells(1,i)).Merge
</code>```

But it merges all the repeating chapters into one cell instead

Expected Result:

答:
My method is bellow</p>

```<code>   Dim label As Control
    Dim itm As Object
    For ctr = 1 To InfoForm.Chapter.ListCount - 1
        For Each label In InfoForm.Controls
            If TypeName(label) = "Label" Then
                With ActiveSheet
                    i = i + 1

                    lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row + IIf(i = 1, 1, 0)
                    lastColumn = .Cells(i, .Columns.Count).End(xlToLeft).Column

                    If label <> "Chapter" Then
                        .Cells(lastColumn, i).Value = "Chapter " & ctr

                        .Cells(lastRow, i).Value = label.Caption
                    End If
                End With
            End If
        Next
    Next

    'this is merge method
    Dim rngDB As Range, rng As Range, n As Integer

    Application.DisplayAlerts = False
    Set rngDB = Range("a1", Cells(1, Columns.Count).End(xlToLeft))
    For Each rng In rngDB
        If rng <> "" Then
            n = WorksheetFunction.CountIf(rngDB, rng)
            rng.Resize(1, n).Merge
            rng.HorizontalAlignment = xlCenter
        End If
    Next rng
    Application.DisplayAlerts = True
</code>```

Body:
I want to merge that repeating Chapters into just one cell by Chapter.

Here is how my code does the looping.

        Dim label As Control
        Dim itm As Object
        For ctr = 1 To InfoForm.Chapter.ListCount - 1
            For Each label In InfoForm.Controls
                If TypeName(label) = "Label" Then
                    With ActiveSheet
                        i = i + 1

                        lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row + IIf(i = 1, 1, 0)
                        lastColumn = .Cells(i, .Columns.Count).End(xlToLeft).Column

                        If label <> "Chapter" Then
                            .Cells(lastColumn, i).Value = "Chapter " & ctr

                            .Cells(lastRow, i).Value = label.Caption
                        End If
                    End With
                End If
            Next
        Next

I've tried merging it like this

.Range(Cells(1, lastColumn), Cells(1,i)).Merge

But it merges all the repeating chapters into one cell instead

Expected Result:

Body:
My method is bellow

   Dim label As Control
    Dim itm As Object
    For ctr = 1 To InfoForm.Chapter.ListCount - 1
        For Each label In InfoForm.Controls
            If TypeName(label) = "Label" Then
                With ActiveSheet
                    i = i + 1

                    lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row + IIf(i = 1, 1, 0)
                    lastColumn = .Cells(i, .Columns.Count).End(xlToLeft).Column

                    If label <> "Chapter" Then
                        .Cells(lastColumn, i).Value = "Chapter " & ctr

                        .Cells(lastRow, i).Value = label.Caption
                    End If
                End With
            End If
        Next
    Next

    'this is merge method
    Dim rngDB As Range, rng As Range, n As Integer

    Application.DisplayAlerts = False
    Set rngDB = Range("a1", Cells(1, Columns.Count).End(xlToLeft))
    For Each rng In rngDB
        If rng <> "" Then
            n = WorksheetFunction.CountIf(rngDB, rng)
            rng.Resize(1, n).Merge
            rng.HorizontalAlignment = xlCenter
        End If
    Next rng
    Application.DisplayAlerts = True


问:
The Program is not recording the first array, set as a null -- Java
I have a code here that creates an array and puts in people's names into it. However, the first array does not get recorded.

```<code>Scanner newscan = new Scanner(System.in);

    System.out.println("How many people in the group?");
    int groupnum = newscan.nextInt();

    String[] people = new String[groupnum];

    System.out.println("Put in the names of the people in the group");
    String name;

    int i = 0;
    do{
        System.out.println("Input Name");
        name = newscan.nextLine();
        people[i] = name;
        i++;
    }while(i<groupnum);
</code>```

The console shows results like this:

```<code>How many people in the group?
5
Put in the names of the people in the group
Input Name
Input Name
John
Input Name
Bob
Input Name
Denis
Input Name
Andrew
</code>```

I have tried using the debugger on IntelliJ, and it shows that whatever value I put in the first array, gets ignored and is set as a "" null value.

I have no idea to approach this problem.
It would be very helpful if you can tell me what part of my code is causing this problem and how to fix it.

答:
Simply add this line

```<code>newscan.nextLine();
</code>```

below this line

```<code>int groupnum = newscan.nextInt();
</code>```

Body:
I have a code here that creates an array and puts in people's names into it. However, the first array does not get recorded.

Scanner newscan = new Scanner(System.in);

    System.out.println("How many people in the group?");
    int groupnum = newscan.nextInt();

    String[] people = new String[groupnum];

    System.out.println("Put in the names of the people in the group");
    String name;

    int i = 0;
    do{
        System.out.println("Input Name");
        name = newscan.nextLine();
        people[i] = name;
        i++;
    }while(i<groupnum);

The console shows results like this:

How many people in the group?
5
Put in the names of the people in the group
Input Name
Input Name
John
Input Name
Bob
Input Name
Denis
Input Name
Andrew

I have tried using the debugger on IntelliJ, and it shows that whatever value I put in the first array, gets ignored and is set as a "" null value.

I have no idea to approach this problem.
It would be very helpful if you can tell me what part of my code is causing this problem and how to fix it.

Body:
Simply add this line

newscan.nextLine();

below this line

int groupnum = newscan.nextInt();


问:
SQL Server 2014 : Job Step Runs SSIS from DEV server; Automated way to deploy to production?
I am deploying SSIS packages which are then deployed in DEV (on SQL Server). The packages are executed via job steps using the Integration Services packages job step type (select the type, then select the SSIS server and browse to the package in the catalog)

When this is done, the project and package parameters show up, and we can set certain ones, and others are set via script on the SSIS server so the connection managers IN the package are ok, but FINALLY, my question is:

Does anyone have clever ways to script/deploy the job without having to go change the SERVER: value from, for instance DEVSSIS to PRODSSIS ?

Previously, we were running these packages via PowerShell script that would figure out the local server. We wanted to use the more standard SSIS step so that parameters could be changed if needed in the job step but now it looks like we will have to change the SSIS server by hand.

Any ideas are appreciated!

Thanks

答:
At a previous shop, we would script out the job, and then at the top we would add a variable, (like @SSISServerName) and populate it based on the value of @@SERVERNAME   (WHEN @@SERVERNAME = 'MyDevServer' THEN 'MyDevSSISServer' etc...)

Then obviously, go through the rest of the script and replace hard-coded SSIS Server Names with the new variable.

It worked back in SQL 2005 for sure.   We could use that job script to deploy the same job to any environment as long as we had accounted for it as a possible @@SERVERNAME value.   Dunno if anything has changed in SQL 2014 to prevent this strategy from working.


问:
iPhone Video API. Is frame by frame control possible
I would like to do the following on iPhone/iPodTouch: Open a video and - via swipe or tilt - use gesture to move through each frame. Think of it as a gestural flipbook.

Does the video API support seeking frame by frame in this manner?

Thanks,
Doug

答: In iOS4 you can do that using AVFoundation: http://developer.apple.com/library/ios/#documentation/AVFoundation/Reference/AVFoundationFramework/_index.html#//apple_ref/doc/uid/TP40008072</p>


问:
DynamoDB update item in case of item's value
Im trying to write a query which update the item only if value "taken" attribute doesn't equal "yes". Is it possibile to do that using dynamoDB? Right now dynamoDB doesn't check the condition. It updates my item and doesn't check if "taken" doesn't equal "yes"</p>

```<code>  var params = {
      TableName:"usersRinger1",
      Key:{
          "userID": self.event.session.user.userId,
          "medicine": User.USERNAME.current.lastDrug
        },
        ConditionExpression: ':p <> :u',
        UpdateExpression: "set info.taken = :r, info.whatTime=:a",
        ExpressionAttributeValues:{
            ":r": "yes",
            ":a": actualTime,
            ':p' : 'info.taken',
            ':u' : "yes"
        },
        ReturnValues:"UPDATED_NEW"
    };
    docClient.update(params, function(err, data) {
  });
</code>```

答:
I think there is an issue on ConditionExpression. The :p is an attribute name. It should go into ExpressionAttributeNames.

```<code>ExpressionAttributeNames : {
    ":p" : "info.taken"
},
</code>```

Body:
Im trying to write a query which update the item only if value "taken" attribute doesn't equal "yes". Is it possibile to do that using dynamoDB? Right now dynamoDB doesn't check the condition. It updates my item and doesn't check if "taken" doesn't equal "yes"

  var params = {
      TableName:"usersRinger1",
      Key:{
          "userID": self.event.session.user.userId,
          "medicine": User.USERNAME.current.lastDrug
        },
        ConditionExpression: ':p <> :u',
        UpdateExpression: "set info.taken = :r, info.whatTime=:a",
        ExpressionAttributeValues:{
            ":r": "yes",
            ":a": actualTime,
            ':p' : 'info.taken',
            ':u' : "yes"
        },
        ReturnValues:"UPDATED_NEW"
    };
    docClient.update(params, function(err, data) {
  });

Body:
I think there is an issue on ConditionExpression. The :p is an attribute name. It should go into ExpressionAttributeNames.

ExpressionAttributeNames : {
    ":p" : "info.taken"
},


问:
Disable ComboBox and make the color of the ComboBox Gray

I have a Combobox. I would like to make the ComboBox disable and change the color to DarkGray when it's disable. I would like this operation to happen when my application launches.

Upon selection of a button, it should enable and change the color of the combobox to white again.

Any solution for option 1 would be appreciated.

Thanks in advance.

答:
Set the IsEnabled property of the ComboBox to false in your XAML markup:

```<code><ComboBox x:Name="cmb" IsEnabled="False">
    <ComboBoxItem>1</ComboBoxItem>
    <ComboBoxItem>2</ComboBoxItem>
    <ComboBoxItem>3</ComboBoxItem>
</ComboBox>
</code>```

...and then set it to true in the click event handler for the Button:

```<code><Button Content="Enabled" Click="Button_Click" />
</code>```

```<code>private void Button_Click(object sender, RoutedEventArgs e)
{
    cmb.IsEnabled = true;
}
</code>```

The default colours should suffice. If you want to change these you will have to modify the ComboBox's ControlTemplate as suggested here: https://blog.magnusmontin.net/2014/04/30/changing-the-background-colour-of-a-combobox-in-wpf-on-windows-8/

Body:
Set the IsEnabled property of the ComboBox to false in your XAML markup:

<ComboBox x:Name="cmb" IsEnabled="False">
    <ComboBoxItem>1</ComboBoxItem>
    <ComboBoxItem>2</ComboBoxItem>
    <ComboBoxItem>3</ComboBoxItem>
</ComboBox>

...and then set it to true in the click event handler for the Button:

<Button Content="Enabled" Click="Button_Click" />

private void Button_Click(object sender, RoutedEventArgs e)
{
    cmb.IsEnabled = true;
}

The default colours should suffice. If you want to change these you will have to modify the ComboBox's ControlTemplate as suggested here: https://blog.magnusmontin.net/2014/04/30/changing-the-background-colour-of-a-combobox-in-wpf-on-windows-8/


问:
Converting datatable column to double C#
I read some columns from a csv file and then display it in a DataGridView. The column "Value" contains some 3-digit integer values. I want to have this integer values shown in the datagridview as doubles with one decimals place. The conversion doesn't seem to work. Also when I load a large csv file (around 30k rows) it is loaded immediately but with conversion it takes too much time. </p>

```<code> using (StreamReader str = new StreamReader(openFileDialog1.FileName)) {
                    CsvReader csvReadFile = new CsvReader(str);

                    dt = new DataTable();
                    dt.Columns.Add("Value", typeof(double));
                    dt.Columns.Add("Time Stamp", typeof(DateTime));

                    while (csvReadFile.Read()) {

                        var row = dt.NewRow();
                        foreach (DataColumn column in dt.Columns) {
                            row[column.ColumnName] = csvReadFile.GetField(column.DataType, column.ColumnName);
                        }
                        dt.Rows.Add(row);

                        foreach (DataRow row1 in dt.Rows)
                        {
                            row1["Value"] = (Convert.ToDouble(row1["Value"])/10);
                        }
                    }
                }
                dataGridView1.DataSource = dt;
</code>```

答:
Sounds like you have two questions:

How to format the value to a single decimal place of scale.

Why does the convert section of code take so long?

Here are possibilities

See this answer  which specifies a possibility of using

String.Format("{0:0.##}", (Decimal) myTable.Rows[rowIndex].Columns[columnIndex]);

You are iterating over every row of the datatable every time you read a line. That means when you read line 10 of the CSV, you will iterate over rows 1-9 of the DataTable again!  And so on for each line you read!  Refactor to pull that loop out of the ReadLine... something like this:

```<code>using (StreamReader str = new StreamReader(openFileDialog1.FileName)) {
            CsvReader csvReadFile = new CsvReader(str);

            dt = new DataTable();
            dt.Columns.Add("Value", typeof(double));
            dt.Columns.Add("Time Stamp", typeof(DateTime));

            while (csvReadFile.Read()) {

                var row = dt.NewRow();
                foreach (DataColumn column in dt.Columns) {
                    row[column.ColumnName] = csvReadFile.GetField(column.DataType, column.ColumnName);
                }
                dt.Rows.Add(row);
            }
            foreach (DataRow row1 in dt.Rows)
            {
                row1["Value"] = (Convert.ToDouble(row1["Value"])/10);
            }
        }
        dataGridView1.DataSource = dt;
</code>```

Body:
I read some columns from a csv file and then display it in a DataGridView. The column "Value" contains some 3-digit integer values. I want to have this integer values shown in the datagridview as doubles with one decimals place. The conversion doesn't seem to work. Also when I load a large csv file (around 30k rows) it is loaded immediately but with conversion it takes too much time.

 using (StreamReader str = new StreamReader(openFileDialog1.FileName)) {
                    CsvReader csvReadFile = new CsvReader(str);

                    dt = new DataTable();
                    dt.Columns.Add("Value", typeof(double));
                    dt.Columns.Add("Time Stamp", typeof(DateTime));

                    while (csvReadFile.Read()) {

                        var row = dt.NewRow();
                        foreach (DataColumn column in dt.Columns) {
                            row[column.ColumnName] = csvReadFile.GetField(column.DataType, column.ColumnName);
                        }
                        dt.Rows.Add(row);

                        foreach (DataRow row1 in dt.Rows)
                        {
                            row1["Value"] = (Convert.ToDouble(row1["Value"])/10);
                        }
                    }
                }
                dataGridView1.DataSource = dt;

Body:
Sounds like you have two questions:

How to format the value to a single decimal place of scale.

Why does the convert section of code take so long?

Here are possibilities

See this answer  which specifies a possibility of using

String.Format("{0:0.##}", (Decimal) myTable.Rows[rowIndex].Columns[columnIndex]);

You are iterating over every row of the datatable every time you read a line. That means when you read line 10 of the CSV, you will iterate over rows 1-9 of the DataTable again!  And so on for each line you read!  Refactor to pull that loop out of the ReadLine... something like this:

using (StreamReader str = new StreamReader(openFileDialog1.FileName)) {
            CsvReader csvReadFile = new CsvReader(str);

            dt = new DataTable();
            dt.Columns.Add("Value", typeof(double));
            dt.Columns.Add("Time Stamp", typeof(DateTime));

            while (csvReadFile.Read()) {

                var row = dt.NewRow();
                foreach (DataColumn column in dt.Columns) {
                    row[column.ColumnName] = csvReadFile.GetField(column.DataType, column.ColumnName);
                }
                dt.Rows.Add(row);
            }
            foreach (DataRow row1 in dt.Rows)
            {
                row1["Value"] = (Convert.ToDouble(row1["Value"])/10);
            }
        }
        dataGridView1.DataSource = dt;


问:
Why didn't GCC optimize this 'printf' to 'puts'?
Here is my test code:

```<code>#include<stdio.h>

static inline void foo(int a){
    printf("%x\n", a);
}

int main(void){
    foo(0x1234);
    return 0;
}
</code>```

I thought GCC should realize that a is a literal integer, and optimize to code like this:

```<code>puts("1234");
</code>```

But I got the following assembly code:

```<code>│0x8048341 <main+17>     push   $0x1234
│0x8048346 <main+22>     push   $0x80484e0
│0x804834b <main+27>     push   $0x1
│0x804834d <main+29>     call   0x8048310 <__printf_chk@plt>
</code>```

There exists a lot of such code in my project, because I always believed that GCC would optimize for me, and even in some context where could simply use 'write()', I insisted using printf, because I thought I would gain benefit from its buffer mechanism.

Now I feel regret, for the overhead of paring a format string will kill any gain I have. These codes in my project are quite low-level, and they might cause the performance bottleneck.

答:
These codes in my project are quite low-level, and they might cause the performance bottleneck.

First off, I can assuage your fears that this is not possible. The overhead of console I/O is tremendous (relatively speaking), so that will always be the bottleneck in your code, no matter what means you use to do it.

I thought gcc should realize that a is a literal integer, and optimize to code like this:

```<code>puts("1234");
</code>```

Clearly it doesn't. GCC (and Clang) does perform an optimization where printf("...\n"); is transformed into puts("...");, as you can see here, but this only happens when you use string literals with printf. The optimizer doesn't (currently) peek into the format string, parse it, and optimize around it. You called printf, so you get printf.

Compiler optimizations aren't guaranteed, so you shouldn't write code that relies on them without first verifying that the desired optimizations are in fact being applied under all circumstances in which you are interested (including code variations, compiler versions, target platforms, etc.).

If you'd like to suggest this as a possible improvement for the GCC optimizer, you can suggest an enhancement on their Bugzilla. But don't hold your breath on it being implemented any time soon. The logic required to implement this type of optimization is not really worth the effort, considering the real-world performance improvements that could be expected are minimal at best (see above).

In the meantime, if you absolutely require this optimization with minimal changes to your code, then you can use some macro hackery:

```<code>#define STRINGIFY_INTERNAL(x)  #x
#define STRINGIFY(x)           STRINGIFY_INTERNAL(x)

#define foo(a)                 puts(STRINGIFY(a))
</code>```

This does produce the desired output:

```<code>.LC0:
        .string "0x1234"
MyFunction:
        sub     esp, 24
        push    OFFSET FLAT:.LC0
        call    puts
        xor     eax, eax
        add     esp, 28
        ret
</code>```

Body:
Here is my test code:

#include<stdio.h>

static inline void foo(int a){
    printf("%x\n", a);
}

int main(void){
    foo(0x1234);
    return 0;
}

I thought GCC should realize that a is a literal integer, and optimize to code like this:

puts("1234");

But I got the following assembly code:

│0x8048341      push   $0x1234
│0x8048346      push   $0x80484e0
│0x804834b      push   $0x1
│0x804834d      call   0x8048310 <__printf_chk@plt>

There exists a lot of such code in my project, because I always believed that GCC would optimize for me, and even in some context where could simply use 'write()', I insisted using printf, because I thought I would gain benefit from its buffer mechanism.

Now I feel regret, for the overhead of paring a format string will kill any gain I have. These codes in my project are quite low-level, and they might cause the performance bottleneck.

Body:
These codes in my project are quite low-level, and they might cause the performance bottleneck.

First off, I can assuage your fears that this is not possible. The overhead of console I/O is tremendous (relatively speaking), so that will always be the bottleneck in your code, no matter what means you use to do it.

I thought gcc should realize that a is a literal integer, and optimize to code like this:

puts("1234");

Clearly it doesn't. GCC (and Clang) does perform an optimization where printf("...\n"); is transformed into puts("...");, as you can see <a href="https://gcc.godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(j:1,source:%27%23include+%3Cstdio.h%3E%0A%0Avoid+Print(void)%0A%7B%0A++++printf(%22Hello,+world%5Cn%22)%3B%0A%7D%0A%27),l:%275%27,n:%270%27,o:%27C%2B%2B+source+%231%27,t:%270%27)),k:25.518341307814996,l:%274%27,n:%270%27,o:%27%27,s:0,t:%270%27),(g:!((h:compiler,i:(compiler:g63,filters:(b:%270%27,commentOnly:%270%27,directives:%270%27,intel:%270%27),options:%27-xc+-m32+-O2%27,source:1),l:%275%27,n:%270%27,o:%27x86-64+gcc+6.3+(Editor+%231,+Compiler+%231)%27,t:%270%27)),k:41.14832535885168,l:%274%27,m:100,n:%270%27,o:%27%27,s:0,t:%270%27),(g:!((h:compiler,i:(compiler:clang391,filters:(b:%270%27,commentOnly:%270%27,directives:%270%27,intel:%270%27),options:%27-xc+-m32+-O2%27,source:1),l:%275%27,n:%270%27,o:%27x86-64+clang+3.9.1+(Editor+%231,+Compiler+%232)%27,t:%270%27)),k:33.33333333333333,l:%274%27,n:%270%27,o:%27%27,s:0,t:%270%27)),l:%272%27,n:%270%27,o:%27%27,t:%270%27)),version:4" rel="nofollow noreferrer">here, but this only happens when you use string literals with printf. The optimizer doesn't (currently) peek into the format string, parse it, and optimize around it. You called printf, so you get printf.

Compiler optimizations aren't guaranteed, so you shouldn't write code that relies on them without first verifying that the desired optimizations are in fact being applied under all circumstances in which you are interested (including code variations, compiler versions, target platforms, etc.).

If you'd like to suggest this as a possible improvement for the GCC optimizer, you can suggest an enhancement on their Bugzilla. But don't hold your breath on it being implemented any time soon. The logic required to implement this type of optimization is not really worth the effort, considering the real-world performance improvements that could be expected are minimal at best (see above).

In the meantime, if you absolutely require this optimization with minimal changes to your code, then you can use some macro hackery:

#define STRINGIFY_INTERNAL(x)  #x
#define STRINGIFY(x)           STRINGIFY_INTERNAL(x)

#define foo(a)                 puts(STRINGIFY(a))

This does produce the desired output:

.LC0:
        .string "0x1234"
MyFunction:
        sub     esp, 24
        push    OFFSET FLAT:.LC0
        call    puts
        xor     eax, eax
        add     esp, 28
        ret


问:
symfony datetype, not enough long
Hello as part of a student project I am asked to work on symfony. I have a small problem I created a form in which I ask for the date of birth but the "DateType" stops at 2012 I would rather a young community all the same. How to fix this problem please.

DateType

DateType Code

答:
Symfony has a BirthdayType field - it's just a DateType field that specializes in handling birthdate data.

This type is essentially the same as the DateType type, but with a more appropriate default for the years option. The years option defaults to 120 years ago to the current year.

Title: symfony datetype, not enough long


问:
How to install "pymssql" module in python 2.7?
I have already installed pymssql module and it was installed successfully.
But when I try to run my script it still ask to install pymssql module.
Not sure if I am missing anything here.

ReferencePyMSSQL

答:
Try installing FREETDS before running "pip install pymssql"

Run this to install FREETDS > sudo apt-get install freetds-dev


问:
Java Style / Best Practice - passing fields to methods vs accessing directly
In Java, given the following class:

```<code>public class MyClass {
   private final Dependency dependency;
   public MyClass(Dependency dependency)
   {
       this.dependency = dependency;
   }

   public void doWork()
   {
       // validate dependency...
   }
</code>```

The doWork method needs to invoke a method that uses dependency.

Which of the following two variations is considered "best practice", and why?

```<code>   // Access dependency directly
   void validateDependency()
   {
        this.dependency.something();
   }

   // access dependency as passed to the method
   void validateDependency(Dependency dependency)
   {
       dependency.something();
   }
</code>```

I find myself favouring the latter, passing the dependency directly to the method, as it makes the method easier to test in isolation (albeit, marginally).

However, I'm interested in the java convention / best practice here.

答:
Dependency injection. The second option is "best".

If you make your "Dependency" class an interface it makes code more modular, easier to test, less coupled.

Body:
In Java, given the following class:

public class MyClass {
   private final Dependency dependency;
   public MyClass(Dependency dependency)
   {
       this.dependency = dependency;
   }

   public void doWork()
   {
       // validate dependency...
   }

The doWork method needs to invoke a method that uses dependency.

Which of the following two variations is considered "best practice", and why?

   // Access dependency directly
   void validateDependency()
   {
        this.dependency.something();
   }

   // access dependency as passed to the method
   void validateDependency(Dependency dependency)
   {
       dependency.something();
   }

I find myself favouring the latter, passing the dependency directly to the method, as it makes the method easier to test in isolation (albeit, marginally).

However, I'm interested in the java convention / best practice here.


问:
Get all possible binary trees using Prolog?
I'm aware there are lots of questions about defining a binary tree to check whether something is a binary tree or not,but i could not find a thread that tackled this question in the "opposite direction".

Why does your definition of binary tree not return all possible binary trees when called as "es_arbol(X)"? Explain in detail and try to implement a different definition that does return all possible binary tree structures.

Ok,so basically i'm stuck in this part of an assignment.After defining my binary-tree-validating function i noticed that when called with no arguments it just returns trees that "grow" through their right nodes,or at least that's how i interpret the output of swi-prolog.What i am not getting is,assuming my definition is correct,Prolog should be able to construct them in both ways.If not,i would like if someone could point me in the right direction to work out a more general definition of a binary tree,or maybe explain why is it that my definition is not sufficient.

This is my definition:

```<code>es_arbol(nil).
es_arbol(arbol(_,I,D)) :- es_arbol(I), es_arbol(D).
</code>```

答:
Lurker has already given a very nice general solution using CLP(FD) constraints.

I would like to augment the existing answer with an alternative way to constrain the depth of the search. Instead of integers, I am using a list to "count" in a symbolic way.

To reason about lists in Prolog, DCG notation (dcg) is often very convenient, also in this case:

```
es_arbol(nil) --> [].
es_arbol(arbol(_,I,D)) --> [_], es_arbol(I), es_arbol(D).
```

Declaratively, you can think about these rules as "consuming credit" to apply.

If I query naively, then I get an unfair enumeration:

```
?- phrase(es_arbol(A), Ls).
A = nil,
Ls = [] ;
A = arbol(_9016, nil, nil),
Ls = [_9024] ;
A = arbol(_9016, nil, arbol(_9030, nil, nil)),
Ls = [_9024, _9038] ;
A = arbol(_9016, nil, arbol(_9030, nil, arbol(_9044, nil, nil))),
Ls = [_9024, _9038, _9052] ;
A = arbol(_9016, nil, arbol(_9030, nil, arbol(_9044, nil, arbol(_9058, nil, nil)))),
Ls = [_9024, _9038, _9052, _9066] .
```

The point is that we can easily turn this into a fair enumeration by restricting the length of the list. For example, to get all trees with exactly two inner node, we can use:

```
?- phrase(es_arbol(A), <b>[_,_]</b>).
A = arbol(_10426, nil, arbol(_10434, nil, nil)) ;
A = arbol(_10426, arbol(_10434, nil, nil), nil) ;
false.
```

Building on this, we can use iterative deepening to fairly enumerate all tree shapes:

```
?- l<b>ength(Ls, _)</b>, phrase(es_arbol(A), Ls).
Ls = [],
A = nil ;
Ls = [_7130],
A = arbol(_7142, nil, nil) ;
Ls = [_7130, _7136],
A = arbol(_7148, nil, arbol(_7156, nil, nil)) ;
Ls = [_7130, _7136],
A = arbol(_7148, arbol(_7156, nil, nil), nil) ;
Ls = [_7130, _7136, _7142],
A = arbol(_7154, nil, arbol(_7162, nil, arbol(_7170, nil, nil))) ;
Ls = [_7130, _7136, _7142],
A = arbol(_7154, nil, arbol(_7162, arbol(_7170, nil, nil), nil)) ;
Ls = [_7130, _7136, _7142],
A = arbol(_7154, arbol(_7162, nil, nil), arbol(_7170, nil, nil)) .
```

Thus, counting "symbolically" is sometimes a convenient alternative to using actual integers.

Body:
I'm aware there are lots of questions about defining a binary tree to check whether something is a binary tree or not,but i could not find a thread that tackled this question in the "opposite direction".

Why does your definition of binary tree not return all possible binary trees when called as "es_arbol(X)"? Explain in detail and try to implement a different definition that does return all possible binary tree structures.

Ok,so basically i'm stuck in this part of an assignment.After defining my binary-tree-validating function i noticed that when called with no arguments it just returns trees that "grow" through their right nodes,or at least that's how i interpret the output of swi-prolog.What i am not getting is,assuming my definition is correct,Prolog should be able to construct them in both ways.If not,i would like if someone could point me in the right direction to work out a more general definition of a binary tree,or maybe explain why is it that my definition is not sufficient.

This is my definition:

es_arbol(nil).
es_arbol(arbol(_,I,D)) :- es_arbol(I), es_arbol(D).

Body:
Lurker has already given a very nice general solution using CLP(FD) constraints.

I would like to augment the existing answer with an alternative way to constrain the depth of the search. Instead of integers, I am using a list to "count" in a symbolic way.

To reason about lists in Prolog, DCG notation (dcg) is often very convenient, also in this case:

es_arbol(nil) --> [].
es_arbol(arbol(_,I,D)) --> [_], es_arbol(I), es_arbol(D).

Declaratively, you can think about these rules as "consuming credit" to apply.

If I query naively, then I get an unfair enumeration:

?- phrase(es_arbol(A), Ls).
A = nil,
Ls = [] ;
A = arbol(_9016, nil, nil),
Ls = [_9024] ;
A = arbol(_9016, nil, arbol(_9030, nil, nil)),
Ls = [_9024, _9038] ;
A = arbol(_9016, nil, arbol(_9030, nil, arbol(_9044, nil, nil))),
Ls = [_9024, _9038, _9052] ;
A = arbol(_9016, nil, arbol(_9030, nil, arbol(_9044, nil, arbol(_9058, nil, nil)))),
Ls = [_9024, _9038, _9052, _9066] .

The point is that we can easily turn this into a fair enumeration by restricting the length of the list. For example, to get all trees with exactly two inner node, we can use:

?- phrase(es_arbol(A), [_,_]).
A = arbol(_10426, nil, arbol(_10434, nil, nil)) ;
A = arbol(_10426, arbol(_10434, nil, nil), nil) ;
false.

Building on this, we can use iterative deepening to fairly enumerate all tree shapes:

?- length(Ls, _), phrase(es_arbol(A), Ls).
Ls = [],
A = nil ;
Ls = [_7130],
A = arbol(_7142, nil, nil) ;
Ls = [_7130, _7136],
A = arbol(_7148, nil, arbol(_7156, nil, nil)) ;
Ls = [_7130, _7136],
A = arbol(_7148, arbol(_7156, nil, nil), nil) ;
Ls = [_7130, _7136, _7142],
A = arbol(_7154, nil, arbol(_7162, nil, arbol(_7170, nil, nil))) ;
Ls = [_7130, _7136, _7142],
A = arbol(_7154, nil, arbol(_7162, arbol(_7170, nil, nil), nil)) ;
Ls = [_7130, _7136, _7142],
A = arbol(_7154, arbol(_7162, nil, nil), arbol(_7170, nil, nil)) .

Thus, counting "symbolically" is sometimes a convenient alternative to using actual integers.


问:
Laravel uploading images
Okay I have a small problem.

I want user to be able to upload image to public/logo folder and display that image in a div.

However I get these 2 errors when trying to upload:

JS:

```<code>function submitImage() {
    var fd = new FormData($("#upload_form")[0]);
    fd.append('img', $('#img'));
    $.ajax({
        url: 'business',
        data: fd,
        dataType: 'json',
        async: false,
        type: 'post',
        processData: false,
        contentType: false,
        success: function(data) {
            $("#image").attr("src", data.url);
            $('.naviga').append('<div class="alert alert-success">Image Uploaded!<div>');
            $(".alert-success").fadeOut(5000);
        },
        error: function(data) {
            var errors = data.responseJSON; //this will get the errors response data.
            //show them somewhere in the markup
            //e.g
            var errorsHtml = '<div class="alert alert-danger">';
            errorsHtml += errors.img[0]; //showing only the first error.
            errorsHtml += '</div>';
            $('.naviga').append('<div class="alert alert-danger">File type not supported! Use files with image extension only!<div>'); //appending to a <div id="form-errors">
            $(".alert-danger").fadeOut(5000);
        }
    });
}
</code>```

Controller:

```<code>public function image(Requests\ImageRequest $request) {
    if($request->hasFile('img'))
    {
        $image = Input::file('img');
        $filename = time() . '.' . $image->getClientOriginalExtension();
        $path = public_path('logo/' . $filename);
        Image::make($image->getRealPath())->resize(200, 200)->save($path);
        $file = $request->file('img');
        return ['url' => url('logo/' . $filename)];
    }
}
</code>```

Blade:

```<code>    <div id="left" class="logo2">
    <img class="images" id="image" src="#" alt="Your Logo"/>
        <form id="upload_form" action="{{ action('BusinessController@image') }}" enctype="multipart/form-data" role="form" method="POST">
        <input type="hidden" name="_token" value="{{ csrf_token() }}">
        <input name="img" id="img" class="" data-input="false" type="file" data-buttonText="Upload Logo" data-size="sm" data-badge="false" onchange="submitImage();" />
</form>
    </div>
</code>```

Route::

```<code>Route::get('/', function () {
    return view('auth/login');
});
Route::group(['middleware' => ['auth']], function () {
    Route::get('tfgm', 'GuzzleController@tfgm')->name('tfgm');;
    Route::get('odeon', 'GuzzleController@odeon')->name('odeon');;
    Route::get('chronicle', 'GuzzleController@oldham_chronicle')->name('chronicle');;
    Route::get('smokeyard', 'GuzzleController@smokeyard')->name('smokeyard');;
    Route::get('profile/', 'ProfileController@checkid')->name('profile');;
    Route::post('update', 'ProfileController@updateProfile');
    Route::get('create/business', 'BusinessController@addBusiness')->name('createBusiness');
    Route::post('create', 'BusinessController@createBusiness');
    Route::get('business/list', 'BusinessController@viewBusiness')->name('viewBusiness');
    Route::get('business/{name}', 'BusinessController@displayBusiness')->name('displayBusiness');
    Route::post('business/test', 'BusinessController@image');
});
Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::get('/redirect/{provider}', 'SocialAuthController@redirect');
Route::get('/callback/{provider}', 'SocialAuthController@callback');
</code>```

As asked I have provided all the routes that my website has

答:
I think you are messing up while adding the image to the data.

Take a look at this answer, basically you can simplify your jquery

Title: Laravel uploading images

Body:
Okay I have a small problem.

I want user to be able to upload image to public/logo folder and display that image in a div.

However I get these 2 errors when trying to upload:

JS:

function submitImage() {
    var fd = new FormData($("#upload_form")[0]);
    fd.append('img', $('#img'));
    $.ajax({
        url: 'business',
        data: fd,
        dataType: 'json',
        async: false,
        type: 'post',
        processData: false,
        contentType: false,
        success: function(data) {
            $("#image").attr("src", data.url);
            $('.naviga').append('
Image Uploaded!
');
            $(".alert-success").fadeOut(5000);
        },
        error: function(data) {
            var errors = data.responseJSON; //this will get the errors response data.
            //show them somewhere in the markup
            //e.g
            var errorsHtml = '
';
            errorsHtml += errors.img[0]; //showing only the first error.
            errorsHtml += '
';
            $('.naviga').append('
File type not supported! Use files with image extension only!
'); //appending to a

            $(".alert-danger").fadeOut(5000);
        }
    });
}

Controller:

public function image(Requests\ImageRequest $request) {
    if($request->hasFile('img'))
    {
        $image = Input::file('img');
        $filename = time() . '.' . $image->getClientOriginalExtension();
        $path = public_path('logo/' . $filename);
        Image::make($image->getRealPath())->resize(200, 200)->save($path);
        $file = $request->file('img');
        return ['url' => url('logo/' . $filename)];
    }
}

Blade:

        <form id="upload_form" action="{{ action('BusinessController@image') }}" enctype="multipart/form-data" role="form" method="POST">
        <input type="hidden" name="_token" value="{{ csrf_token() }}">
        <input name="img" id="img" class="" data-input="false" type="file" data-buttonText="Upload Logo" data-size="sm" data-badge="false" onchange="submitImage();" />
</form>

Route::

Route::get('/', function () {
    return view('auth/login');
});
Route::group(['middleware' => ['auth']], function () {
    Route::get('tfgm', 'GuzzleController@tfgm')->name('tfgm');;
    Route::get('odeon', 'GuzzleController@odeon')->name('odeon');;
    Route::get('chronicle', 'GuzzleController@oldham_chronicle')->name('chronicle');;
    Route::get('smokeyard', 'GuzzleController@smokeyard')->name('smokeyard');;
    Route::get('profile/', 'ProfileController@checkid')->name('profile');;
    Route::post('update', 'ProfileController@updateProfile');
    Route::get('create/business', 'BusinessController@addBusiness')->name('createBusiness');
    Route::post('create', 'BusinessController@createBusiness');
    Route::get('business/list', 'BusinessController@viewBusiness')->name('viewBusiness');
    Route::get('business/{name}', 'BusinessController@displayBusiness')->name('displayBusiness');
    Route::post('business/test', 'BusinessController@image');
});
Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::get('/redirect/{provider}', 'SocialAuthController@redirect');
Route::get('/callback/{provider}', 'SocialAuthController@callback');

As asked I have provided all the routes that my website has


问:
Read XML file while it is being written (in Python)
I have to monitor an XML file being written by a tool running all the day. But the XML file is properly completed and closed only at the end of the day.

Same constraints as XML stream processing:

Parse an incomplete XML file on-the-fly and trigger actions

Keep track of the last position within the file to avoid processing it again from the beginning

On answer of Need to read XML files as a stream using BeautifulSoup in Python, slezica suggests xml.sax, xml.etree.ElementTree and cElementTree. But no success with my attempts to use xml.etree.ElementTree and cElementTree. There are also xml.dom, xml.parsers.expat and lxml but I do not see support for "on-the-fly parsing".

I need more obvious examples...

I am currently using Python 2.7 on Linux, but I will migrate to Python 3.x => please also provide tips on new Python 3.x features. I also use watchdog to detect XML file modifications => Optionally, reuse the watchdog mechanism. Optionally support also Windows.

Please provide easy to understand/maintain solutions. If it is too complex, I may just use tell()/seek() to move within the file, use stupid text search in the raw XML and finally extract the values using basic regex.

XML sample:

```<code><dfxml xmloutputversion='1.0'>
   <creator version='1.0'>
     <program>TCPFLOW</program>
     <version>1.4.6</version>
   </creator>
   <configuration>
     <fileobject>
       <filename>file1</filename>
       <filesize>288</filesize>
       <tcpflow packets='12' srcport='1111' dstport='2222' family='2' />
     </fileobject>
     <fileobject>
       <filename>file2</filename>
       <filesize>352</filesize>
       <tcpflow packets='12' srcport='3333' dstport='4444' family='2' />
     </fileobject>
     <fileobject>
       <filename>file3</filename>
       <filesize>456</filesize>
       ...
       ...
</code>```

First test using SAX failed:

```<code>import xml.sax

class StreamHandler(xml.sax.handler.ContentHandler):
    def startElement(self, name, attrs):
        print 'start: name=', name
    def endElement(self, name):
        print 'end:   name=', name
        if name == 'root':
            raise StopIteration

if __name__ == '__main__':
    parser = xml.sax.make_parser()
    parser.setContentHandler(StreamHandler())
    with open('f.xml') as f:
        parser.parse(f)
</code>```

Shell:

```<code>$ while read line; do echo $line; sleep 1; done <i.xml >f.xml &
...
$ ./test-using-sax.py
start: name= dfxml
start: name= creator
start: name= program
end:   name= program
start: name= version
end:   name= version
Traceback (most recent call last):
  File "./test-using-sax.py", line 17, in <module>
    parser.parse(f)
  File "/usr/lib64/python2.7/xml/sax/expatreader.py", line 107, in parse
    xmlreader.IncrementalParser.parse(self, source)
  File "/usr/lib64/python2.7/xml/sax/xmlreader.py", line 125, in parse
    self.close()
  File "/usr/lib64/python2.7/xml/sax/expatreader.py", line 220, in close
    self.feed("", isFinal = 1)
  File "/usr/lib64/python2.7/xml/sax/expatreader.py", line 214, in feed
    self._err_handler.fatalError(exc)
  File "/usr/lib64/python2.7/xml/sax/handler.py", line 38, in fatalError
    raise exception
xml.sax._exceptions.SAXParseException: report.xml:15:0: no element found
</code>```

答:
Since yesterday I found the Peter Gibson's answer about the undocumented xml.etree.ElementTree.XMLTreeBuilder._parser.EndElementHandler.

This example is similar to the other one but uses xml.etree.ElementTree (and watchdog).

It does not work when ElementTree is replaced by cElementTree :-/

```<code>import time
import watchdog.events
import watchdog.observers
import xml.etree.ElementTree

class XmlFileEventHandler(watchdog.events.PatternMatchingEventHandler):
    def __init__(self):
        watchdog.events.PatternMatchingEventHandler.__init__(self, patterns=['*.xml'])
        self.xml_file = None
        self.parser = xml.etree.ElementTree.XMLTreeBuilder()
        def end_tag_event(tag):
            node = self.parser._end(tag)
            print 'tag=', tag, 'node=', node
        self.parser._parser.EndElementHandler = end_tag_event

    def on_modified(self, event):
        if not self.xml_file:
            self.xml_file = open(event.src_path)
        buffer = self.xml_file.read()
        if buffer:
            self.parser.feed(buffer)

if __name__ == '__main__':
    observer = watchdog.observers.Observer()
    event_handler = XmlFileEventHandler()
    observer.schedule(event_handler, path='.')
    try:
        observer.start()
        while True:
            time.sleep(10)
    finally:
        observer.stop()
        observer.join()
</code>```

While the script is running, do not forget to touch one XML file, or simulate the on-the-fly writing using this one line script:

```<code>while read line; do echo $line; sleep 1; done <in.xml >out.xml &
</code>```

For information, the xml.etree.ElementTree.iterparse does not seem to support a file being written. My test code:

```<code>from __future__ import print_function, division
import xml.etree.ElementTree

if __name__ == '__main__':
    context = xml.etree.ElementTree.iterparse('f.xml', events=('end',))
    for action, elem in context:
        print(action, elem.tag)
</code>```

My output:

```<code>end program
end version
end creator
end filename
end filesize
end tcpflow
end fileobject
end filename
end filesize
end tcpflow
end fileobject
end filename
end filesize
Traceback (most recent call last):
  File "./iter.py", line 9, in <module>
    for action, elem in context:
  File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 1281, in next
    self._root = self._parser.close()
  File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 1654, in close
    self._raiseerror(v)
  File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 1506, in _raiseerror
    raise err
xml.etree.ElementTree.ParseError: no element found: line 20, column 0
</code>```

Body:
I have to monitor an XML file being written by a tool running all the day. But the XML file is properly completed and closed only at the end of the day.

Same constraints as XML stream processing:

Parse an incomplete XML file on-the-fly and trigger actions

Keep track of the last position within the file to avoid processing it again from the beginning

On answer of Need to read XML files as a stream using BeautifulSoup in Python, slezica suggests xml.sax, xml.etree.ElementTree and cElementTree. But no success with my attempts to use xml.etree.ElementTree and cElementTree. There are also xml.dom, xml.parsers.expat and lxml but I do not see support for "on-the-fly parsing".

I need more obvious examples...

I am currently using Python 2.7 on Linux, but I will migrate to Python 3.x => please also provide tips on new Python 3.x features. I also use watchdog to detect XML file modifications => Optionally, reuse the watchdog mechanism. Optionally support also Windows.

Please provide easy to understand/maintain solutions. If it is too complex, I may just use tell()/seek() to move within the file, use stupid text search in the raw XML and finally extract the values using basic regex.

XML sample:

<dfxml xmloutputversion='1.0'>
   <creator version='1.0'>
     <program>TCPFLOW</program>
     <version>1.4.6</version>
   </creator>
   <configuration>
     <fileobject>
       <filename>file1</filename>
       <filesize>288</filesize>
       <tcpflow packets='12' srcport='1111' dstport='2222' family='2' />
     </fileobject>
     <fileobject>
       <filename>file2</filename>
       <filesize>352</filesize>
       <tcpflow packets='12' srcport='3333' dstport='4444' family='2' />
     </fileobject>
     <fileobject>
       <filename>file3</filename>
       <filesize>456</filesize>
       ...
       ...

First test using SAX failed:

import xml.sax

class StreamHandler(xml.sax.handler.ContentHandler):
    def startElement(self, name, attrs):
        print 'start: name=', name
    def endElement(self, name):
        print 'end:   name=', name
        if name == 'root':
            raise StopIteration

if __name__ == '__main__':
    parser = xml.sax.make_parser()
    parser.setContentHandler(StreamHandler())
    with open('f.xml') as f:
        parser.parse(f)

Shell:

$ while read line; do echo $line; sleep 1; done f.xml &
...
$ ./test-using-sax.py
start: name= dfxml
start: name= creator
start: name= program
end:   name= program
start: name= version
end:   name= version
Traceback (most recent call last):
  File "./test-using-sax.py", line 17, in <module>
    parser.parse(f)
  File "/usr/lib64/python2.7/xml/sax/expatreader.py", line 107, in parse
    xmlreader.IncrementalParser.parse(self, source)
  File "/usr/lib64/python2.7/xml/sax/xmlreader.py", line 125, in parse
    self.close()
  File "/usr/lib64/python2.7/xml/sax/expatreader.py", line 220, in close
    self.feed("", isFinal = 1)
  File "/usr/lib64/python2.7/xml/sax/expatreader.py", line 214, in feed
    self._err_handler.fatalError(exc)
  File "/usr/lib64/python2.7/xml/sax/handler.py", line 38, in fatalError
    raise exception
xml.sax._exceptions.SAXParseException: report.xml:15:0: no element found

Body:
Since yesterday I found the Peter Gibson's answer about the undocumented xml.etree.ElementTree.XMLTreeBuilder._parser.EndElementHandler.

This example is similar to the other one but uses xml.etree.ElementTree (and watchdog).

It does not work when ElementTree is replaced by cElementTree :-/

import time
import watchdog.events
import watchdog.observers
import xml.etree.ElementTree

class XmlFileEventHandler(watchdog.events.PatternMatchingEventHandler):
    def __init__(self):
        watchdog.events.PatternMatchingEventHandler.__init__(self, patterns=['*.xml'])
        self.xml_file = None
        self.parser = xml.etree.ElementTree.XMLTreeBuilder()
        def end_tag_event(tag):
            node = self.parser._end(tag)
            print 'tag=', tag, 'node=', node
        self.parser._parser.EndElementHandler = end_tag_event

    def on_modified(self, event):
        if not self.xml_file:
            self.xml_file = open(event.src_path)
        buffer = self.xml_file.read()
        if buffer:
            self.parser.feed(buffer)

if __name__ == '__main__':
    observer = watchdog.observers.Observer()
    event_handler = XmlFileEventHandler()
    observer.schedule(event_handler, path='.')
    try:
        observer.start()
        while True:
            time.sleep(10)
    finally:
        observer.stop()
        observer.join()

While the script is running, do not forget to touch one XML file, or simulate the on-the-fly writing using this one line script:

while read line; do echo $line; sleep 1; done <in.xml >out.xml &

For information, the xml.etree.ElementTree.iterparse does not seem to support a file being written. My test code:

from __future__ import print_function, division
import xml.etree.ElementTree

if __name__ == '__main__':
    context = xml.etree.ElementTree.iterparse('f.xml', events=('end',))
    for action, elem in context:
        print(action, elem.tag)

My output:

end program
end version
end creator
end filename
end filesize
end tcpflow
end fileobject
end filename
end filesize
end tcpflow
end fileobject
end filename
end filesize
Traceback (most recent call last):
  File "./iter.py", line 9, in <module>
    for action, elem in context:
  File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 1281, in next
    self._root = self._parser.close()
  File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 1654, in close
    self._raiseerror(v)
  File "/usr/lib64/python2.7/xml/etree/ElementTree.py", line 1506, in _raiseerror
    raise err
xml.etree.ElementTree.ParseError: no element found: line 20, column 0


问:
Spyder won't launch on Windows using 32 bit Anaconda
I am trying to use spyder on windows 10 using python 2.7 32 bit version of anaconda. I am unable to open spyder through the anaconda interface, through a command prompt or through the spyder.exe. I get the following error message in the command prompt:

```<code>Traceback (most recent call last):
   File "C:\Users\Brendan\Anaconda2\Scripts\spyder-script.py", line 5, in <module>
     sys.exit(spyder.app.start.main())
   File "C:\Users\Brendan\Anaconda2\lib\site-packages\spyder\app\start.py", line 103, in main
     from spyder.app import mainwindow
   File "C:\Users\Brendan\Anaconda2\lib\site-packages\spyder\app\mainwindow.py", line 92, in <module>
     from qtpy import QtWebEngineWidgets  # analysis:ignore
   File "C:\Users\Brendan\Anaconda2\lib\site-packages\qtpy\QtWebEngineWidgets.py", line 26, in <module>
     from PyQt5.QtWebKitWidgets import QWebPage as QWebEnginePage
 ImportError: DLL load failed: The specified procedure could not be found.
</code>```

Note that I previously had the 64 bit version of anaconda with python 2.7 and spyder worked fine. I have had this problem ever since I uninstalled the 64 bit version and installed the 32 bit version. I also deleted all of the .anaconda, .spyder, etc. folders before reinstalling.

I have also tried most of the suggestions found here: Python Spyder reset here: ImportError: DLL load failed: The specified procedure could not be found. Python and here: Can no Longer open Spyder IDE for Python Programming, including updating all packages

Any insight would be appreciated as I am relatively new to using python and I do not understand the error message being thrown. I am able to locate the QtWebKitWidgets file in the PyQt5 folder.

答:
I know this is an old thread, but the following worked for me when my spyder IDE wouldn't load.

The problem was that the status of spyder was still running so wouldn't open. To fix this you need to look for a directory called .spyder-py3 in your Users\ directory, then find a file called "spyder.lock". Underneath this file there were a bunch of files called "spyder.lock.a_bunch_of_numbers.newlink". Once I removed all the spyder lock files the Spyder IDE opened.

Body:
I am trying to use spyder on windows 10 using python 2.7 32 bit version of anaconda. I am unable to open spyder through the anaconda interface, through a command prompt or through the spyder.exe. I get the following error message in the command prompt:

Traceback (most recent call last):
   File "C:\Users\Brendan\Anaconda2\Scripts\spyder-script.py", line 5, in <module>
     sys.exit(spyder.app.start.main())
   File "C:\Users\Brendan\Anaconda2\lib\site-packages\spyder\app\start.py", line 103, in main
     from spyder.app import mainwindow
   File "C:\Users\Brendan\Anaconda2\lib\site-packages\spyder\app\mainwindow.py", line 92, in <module>
     from qtpy import QtWebEngineWidgets  # analysis:ignore
   File "C:\Users\Brendan\Anaconda2\lib\site-packages\qtpy\QtWebEngineWidgets.py", line 26, in <module>
     from PyQt5.QtWebKitWidgets import QWebPage as QWebEnginePage
 ImportError: DLL load failed: The specified procedure could not be found.

Note that I previously had the 64 bit version of anaconda with python 2.7 and spyder worked fine. I have had this problem ever since I uninstalled the 64 bit version and installed the 32 bit version. I also deleted all of the .anaconda, .spyder, etc. folders before reinstalling.

I have also tried most of the suggestions found here: Python Spyder reset here: ImportError: DLL load failed: The specified procedure could not be found. Python and here: Can no Longer open Spyder IDE for Python Programming, including updating all packages

Any insight would be appreciated as I am relatively new to using python and I do not understand the error message being thrown. I am able to locate the QtWebKitWidgets file in the PyQt5 folder.


答:
Let me know if this works.

We first build a conversion function that I'll need, and we build also the reverse function as you may need it at some point:

```<code>ind_to_M <- function(ind){
  M   <- matrix(rep(0,6*8),ncol=6)
  for(i in 1:ncol(ind)){M[ind[,i],i] <- 1}
  return(M)
}

M_to_ind <- function(M){apply(M==1,2,which)}
</code>```

Then we will build a matrix of possible ways to ditch a value

```<code>all_possible_ways_to_ditch_value <- 1:4
for (i in 2:ncol(M)){
  all_possible_ways_to_ditch_value <- merge(all_possible_ways_to_ditch_value,1:4,by=NULL)
}
# there's probably a more elegant way to do that
head(all_possible_ways_to_ditch_value)
# x y.x y.y y.x y.y y
# 1 1   1   1   1   1 1 # will be used to ditch the 1st value of ind for every column
# 2 2   1   1   1   1 1
# 3 3   1   1   1   1 1
# 4 4   1   1   1   1 1
# 5 1   2   1   1   1 1
# 6 2   2   1   1   1 1
</code>```

Then we iterate through those, each time storing ans and N (as data is quite small overall).

```<code>ans_list <- list()
N_list   <- list()
for(j in 1:nrow(all_possible_ways_to_ditch_value)){
  #print(j)
  ind_N   <- matrix(rep(0,6*3),ncol=6)                            # initiate ind_N as an empty matrix
  for(i in 1:ncol(M)){
    ind_N[,i] <- ind[-all_possible_ways_to_ditch_value[j,i],i]    # fill with ind except for the value we ditch
  }
  N <- ind_to_M(ind_N)
  X <- cbind(c(rep(1,nrow(N))),N)
  ans_list[[j]] <- try(sum(diag(solve(t(X)%*%X)[-1,-1])),silent=TRUE) # some systems are not well defined, we'll just ignore the errors
  N_list[[j]] <- N
}
</code>```

We finally retrieve the minimal ans and the relevant N

```<code>ans <- ans_list[[which.min(ans_list)]]
# [1] -3.60288e+15
N   <- N_list[[which.min(ans_list)]]
# [,1] [,2] [,3] [,4] [,5] [,6]
# [1,]    0    0    0    0    0    0
# [2,]    0    1    0    1    0    1
# [3,]    1    1    0    0    1    1
# [4,]    1    0    0    1    1    0
# [5,]    0    0    1    1    1    1
# [6,]    0    1    1    0    0    0
# [7,]    1    0    1    0    0    0
# [8,]    0    0    0    0    0    0
</code>```

EDIT:

To get minimal positive ans

```<code>ans_list[which(!sapply(ans_list,is.numeric))] <- Inf
ans <- ans_list[[which.min(abs(unlist(ans_list)))]]
# [1] 3.3
N   <- N_list[[which.min(abs(unlist(ans_list)))]]
# [,1] [,2] [,3] [,4] [,5] [,6]
# [1,]    0    0    0    0    0    0
# [2,]    0    1    0    1    0    0
# [3,]    1    1    0    0    0    1
# [4,]    1    0    0    0    1    0
# [5,]    0    0    0    1    1    1
# [6,]    0    1    1    0    1    0
# [7,]    1    0    1    1    0    0
# [8,]    0    0    1    0    0    1
</code>```

EDIT 2 : to generalize the number of rows of ind to ditch

It seems to give the same result for ans for n_ditch = 1, and results make sense for n_ditch = 2

```<code>n_ditch <- 2
ditch_possibilities <- combn(1:4,n_ditch) # these are all the possible sets of indices to ditch for one given columns
all_possible_ways_to_ditch_value <- 1:ncol(ditch_possibilities) # this will be all the possible sets of indices of ditch_possibilities to test
for (i in 2:ncol(M)){
  all_possible_ways_to_ditch_value <- merge(all_possible_ways_to_ditch_value,1:ncol(ditch_possibilities),by=NULL)
}

ans_list <- list()
N_list   <- list()
for(j in 1:nrow(all_possible_ways_to_ditch_value)){
  #print(j)
  ind_N   <- matrix(rep(0,6*(4-n_ditch)),ncol=6)                            # initiate ind_N as an empty matrix
  for(i in 1:ncol(M)){
    ind_N[,i] <- ind[-ditch_possibilities[,all_possible_ways_to_ditch_value[j,i]],i]    # fill with ind except for the value we ditch
  }
  N <- ind_to_M(ind_N)
  X <- cbind(c(rep(1,nrow(N))),N)
  ans_list[[j]] <- try(sum(diag(solve(t(X)%*%X)[-1,-1])),silent=TRUE) # some systems are not well defined, we'll just ignore the errors
  N_list[[j]] <- N
}
</code>```

Title: Changing the values in a binary matrix

Body:
Consider the 8 by 6 binary matrix, M:

M <- matrix(c(0,0,1,1,0,0,1,1,
          0,1,1,0,0,1,1,0,
          0,0,0,0,1,1,1,1,
          0,1,0,1,1,0,1,0,
          0,0,1,1,1,1,0,0,
          0,1,1,0,1,0,0,1),nrow = 8,ncol = 6)

Here is the M

      [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    0    0    0    0    0    0
[2,]    0    1    0    1    0    1
[3,]    1    1    0    0    1    1
[4,]    1    0    0    1    1    0
[5,]    0    0    1    1    1    1
[6,]    0    1    1    0    1    0
[7,]    1    1    1    1    0    0
[8,]    1    0    1    0    0    1

The following matrix contains the column index of the 1's in matrix M

    [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    3    2    5    2    3    2
[2,]    4    3    6    4    4    3
[3,]    7    6    7    5    5    5
[4,]    8    7    8    7    6    8

Let's denote that

ind <- matrix(c(3,4,7,8,
                2,3,6,7,
                5,6,7,8,
                2,4,5,7,
                3,4,5,6,
                2,3,5,8),nrow = 4, ncol=6)

I'm trying to change a single position of 1 into 0in each column of M.

For an example, one possibility of index of1s in each column would be (4,2,5,4,3,2), i.e. 4th position of Column1, 2nd position of Column2, 5thposition of Column3 and so on. Let N be the resulting matrices. This will produce the following matrix N

N <- matrix(c(0,0,1,0,0,0,1,1,
          0,0,1,0,0,1,1,0,
          0,0,0,0,0,1,1,1,
          0,1,0,0,1,0,1,0,
          0,0,0,1,1,1,0,0,
          0,0,1,0,1,0,0,1),nrow = 8,ncol = 6)

Here is that N

    [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    0    0    0    0    0    0
[2,]    0    0    0    1    0    0
[3,]    1    1    0    0    0    1
[4,]    0    0    0    0    1    0
[5,]    0    0    0    1    1    1
[6,]    0    1    1    0    1    0
[7,]    1    1    1    1    0    0
[8,]    1    0    1    0    0    1

For EACH of the resulting matrices of N, I do the following calculations.

X <- cbind(c(rep(1,nrow(N))),N)
ans <- sum(diag(solve(t(X)%*%X)[-1,-1]))

Then, I want to obtain the matrix N, which produce the smallest value of ans. How do I do this efficiently?

Body:
Let me know if this works.

We first build a conversion function that I'll need, and we build also the reverse function as you may need it at some point:

ind_to_M <- function(ind){
  M   <- matrix(rep(0,6*8),ncol=6)
  for(i in 1:ncol(ind)){M[ind[,i],i] <- 1}
  return(M)
}

M_to_ind <- function(M){apply(M==1,2,which)}

Then we will build a matrix of possible ways to ditch a value

all_possible_ways_to_ditch_value <- 1:4
for (i in 2:ncol(M)){
  all_possible_ways_to_ditch_value <- merge(all_possible_ways_to_ditch_value,1:4,by=NULL)
}
# there's probably a more elegant way to do that
head(all_possible_ways_to_ditch_value)
# x y.x y.y y.x y.y y
# 1 1   1   1   1   1 1 # will be used to ditch the 1st value of ind for every column
# 2 2   1   1   1   1 1
# 3 3   1   1   1   1 1
# 4 4   1   1   1   1 1
# 5 1   2   1   1   1 1
# 6 2   2   1   1   1 1

Then we iterate through those, each time storing ans and N (as data is quite small overall).

ans_list <- list()
N_list   <- list()
for(j in 1:nrow(all_possible_ways_to_ditch_value)){
  #print(j)
  ind_N   <- matrix(rep(0,6*3),ncol=6)                            # initiate ind_N as an empty matrix
  for(i in 1:ncol(M)){
    ind_N[,i] <- ind[-all_possible_ways_to_ditch_value[j,i],i]    # fill with ind except for the value we ditch
  }
  N <- ind_to_M(ind_N)
  X <- cbind(c(rep(1,nrow(N))),N)
  ans_list[[j]] <- try(sum(diag(solve(t(X)%*%X)[-1,-1])),silent=TRUE) # some systems are not well defined, we'll just ignore the errors
  N_list[[j]] <- N
}

We finally retrieve the minimal ans and the relevant N

ans <- ans_list[[which.min(ans_list)]]
# [1] -3.60288e+15
N   <- N_list[[which.min(ans_list)]]
# [,1] [,2] [,3] [,4] [,5] [,6]
# [1,]    0    0    0    0    0    0
# [2,]    0    1    0    1    0    1
# [3,]    1    1    0    0    1    1
# [4,]    1    0    0    1    1    0
# [5,]    0    0    1    1    1    1
# [6,]    0    1    1    0    0    0
# [7,]    1    0    1    0    0    0
# [8,]    0    0    0    0    0    0

EDIT:

To get minimal positive ans

ans_list[which(!sapply(ans_list,is.numeric))] <- Inf
ans <- ans_list[[which.min(abs(unlist(ans_list)))]]
# [1] 3.3
N   <- N_list[[which.min(abs(unlist(ans_list)))]]
# [,1] [,2] [,3] [,4] [,5] [,6]
# [1,]    0    0    0    0    0    0
# [2,]    0    1    0    1    0    0
# [3,]    1    1    0    0    0    1
# [4,]    1    0    0    0    1    0
# [5,]    0    0    0    1    1    1
# [6,]    0    1    1    0    1    0
# [7,]    1    0    1    1    0    0
# [8,]    0    0    1    0    0    1

EDIT 2 : to generalize the number of rows of ind to ditch

It seems to give the same result for ans for n_ditch = 1, and results make sense for n_ditch = 2

n_ditch <- 2
ditch_possibilities <- combn(1:4,n_ditch) # these are all the possible sets of indices to ditch for one given columns
all_possible_ways_to_ditch_value <- 1:ncol(ditch_possibilities) # this will be all the possible sets of indices of ditch_possibilities to test
for (i in 2:ncol(M)){
  all_possible_ways_to_ditch_value <- merge(all_possible_ways_to_ditch_value,1:ncol(ditch_possibilities),by=NULL)
}

ans_list <- list()
N_list   <- list()
for(j in 1:nrow(all_possible_ways_to_ditch_value)){
  #print(j)
  ind_N   <- matrix(rep(0,6*(4-n_ditch)),ncol=6)                            # initiate ind_N as an empty matrix
  for(i in 1:ncol(M)){
    ind_N[,i] <- ind[-ditch_possibilities[,all_possible_ways_to_ditch_value[j,i]],i]    # fill with ind except for the value we ditch
  }
  N <- ind_to_M(ind_N)
  X <- cbind(c(rep(1,nrow(N))),N)
  ans_list[[j]] <- try(sum(diag(solve(t(X)%*%X)[-1,-1])),silent=TRUE) # some systems are not well defined, we'll just ignore the errors
  N_list[[j]] <- N
}


问:
Why isn't counter() called in "false && counter()"?
I am trying to figure out how this boolean expression is evaluated:

```<code>int i = 0;
boolean exp = i > 1 && counter();
</code>```

In the following code:

```<code>public class Main {

    static int num = 0;

    public static boolean counter(){
            num++;
         if(num == 6){
             return true;
         }
          return false;
     }
    public static void main(String[] args) {
            //int i = 2;
              int i = 0;
            boolean exp = i > 1 && counter();
            System.out.println(num); // 0
            System.out.println(exp); // false
    }
 }
</code>```

Since i = 0, i > 1 is false and counter() returns false. However, I'm confused because the value of static variable num doesn't change despite the counter() function being in the boolean expression:

```<code>exp = i > 1 && counter();
</code>```

I was expecting the output to be

```<code>1
false
</code>```

but it is

```<code>0
false
</code>```

Why does counter() not seem to be called?

答:
This is because && is short-circuiting. When i > 1 evaluates to false, there is no need to check the other side of the logical AND because the resulting expression will always be false. Therefore, the method counter is never run.

To fix this, you can either move counter() to be the first condition, or use the non-short-circuiting &.

Body:
I am trying to figure out how this boolean expression is evaluated:

int i = 0;
boolean exp = i > 1 && counter();

In the following code:

public class Main {

    static int num = 0;

    public static boolean counter(){
            num++;
         if(num == 6){
             return true;
         }
          return false;
     }
    public static void main(String[] args) {
            //int i = 2;
              int i = 0;
            boolean exp = i > 1 && counter();
            System.out.println(num); // 0
            System.out.println(exp); // false
    }
 }

Since i = 0, i > 1 is false and counter() returns false. However, I'm confused because the value of static variable num doesn't change despite the counter() function being in the boolean expression:

exp = i > 1 && counter();

I was expecting the output to be

1
false

but it is

0
false

Why does counter() not seem to be called?


问:
Duplicate entry for key 'PRIMARY' php
I have the following datatables:

When I enter the data to the participantes_atividades table it shows me this error:

Duplicate entry for key 'PRIMARY

```<code>$sql = "INSERT INTO participantes_atividades (cd_p,cd_ati) VALUES ('$p','$cd')";

if (mysqli_query($connect, $sql) or die (mysqli_error($connect)))
</code>```

答: You are trying to insert a pair of values that are already stored in this table</p>

Title: Duplicate entry for key 'PRIMARY' php

Body:
I have the following datatables:

When I enter the data to the participantes_atividades table it shows me this error:

Duplicate entry for key 'PRIMARY

$sql = "INSERT INTO participantes_atividades (cd_p,cd_ati) VALUES ('$p','$cd')";

if (mysqli_query($connect, $sql) or die (mysqli_error($connect)))


问:
JWPlayer 7 error "cannot load m3u8 crossdomain access denied" chrome only win 10
On pc windows 10 Firefox and Edge loads ok. In chrome only! "cannot load m3u8: crossdomain access denied"

JWPlayer HTML code

Crossdomain.xml

```<code><cross-domain-policy>
  <allow-access-from domain="*" secure="false"/>
  <allow-http-request-headers-from secure="false" headers="*" domain="*"/>
</cross-domain-policy>
</code>```

答:
You need to set the CORS header of stream files  ..../playlist.m3u8 and it's needed when the player works in HTML5 Mode (on new releases of Chrome the  Flash plugin has blocked by default)

```<code>Access-Control-Allow-Origin:*
</code>```

It's a mechanism similar to Flash.

You can test your CORS HLS streams on hls.js demo page: http://video-dev.github.io/hls.js/demo/

about CORS: https://enable-cors.org/

Body:
On pc windows 10 Firefox and Edge loads ok. In chrome only! "cannot load m3u8: crossdomain access denied"

JWPlayer HTML code

Crossdomain.xml

<cross-domain-policy>
  <allow-access-from domain="*" secure="false"/>
  <allow-http-request-headers-from secure="false" headers="*" domain="*"/>
</cross-domain-policy>

Body:
You need to set the CORS header of stream files  ..../playlist.m3u8 and it's needed when the player works in HTML5 Mode (on new releases of Chrome the  Flash plugin has blocked by default)

Access-Control-Allow-Origin:*

It's a mechanism similar to Flash.

You can test your CORS HLS streams on hls.js demo page: http://video-dev.github.io/hls.js/demo/

about CORS: https://enable-cors.org/