问:
Using vectorization to get a specific matrix output from two vectors
I wanted to know if there is a efficient way using MATLAB vectorization to generate a specific matrix from two vectors.

Suppose the vectors are

```<code>x = [u v]

y = [a1 a2 a3 b1 b2 b3]
</code>```

where u, v, a1, a2, a3, b1, b2, b3 are some real numbers.

The 2-column matrix that I wish to generate using these vectors is

```<code>M = [u  a1;
     u  a2;
     u  a3;
     v  a1;
     v  a2;
     v  a3;
     u  b1;
     u  b2;
     u  b3;
     v  b1;
     v  b2;
     v  b3]
</code>```

In general, the length of x can be anything and the length of y is multiple of 3. Here is the code that I have now, but I think there should some better way (that possibly avoids the use of for-loop):

```<code>M = [];
Y = reshape(y, 3, []);

for j = 1:size(Y, 2)
    [a, b] = meshgrid(x, Y(:, j));
    L = [a(:) b(:)];
    M = [M; L];
end
</code>```

答:
you have a pretty strange order in M. Is that order important? if not, or if you are happy to fix the order later yourself I have two solutions:

1) code

```<code>[a,b] = meshgrid(x,y);
M = [a(:) b(:)]
</code>```

will give you:

```<code>M = [
 u  a1
 u  a2
 u  a3
 u  b1
 u  b2
 u  b3
 v  a1
 v  a2
 v  a3
 v  b1
 v  b2
 v  b3]
</code>```

and

2) code M = combvec(x, y)' gives you:

```<code>M = [
 u  a1
 v  a1
 u  a2
 v  a2
 u  a3
 v  a3
 u  b1
 v  b1
 u  b2
 v  b2
 u  b3
 v  b3]
</code>```

Body:
I wanted to know if there is a efficient way using MATLAB vectorization to generate a specific matrix from two vectors.

Suppose the vectors are

x = [u v]

y = [a1 a2 a3 b1 b2 b3]

where u, v, a1, a2, a3, b1, b2, b3 are some real numbers.

The 2-column matrix that I wish to generate using these vectors is

M = [u  a1;
     u  a2;
     u  a3;
     v  a1;
     v  a2;
     v  a3;
     u  b1;
     u  b2;
     u  b3;
     v  b1;
     v  b2;
     v  b3]

In general, the length of x can be anything and the length of y is multiple of 3. Here is the code that I have now, but I think there should some better way (that possibly avoids the use of for-loop):

M = [];
Y = reshape(y, 3, []);

for j = 1:size(Y, 2)
    [a, b] = meshgrid(x, Y(:, j));
    L = [a(:) b(:)];
    M = [M; L];
end

Body:
you have a pretty strange order in M. Is that order important? if not, or if you are happy to fix the order later yourself I have two solutions:

1) code

[a,b] = meshgrid(x,y);
M = [a(:) b(:)]

will give you:

M = [
 u  a1
 u  a2
 u  a3
 u  b1
 u  b2
 u  b3
 v  a1
 v  a2
 v  a3
 v  b1
 v  b2
 v  b3]

and

2) code M = combvec(x, y)' gives you:

M = [
 u  a1
 v  a1
 u  a2
 v  a2
 u  a3
 v  a3
 u  b1
 v  b1
 u  b2
 v  b2
 u  b3
 v  b3]


来源: stackexchange

问:
How to make my if statement run once in a while loop
I'm trying to make a simplified mock banking terminal application for a class in python. I'm trying to make it so that if they have a checking or savings account they cannot create a new one. I have tried setting cacc_check to a global variable in both the if loop_set and outside of the while loop. When I try that it complains that cacc_check hasn't been initialized before it has been used. When I have cacc_check = in if menu_choice == 1 it will reset it to 0 every time I enter that loop. I'm not sure how to initialize cacc_check so that it won't get reset to 0 every time I enter that menu and still be able to be used in the `if acc_choice == 1 and cacc_check != 0' so that any account number generated is not wiped out. This is where I'm stuck right now:

```<code>import random
loop_set = 1

while loop_set < 5:

def homeScreen():
    print('Welcome to your bank application \n 1. Create Account \n 2. Make a Deposit \n 3. Make a Withdrawal \n'
          ' 4. View Accounts \n 5. View Transactions \n 6. Transfer Money \n 7. Loans \n 8. Close an Account')
    menu_choice = int(input('Please enter a number to select an option'))
    if menu_choice == 0:
        homeScreen()
    if menu_choice == 1:
        cacc_check = 0
        sacc_check =
        print('Creating Account')
        name = str(input('Please enter your name: '))
        acc_choice = int(input('Type 1 for a checking account and 2 for a savings account'))
        if acc_choice == 1 and cacc_check == 0:
            cacc_num = random.randint(1000, 9999)
            cacc_check += 1
            print('Hello ', name, 'your checking account number is', cacc_num)
            homeScreen()
        if acc_choice == 1 and cacc_num != 0:
            print("It looks like you already have a checking account with us")
            homeScreen()
        if acc_choice == 2 and sacc_check == 0:
            sacc_num = random.randint(1000, 9999)
            print('Hello ', name, 'your savings account number is', sacc_num)

    if loop_set == 1:
        loop_set = loop_set + 1
        print('loop_set = ', loop_set)
        homeScreen()
</code>```

I'd like to be able to ensure that it can only run through the statement assigning a random account number once, or else that account number will get overwritten next time it goes through. I apologize in advance for bad formatting and optimization. I'm sure there are better ways to accomplish what I'm trying to do but I'm still learning. Any advice is appreciated.

答:
You need to move the variables to before the while loop. That way the values don't get reset each time the loop runs. Try something like:

```<code>import random

def homeScreen():
    print('Welcome to your bank application \n 1. Create Account \n 2. Make a Deposit \n 3. Make a Withdrawal \n'
          ' 4. View Accounts \n 5. View Transactions \n 6. Transfer Money \n 7. Loans \n 8. Close an Account')

def loopScreen():
    menu_choice = int(input('Please enter a number to select an option'))
    loop_set = 1
    cacc_check = 0
    sacc_check = 0

    while loop_set < 5:
        if menu_choice == 0:
            homeScreen()
        if menu_choice == 1:
            print('Creating Account')
            name = str(input('Please enter your name: '))
            acc_choice = int(input('Type 1 for a checking account and 2 for a savings account'))
            if acc_choice == 1 and cacc_check == 0:
                cacc_num = random.randint(1000, 9999)
                cacc_check += 1
                print('Hello ', name, 'your checking account number is', cacc_num)
                homeScreen()
            if acc_choice == 1 and cacc_num != 0:
                print("It looks like you already have a checking account with us")
                homeScreen()
            if acc_choice == 2 and sacc_check == 0:
                sacc_num = random.randint(1000, 9999)
                print('Hello ', name, 'your savings account number is', sacc_num)

        if loop_set == 1:
            loop_set = loop_set + 1
            print('loop_set = ', loop_set)
            homeScreen()

loopScreen()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to make a simplified mock banking terminal application for a class in python. I'm trying to make it so that if they have a checking or savings account they cannot create a new one. I have tried setting cacc_check to a global variable in both the if loop_set and outside of the while loop. When I try that it complains that cacc_check hasn't been initialized before it has been used. When I have cacc_check = in if menu_choice == 1 it will reset it to 0 every time I enter that loop. I'm not sure how to initialize cacc_check so that it won't get reset to 0 every time I enter that menu and still be able to be used in the `if acc_choice == 1 and cacc_check != 0' so that any account number generated is not wiped out. This is where I'm stuck right now:

import random
loop_set = 1

while loop_set < 5:

def homeScreen():
    print('Welcome to your bank application \n 1. Create Account \n 2. Make a Deposit \n 3. Make a Withdrawal \n'
          ' 4. View Accounts \n 5. View Transactions \n 6. Transfer Money \n 7. Loans \n 8. Close an Account')
    menu_choice = int(input('Please enter a number to select an option'))
    if menu_choice == 0:
        homeScreen()
    if menu_choice == 1:
        cacc_check = 0
        sacc_check =
        print('Creating Account')
        name = str(input('Please enter your name: '))
        acc_choice = int(input('Type 1 for a checking account and 2 for a savings account'))
        if acc_choice == 1 and cacc_check == 0:
            cacc_num = random.randint(1000, 9999)
            cacc_check += 1
            print('Hello ', name, 'your checking account number is', cacc_num)
            homeScreen()
        if acc_choice == 1 and cacc_num != 0:
            print("It looks like you already have a checking account with us")
            homeScreen()
        if acc_choice == 2 and sacc_check == 0:
            sacc_num = random.randint(1000, 9999)
            print('Hello ', name, 'your savings account number is', sacc_num)

    if loop_set == 1:
        loop_set = loop_set + 1
        print('loop_set = ', loop_set)
        homeScreen()

I'd like to be able to ensure that it can only run through the statement assigning a random account number once, or else that account number will get overwritten next time it goes through. I apologize in advance for bad formatting and optimization. I'm sure there are better ways to accomplish what I'm trying to do but I'm still learning. Any advice is appreciated.

Body:
You need to move the variables to before the while loop. That way the values don't get reset each time the loop runs. Try something like:

import random

def homeScreen():
    print('Welcome to your bank application \n 1. Create Account \n 2. Make a Deposit \n 3. Make a Withdrawal \n'
          ' 4. View Accounts \n 5. View Transactions \n 6. Transfer Money \n 7. Loans \n 8. Close an Account')

def loopScreen():
    menu_choice = int(input('Please enter a number to select an option'))
    loop_set = 1
    cacc_check = 0
    sacc_check = 0

    while loop_set < 5:
        if menu_choice == 0:
            homeScreen()
        if menu_choice == 1:
            print('Creating Account')
            name = str(input('Please enter your name: '))
            acc_choice = int(input('Type 1 for a checking account and 2 for a savings account'))
            if acc_choice == 1 and cacc_check == 0:
                cacc_num = random.randint(1000, 9999)
                cacc_check += 1
                print('Hello ', name, 'your checking account number is', cacc_num)
                homeScreen()
            if acc_choice == 1 and cacc_num != 0:
                print("It looks like you already have a checking account with us")
                homeScreen()
            if acc_choice == 2 and sacc_check == 0:
                sacc_num = random.randint(1000, 9999)
                print('Hello ', name, 'your savings account number is', sacc_num)

        if loop_set == 1:
            loop_set = loop_set + 1
            print('loop_set = ', loop_set)
            homeScreen()

loopScreen()


问:
Why Erlang is suitable for soft real-time applications, but not for hard real-time?
Or maybe it's good for hard real-time too?</p>

答:
There is a presentation from 2008 by Vincenzo Nicosia describing work on HRT erlang (HARTE), which also describes the problems regarding hard real-time of the current BEAM, etc.
Have a look at http://www.erlang.org/workshop/2007/proceedings/05nicosi.pdf</p>

ContentLicense: CC BY-SA 2.5


问:
.notify() isn't notifying .wait() for a Thread
I've been having trouble trying to get a waited thread to by notified.

Here is the code for where the notify() is called:

```<code>public static void main(String[] args)
    {
        int endUsers = 0;
        Terminal terminal = new Terminal("Master");
        ArrayList<Thread> threads = new ArrayList<Thread>();
        threads.add(new Thread(
                new EndUser("EndUser 1", DEFAULT_DST_NODE, 50000, 50001),
                "EndUser 1"));
        endUsers++;
        threads.add(new Thread(
                new EndUser("EndUser 2", DEFAULT_DST_NODE, 50001, 50000),
                "EndUser 2"));
        endUsers++;

        for (Thread t : threads)
        {
            t.start();
        }

        while (true)
        {
            int user = terminal.readInt("Which user is sending data?  ");
            if (user <= endUsers && user > 0)
            {
                synchronized (threads.get(user - 1))
                {
                    threads.get(user - 1).notify();
                }
            }
        }
    }
}
</code>```

And here is the code where wait() is called:

```<code>public void run()
{
    while (true)
    {
        try
        {
            synchronized (this)
            {
                this.wait();
            }
            this.send();
        }
        catch (Exception e)
        {

        }
    }
}
</code>```

I've tried everything I can think of but I have no idea why it isn't working.

答:
```<code>threads.get(user - 1).notify();
</code>```

is invoking notify on the Thread object, where

```<code>this.wait();
</code>```

is waiting on your runnable, or the class in which the call is housed.
Using

```<code>Thread.currentThread().wait();
</code>```

should fix your issue.

In addition, I would like to mention that creating an Object reference, then waiting on and notifying that would be a fully functional method to obtain what you want as well

You would create the Object as a(n) (optionally static) reference in your thread class

```<code>public final (static) Object waitObject = new Object();
</code>```

Edit: ^ Making this final prevents other (likely malicious) code parts
  from reassigning the value, which would make it so that the waitObject.notify()
  method is never actually able to be reached.

Then use

```<code>waitObject.wait();  //or
waitObject.wait(time);
</code>```

And

```<code>waitObject.notify();  //or
waitObject.notifyAll();
</code>```

Edit:
As was pointed out by @shmosel, it is inherently unsafe to use "wait", "sleep", or "notify" from within a thread, as outlined within the Java Documentation. However, despite this, the functionality is still available for use, though discouraged.

For additional Java references you have multiple resources available to you; such as.:
Java API Overview, Java Thread API, This Google Search - Safe Java Practices (to which you can append what you are looking into, such as "Threading, Wait" for a search query of "Safe Java Practices Threading, Wait"), and many more.

Body:
I've been having trouble trying to get a waited thread to by notified.

Here is the code for where the notify() is called:

public static void main(String[] args)
    {
        int endUsers = 0;
        Terminal terminal = new Terminal("Master");
        ArrayList<Thread> threads = new ArrayList<Thread>();
        threads.add(new Thread(
                new EndUser("EndUser 1", DEFAULT_DST_NODE, 50000, 50001),
                "EndUser 1"));
        endUsers++;
        threads.add(new Thread(
                new EndUser("EndUser 2", DEFAULT_DST_NODE, 50001, 50000),
                "EndUser 2"));
        endUsers++;

        for (Thread t : threads)
        {
            t.start();
        }

        while (true)
        {
            int user = terminal.readInt("Which user is sending data?  ");
            if (user <= endUsers && user > 0)
            {
                synchronized (threads.get(user - 1))
                {
                    threads.get(user - 1).notify();
                }
            }
        }
    }
}

And here is the code where wait() is called:

public void run()
{
    while (true)
    {
        try
        {
            synchronized (this)
            {
                this.wait();
            }
            this.send();
        }
        catch (Exception e)
        {

        }
    }
}

I've tried everything I can think of but I have no idea why it isn't working.

Body:
threads.get(user - 1).notify();

is invoking notify on the Thread object, where

this.wait();

is waiting on your runnable, or the class in which the call is housed.
Using

Thread.currentThread().wait();

should fix your issue.

In addition, I would like to mention that creating an Object reference, then waiting on and notifying that would be a fully functional method to obtain what you want as well

You would create the Object as a(n) (optionally static) reference in your thread class

public final (static) Object waitObject = new Object();

Edit: ^ Making this final prevents other (likely malicious) code parts
  from reassigning the value, which would make it so that the waitObject.notify()
  method is never actually able to be reached.

Then use

waitObject.wait();  //or
waitObject.wait(time);

And

waitObject.notify();  //or
waitObject.notifyAll();

Edit:
As was pointed out by @shmosel, it is inherently unsafe to use "wait", "sleep", or "notify" from within a thread, as outlined within the Java Documentation. However, despite this, the functionality is still available for use, though discouraged.

For additional Java references you have multiple resources available to you; such as.:
Java API Overview, Java Thread API, This Google Search - Safe Java Practices (to which you can append what you are looking into, such as "Threading, Wait" for a search query of "Safe Java Practices Threading, Wait"), and many more.


问:
Python. Detect changes in vector direction
I have a vector y that either increments or decrements by 1. What I want is to create a another vector y2 that shows when y1 changed direction.

I can't figure out how to do this in numpy.

EDIT updated plot, due to missing comma in y

```<code>import matplotlib.pyplot as plt
import numpy as np
</code>```

EDIT: Fixed missing comma in y

```<code>import matplotlib.pyplot as plt
import numpy as np

y = np.array([0,0,1,1,2,2,1,0,-1,-1,0,0,1])

x = np.arange(len(y))

y2 = np.array([0,0,1,0,0,0,-1,0,0,0,1,0,0])

plt.plot(x, y, label='y - Actual')
plt.plot(x, y2, label='y2 - Desired')
plt.legend()
plt.show()
</code>```

答:
Try taking a derivative:

```<code>dy = y[1:] - y[:-1]
</code>```

Then check if adjacent points have switched derivative signs:

```<code>increasing = dy > 0
decreasing = dy < 0
saddle = dy == 0

change_increasing = increasing[1:] and decreasing[:-1]
change_decreasing = decreasing[1:] and increasing[:-1]
</code>```

Bring all that information together:

```<code>changes = np.zeros_like(dy)

changes[0] = (1 * increasing[0]) + (-1 * decreasing[0])
changes[1:][change_increasing] = 1
changes[1:][change_decreasing] = -1
changes[saddle] = 0

print(changes)
</code>```

Body:
I have a vector y that either increments or decrements by 1. What I want is to create a another vector y2 that shows when y1 changed direction.

I can't figure out how to do this in numpy.

EDIT updated plot, due to missing comma in y

import matplotlib.pyplot as plt
import numpy as np

EDIT: Fixed missing comma in y

import matplotlib.pyplot as plt
import numpy as np

y = np.array([0,0,1,1,2,2,1,0,-1,-1,0,0,1])

x = np.arange(len(y))

y2 = np.array([0,0,1,0,0,0,-1,0,0,0,1,0,0])

plt.plot(x, y, label='y - Actual')
plt.plot(x, y2, label='y2 - Desired')
plt.legend()
plt.show()

Body:
Try taking a derivative:

dy = y[1:] - y[:-1]

Then check if adjacent points have switched derivative signs:

increasing = dy > 0
decreasing = dy < 0
saddle = dy == 0

change_increasing = increasing[1:] and decreasing[:-1]
change_decreasing = decreasing[1:] and increasing[:-1]

Bring all that information together:

changes = np.zeros_like(dy)

changes[0] = (1 * increasing[0]) + (-1 * decreasing[0])
changes[1:][change_increasing] = 1
changes[1:][change_decreasing] = -1
changes[saddle] = 0

print(changes)


问:
What happened when I create object using new keyword in static function
This is my code so far:

```<code>public class ServerUtility
{
    public static int LogError(string source, string detail)
    {
        int iresult = -99;
        try
        {
            BaseRepository repo = new BaseRepository();
            using (SqlConnection con = new SqlConnection(repo.connectionString))
            {
                con.Open();
                using (SqlCommand cmd = new SqlCommand($"INSERT INTO [dbo].[LogError]([source],[detail],[date])VALUES('{source.Replace("'", "''")}','{detail.Replace("'", "''")}',GETDATE());SELECT @@IDENTITY", con))
                {
                    string getValue = cmd.ExecuteScalar().ToString();
                    iresult = Convert.ToInt32(getValue);
                } // command disposed here

            } //connection closed and disposed here
        }
        catch (Exception ex) { throw ex; }
        return iresult;
    }
}
</code>```

My question is on GetInstance method :

```<code>BaseRepository repo = new BaseRepository();
using (SqlConnection con = new SqlConnection(repo.connectionString))
</code>```

I am always set it as new object, on my static function, just for get constant value from AppSetting.

What actually happened if I implement this code to my project?
How about the performance?

Is it cause performance issue?

Thanks

答:
Like @gtosto mentioned, you're not implementing singletons correctly.

It should be:

```<code>    public static SenderBackupProvider GetInstance()
    {
        if (oInstance == null)
        {
            oInstance = new SenderBackupProvider(CommFunction.GetLogNumber(CommonConst.APPID));
        }

        return oInstance;
    }
</code>```

Check out Implementing the Singleton Pattern in C#.

EDIT:

Since OP doesn't believe that the oInstance variable should be null on first time run, here's a screenshot.

Upon a closer look at your code, you are using a web application. The life cycle of static variables differ from one platform to the other. You might need to do an app domain restart in IIS. See more information in Lifetime of ASP.NET Static Variable.

Body:
This is my code so far:

public class ServerUtility
{
    public static int LogError(string source, string detail)
    {
        int iresult = -99;
        try
        {
            BaseRepository repo = new BaseRepository();
            using (SqlConnection con = new SqlConnection(repo.connectionString))
            {
                con.Open();
                using (SqlCommand cmd = new SqlCommand($"INSERT INTO [dbo].[LogError]([source],[detail],[date])VALUES('{source.Replace("'", "''")}','{detail.Replace("'", "''")}',GETDATE());SELECT @@IDENTITY", con))
                {
                    string getValue = cmd.ExecuteScalar().ToString();
                    iresult = Convert.ToInt32(getValue);
                } // command disposed here

            } //connection closed and disposed here
        }
        catch (Exception ex) { throw ex; }
        return iresult;
    }
}

My question is on GetInstance method :

BaseRepository repo = new BaseRepository();
using (SqlConnection con = new SqlConnection(repo.connectionString))

I am always set it as new object, on my static function, just for get constant value from AppSetting.

What actually happened if I implement this code to my project?
How about the performance?

Is it cause performance issue?

Thanks

Body:
Like @gtosto mentioned, you're not implementing singletons correctly.

It should be:

    public static SenderBackupProvider GetInstance()
    {
        if (oInstance == null)
        {
            oInstance = new SenderBackupProvider(CommFunction.GetLogNumber(CommonConst.APPID));
        }

        return oInstance;
    }

Check out Implementing the Singleton Pattern in C#.

EDIT:

Since OP doesn't believe that the oInstance variable should be null on first time run, here's a screenshot.

Upon a closer look at your code, you are using a web application. The life cycle of static variables differ from one platform to the other. You might need to do an app domain restart in IIS. See more information in Lifetime of ASP.NET Static Variable.


问:
2 line text UIButton
I have a UIButton and the text of the button is filled by a randomiser.
However my problem is that sometimes the number of characters in a text is too many, leading to the button now showing the whole text.

Would it be possible to check if the characters are too many and then have it drop the rest of the text to another text line? So basically having to text lines instead of one for the UIButton?

答:
In the Interface Builder, change the Line Break mode to Word Wrap for the UIButton control:

And to center the text, make the title Attributed instead of Plain.

Title: 2 line text UIButton


问:
Conditional Formatting based on cell color
Consider a list with 3 columns.

Column 1 holds a list of dates.

Column 2 holds fixed values, special days such national holidays (Easter) and special days such as Mothersday.

Column 3 holds user defined events.

Column 2 is populated via VBA code and the national holidays are colored blue by the same code but the special days such as Mothersday are not. The user can not manipulate this column.

Column 3 is populated by the users on the sheet itself. If the user adds an event in the third column, the row is colored green by means of conditional formatting.

The problem is that if an event coincides with a national holiday, the blue color is overwritten.

My goal is to add a second conditional formatting rule which checks for:

A user defined event is added

that the color of the row is blue

If both conditions are met a pattern color, pattern style and background color will be set so I'll get a combination of both colors.

If only the first condition is met, only the background color will be set.

In short: I need a way to check for a cell color and incorporate this in a conditional format rule.

答:
You must add 3 rules

R1: and(user defined event; not(Holiday)) > green.

R2: and(not(user defined event); Holiday) > blue.

R3: and(user defined event; Holiday) > mixed color.

Check the most right checkBoxs of R1, R2 in conditional format dialog box.


问:
Creating an efficient datatype for looking up conversion factors by initial and resulting units C#
I'm trying to create a windows form application that will convert units of measurements from one to the other.  My form features navigation buttons that I figured would make it user friendly.

When the user selects a category from the main menu it fills the category of measurement combobox and sets default unit of measurements into two other combo boxes.

These comboboxes allow the user to select which unit of measurement they want.  When they choose a category such as distance, it fills the initial and resulting unit of measurement comboboxes.

I therefore have already created a few string[] that contains each unit of measurement.

```<code>string[] distanceUnits = { "Inches", "Feet", "Centimeters", "Meters", "Kilometers", "Miles" };
string[] massUnits = { "Grams", "Kilograms", "Pounds", "Ounces" };
</code>```

I also created a couple different decimal[] arrays filled with conversion factors that I have been looking up and editing for precision purposes since I will be doing unit testing. I'd like to easily be able to change the conversion factor or add new ones into the arrays.

For example,

```<code>decimal[] massConversionFactors =
{
    .001m,               // [0] Grams to KiloGrams
    .00220462m,          // [1] Grams to Pounds
    .035274m,            // [2] Grams to Ounces
    1000,                // [3] KiloGrams to Grams
    2.20462m,            // [4] KiloGrams to Pounds
    35.274m,             // [5] KiloGrams to Ounces
    453.592m,            // [6] Pounds to Grams
    .453592m,            // [7] Pounds to Kilograms
    16                   // [8] Pounds to Ounces
};
</code>```

and

```<code>decimal[] distanceConversionFactors =
{
    .083333m,             // [0] Inches to Feet
    2.54m,                // [1] Inches to Centimeters
    .0254m,               // [2] Inches to Meters
    .0000254m,            // [3] Inches to Kilometers
    .0000157828282828m,   // [4] Inches to Miles
    12,                   // [5] Feet to Inches
    30.48m,               // [6] Feet to Centimetes
    .3048m,               // [7] Feet to Meters
    .0003048m,            // [8] Feet to Kilometers
    .000189394m,          // [9] Feet to Miles
    .3937009133858m,      // [10] Centimeters to Inches
    .03280840944882m,     // [11] Centimeters to Feet
    .01m,                 // [12] Centimeters to Meters
    .00001m,              // [13] Centimeters to Kilometers
    .0000062137m,         // [14] Centimeters to Miles
    39.3701m,             // [15] Meters to Inches
    3.28084m,             // [16] Meters to Feet
    100,                  // [17] Meters to Centimeters
    .001m,                // [18] Meters to Kilometers
    .000621371m,          // [19] Meters to Miles
    39370.1m,             // [20] Kilometers to Inches
    3280.84m,             // [21] Kilometers to Feet
    100000,               // [22] Kilometers to Centimeters
    1000,                 // [23] Kilometers to Meters
    .621371m,             // [24] Kilometers to Miles
    63360,                // [25] Miles to Inches
    5280,                 // [26] Miles to Feet
    160934,               // [27] Miles to Centimeters
    1609.34m,             // [28] Miles to Meters
    1.60934m              // [29] Miles to Kilometers
};
</code>```

That way when the submission button is pressed I can do a calculation such as:

```<code>private void ConvertSubmissionButton_Click(object sender, EventArgs e)
{
    //User's input value
    decimal input = decimal.Parse(UserInputTextBox.Text);
    string initialUnits = InitialUnitsComboBox.SelectedItem.ToString();
    string resultingUnits = ResultingUnitsComboBox.SelectedItem.ToString();

    //conversion of user input to result accepting initial and resulting
    decimal result =  input * ObjectWithTooManyMethods(initalUnits, resultingUnits);

    ResultingValueLabel.Text = (initialUnits);
    ResultingValueLabel.Show();
}
</code>```

This works fine for now, but as I add more methods to the object I wonder if there is a way to consolidate the already created arrays.

The problem I'm having is that I am forced to hardcode every permutation of conversion in the

```<code>ObjectWithTooManyMethods(string, string);
</code>```

What I'd really like to do is create a recursive loop that will go through the distanceUnits[] massUnits[] and other unit of measurement category arrays, and creates every possible permutation based on the category's appropriate conversionFactor arrays.
This way I can add on units of measurements and their conversion factors without coding an entire new method in the future.

Is this possible?

This ideal loop would create a single datatype that contains this information and be able to retrieve the decimal value for the conversion factor for initial, and resulting units when the user clicks a submission button.

Such as:

```<code>DesiredDatatype<string,string,decimal> conversionFactors = new DesiredDatatype<string,string,decimal>()
{
    {initialUnits, resultingUnits, conversionFactor}
};

    private void ConvertSubmissionButton_Click(object sender, EventArgs e)
    {
        //User's input value
        decimal input = decimal.Parse(UserInputTextBox.Text);
        string initialUnits = InitialUnitsComboBox.SelectedItem.ToString();
        string resultingUnits = ResultingUnitsComboBox.SelectedItem.ToString();

        decimal result =  input * conversionFactors.get(initialUnits, resultingUnits);

        ResultingValueLabel.Text = (result);
        ResultingValueLabel.Show();
    }
</code>```

Maybe I'm approaching this the wrong way, and/or have been coding too long today.. I have looked up information about tuples and dictionarys and they seem like they would ideal for this scenario but I have failed in creating a working datatype from looping through the information in these existing arrays.

Any advice is greatly appreciated. Thanks a lot!

答:
Since you don't want to use objects, what about using enumerations and dictionaries? You can define an enumeration like this...

```<code>public enum MassUnit
{
    Grams,
    Kilograms,
    Ounces,
    Pounds
}
</code>```

To convert enum values to and from strings you can...

```<code>var stringArrayOfEnumNames = Enum.GetNames(typeof(Mass));
var enumFromString = Enum.Parse(typeof(MassUnit), "Ounces");
</code>```

Next you could use a dictionary for your conversion amounts. There's no need to have every combination of conversions, just convert to a standard unit (grams) then convert to the destination unit. This dictionary stores values to convert any mass unit to grams.

```<code>public static Dictionary<MassUnit, decimal> MassToGramsMap = new Dictionary<MassUnit, decimal>
{
    [MassUnit.Grams] = 1m,
    [MassUnit.Kilograms] = .001m,
    [MassUnit.Ounces] = .035274m,
    [MassUnit.Pounds] = .00220462m
};
</code>```

Then a conversion would look like...

```<code>var value = 100m;
var from = MassUnit.Pounds;
var to = MassUnit.Kilograms;
var convertedValue = value / MassToGramsMap[from] * MassToGramsMap[to];
</code>```

Now if you wanted to add a new mass unit, you would add it to the MassUnit enumeration and add its conversion to MassToGramsMap dictionary and you're done.

Body:
I'm trying to create a windows form application that will convert units of measurements from one to the other.  My form features navigation buttons that I figured would make it user friendly.

When the user selects a category from the main menu it fills the category of measurement combobox and sets default unit of measurements into two other combo boxes.

These comboboxes allow the user to select which unit of measurement they want.  When they choose a category such as distance, it fills the initial and resulting unit of measurement comboboxes.

I therefore have already created a few string[] that contains each unit of measurement.

string[] distanceUnits = { "Inches", "Feet", "Centimeters", "Meters", "Kilometers", "Miles" };
string[] massUnits = { "Grams", "Kilograms", "Pounds", "Ounces" };

I also created a couple different decimal[] arrays filled with conversion factors that I have been looking up and editing for precision purposes since I will be doing unit testing. I'd like to easily be able to change the conversion factor or add new ones into the arrays.

For example,

decimal[] massConversionFactors =
{
    .001m,               // [0] Grams to KiloGrams
    .00220462m,          // [1] Grams to Pounds
    .035274m,            // [2] Grams to Ounces
    1000,                // [3] KiloGrams to Grams
    2.20462m,            // [4] KiloGrams to Pounds
    35.274m,             // [5] KiloGrams to Ounces
    453.592m,            // [6] Pounds to Grams
    .453592m,            // [7] Pounds to Kilograms
    16                   // [8] Pounds to Ounces
};

and

decimal[] distanceConversionFactors =
{
    .083333m,             // [0] Inches to Feet
    2.54m,                // [1] Inches to Centimeters
    .0254m,               // [2] Inches to Meters
    .0000254m,            // [3] Inches to Kilometers
    .0000157828282828m,   // [4] Inches to Miles
    12,                   // [5] Feet to Inches
    30.48m,               // [6] Feet to Centimetes
    .3048m,               // [7] Feet to Meters
    .0003048m,            // [8] Feet to Kilometers
    .000189394m,          // [9] Feet to Miles
    .3937009133858m,      // [10] Centimeters to Inches
    .03280840944882m,     // [11] Centimeters to Feet
    .01m,                 // [12] Centimeters to Meters
    .00001m,              // [13] Centimeters to Kilometers
    .0000062137m,         // [14] Centimeters to Miles
    39.3701m,             // [15] Meters to Inches
    3.28084m,             // [16] Meters to Feet
    100,                  // [17] Meters to Centimeters
    .001m,                // [18] Meters to Kilometers
    .000621371m,          // [19] Meters to Miles
    39370.1m,             // [20] Kilometers to Inches
    3280.84m,             // [21] Kilometers to Feet
    100000,               // [22] Kilometers to Centimeters
    1000,                 // [23] Kilometers to Meters
    .621371m,             // [24] Kilometers to Miles
    63360,                // [25] Miles to Inches
    5280,                 // [26] Miles to Feet
    160934,               // [27] Miles to Centimeters
    1609.34m,             // [28] Miles to Meters
    1.60934m              // [29] Miles to Kilometers
};

That way when the submission button is pressed I can do a calculation such as:

private void ConvertSubmissionButton_Click(object sender, EventArgs e)
{
    //User's input value
    decimal input = decimal.Parse(UserInputTextBox.Text);
    string initialUnits = InitialUnitsComboBox.SelectedItem.ToString();
    string resultingUnits = ResultingUnitsComboBox.SelectedItem.ToString();

    //conversion of user input to result accepting initial and resulting
    decimal result =  input * ObjectWithTooManyMethods(initalUnits, resultingUnits);

    ResultingValueLabel.Text = (initialUnits);
    ResultingValueLabel.Show();
}

This works fine for now, but as I add more methods to the object I wonder if there is a way to consolidate the already created arrays.

The problem I'm having is that I am forced to hardcode every permutation of conversion in the

ObjectWithTooManyMethods(string, string);

What I'd really like to do is create a recursive loop that will go through the distanceUnits[] massUnits[] and other unit of measurement category arrays, and creates every possible permutation based on the category's appropriate conversionFactor arrays.
This way I can add on units of measurements and their conversion factors without coding an entire new method in the future.

Is this possible?

This ideal loop would create a single datatype that contains this information and be able to retrieve the decimal value for the conversion factor for initial, and resulting units when the user clicks a submission button.

Such as:

DesiredDatatype<string,string,decimal> conversionFactors = new DesiredDatatype<string,string,decimal>()
{
    {initialUnits, resultingUnits, conversionFactor}
};

    private void ConvertSubmissionButton_Click(object sender, EventArgs e)
    {
        //User's input value
        decimal input = decimal.Parse(UserInputTextBox.Text);
        string initialUnits = InitialUnitsComboBox.SelectedItem.ToString();
        string resultingUnits = ResultingUnitsComboBox.SelectedItem.ToString();

        decimal result =  input * conversionFactors.get(initialUnits, resultingUnits);

        ResultingValueLabel.Text = (result);
        ResultingValueLabel.Show();
    }

Maybe I'm approaching this the wrong way, and/or have been coding too long today.. I have looked up information about tuples and dictionarys and they seem like they would ideal for this scenario but I have failed in creating a working datatype from looping through the information in these existing arrays.

Any advice is greatly appreciated. Thanks a lot!

Body:
Since you don't want to use objects, what about using enumerations and dictionaries? You can define an enumeration like this...

public enum MassUnit
{
    Grams,
    Kilograms,
    Ounces,
    Pounds
}

To convert enum values to and from strings you can...

var stringArrayOfEnumNames = Enum.GetNames(typeof(Mass));
var enumFromString = Enum.Parse(typeof(MassUnit), "Ounces");

Next you could use a dictionary for your conversion amounts. There's no need to have every combination of conversions, just convert to a standard unit (grams) then convert to the destination unit. This dictionary stores values to convert any mass unit to grams.

public static Dictionary<MassUnit, decimal> MassToGramsMap = new Dictionary<MassUnit, decimal>
{
    [MassUnit.Grams] = 1m,
    [MassUnit.Kilograms] = .001m,
    [MassUnit.Ounces] = .035274m,
    [MassUnit.Pounds] = .00220462m
};

Then a conversion would look like...

var value = 100m;
var from = MassUnit.Pounds;
var to = MassUnit.Kilograms;
var convertedValue = value / MassToGramsMap[from] * MassToGramsMap[to];

Now if you wanted to add a new mass unit, you would add it to the MassUnit enumeration and add its conversion to MassToGramsMap dictionary and you're done.


问:
Loop through all pixels and get/set individual pixel color in OpenGL?
I wrote a little thingy with Processing that I now would like to make a Mac OS X Screen Saver of. However, diving in to OpenGL was not as easy as I thought it would be.

Basically I want to loop through all pixels on screen and based on that pixels color set another pixels color.

The Processing code looks like this:

```<code>void setup(){
  size(500,500, P2D);
  frameRate(30);
  background(255);
}

void draw(){
 for(int x = 0; x<width; x++){
  for(int y = 0; y<height; y++){
     float xRand2 = x+random(2);
     float yRand2 = y+random(2);

     int xRand = int(xRand2);
     int yRand = int(yRand2);

     if(get(x,y) == -16777216){
     set(x+xRand, y+yRand, #FFFFFF);
     }
     else if(get(x,y) == -1){
     set(x+xRand, y+yRand, #000000);
     }
   }
 }
}
</code>```

It's not very pretty and nor is it very effective. However, I'd like to find out how to do something similiar with OpenGL. I don't even know where to start.

答:
There are a few bugs in your code that make reverse engineering and porting it harder, and make me wonder if you actually posted the correct code. Assuming that the visual effect produced is what you want, here is a more efficient and more correct draw():

```<code>void draw() {
  loadPixels();
  for(int x = 0; x<width/2; x++) {
    for(int y = 0; y<height/2; y++) {
      int x_new = 2*x+int(random(2));
      int y_new = 2*y+int(random(2));

      if (x_new < width && y_new < height) {
        int dest_pixel = (y_new*width + x_new);

        color c = pixels[y*width+x];

        if(c == #FFFFFF){
          pixels[dest_pixel] = #000000;
        }
        else {
          pixels[dest_pixel] = #FFFFFF;
        }
      }
    }
  }
  updatePixels();
}
</code>```

Note that the upper bounds of the loop are divided by two. As you wrote it, 3/4 of your set() calls were for pixels that are beyond the bounds of the window. The extra if is necessary because of the addition of small random values to the coordinates.

The overall effect of this code could be described as an in-place stretch and invert of the image, with a little bit of randomness thrown in. Because it's an in-place transformation, it can't be easily parallelized or accelerated, so you are best off implementing this as bitmap/texture operations on the CPU. You can do this without having to ever read pixels from the GPU, but you will have to push a screen full of pixels to the GPU each frame.

If you use glDrawPixels with a format argument of GL_LUMINANCE and a type argument of GL_UNSIGNED_BYTE, then you can pretty easily convert this code to operate on a byte array, which will keep the memory consumption down somewhat as compared with using 32-bit RGBA values.

Body:
I wrote a little thingy with Processing that I now would like to make a Mac OS X Screen Saver of. However, diving in to OpenGL was not as easy as I thought it would be.

Basically I want to loop through all pixels on screen and based on that pixels color set another pixels color.

The Processing code looks like this:

void setup(){
  size(500,500, P2D);
  frameRate(30);
  background(255);
}

void draw(){
 for(int x = 0; x<width; x++){
  for(int y = 0; y<height; y++){
     float xRand2 = x+random(2);
     float yRand2 = y+random(2);

     int xRand = int(xRand2);
     int yRand = int(yRand2);

     if(get(x,y) == -16777216){
     set(x+xRand, y+yRand, #FFFFFF);
     }
     else if(get(x,y) == -1){
     set(x+xRand, y+yRand, #000000);
     }
   }
 }
}

It's not very pretty and nor is it very effective. However, I'd like to find out how to do something similiar with OpenGL. I don't even know where to start.

Body:
There are a few bugs in your code that make reverse engineering and porting it harder, and make me wonder if you actually posted the correct code. Assuming that the visual effect produced is what you want, here is a more efficient and more correct draw():

void draw() {
  loadPixels();
  for(int x = 0; x<width/2; x++) {
    for(int y = 0; y<height/2; y++) {
      int x_new = 2*x+int(random(2));
      int y_new = 2*y+int(random(2));

      if (x_new < width && y_new < height) {
        int dest_pixel = (y_new*width + x_new);

        color c = pixels[y*width+x];

        if(c == #FFFFFF){
          pixels[dest_pixel] = #000000;
        }
        else {
          pixels[dest_pixel] = #FFFFFF;
        }
      }
    }
  }
  updatePixels();
}

Note that the upper bounds of the loop are divided by two. As you wrote it, 3/4 of your set() calls were for pixels that are beyond the bounds of the window. The extra if is necessary because of the addition of small random values to the coordinates.

The overall effect of this code could be described as an in-place stretch and invert of the image, with a little bit of randomness thrown in. Because it's an in-place transformation, it can't be easily parallelized or accelerated, so you are best off implementing this as bitmap/texture operations on the CPU. You can do this without having to ever read pixels from the GPU, but you will have to push a screen full of pixels to the GPU each frame.

If you use glDrawPixels with a format argument of GL_LUMINANCE and a type argument of GL_UNSIGNED_BYTE, then you can pretty easily convert this code to operate on a byte array, which will keep the memory consumption down somewhat as compared with using 32-bit RGBA values.


问:
Minimum Spanning Tree Algorithm
Hello I am new to the Algorithms and trying to understand the Minimum Spanning Trees.

I study the "Introduction to Algorithms" book by Cormen,Leiserson,Rivest and Stein. I have had a hard problem in understanding the sentence ".. a cut respects a set A of edges if no edge in A crosses the cut."

Let me clear my understanding by putting the pictures from the given example.
A minimum spanning tree for a connected graph.

1 way of viewing a cut (S,V-S) of the previous graph.

So my question is when we cut the graph as shown by the second figure shouldn't we also shade the edge (d,e) since it does not cross the cut ?

I would appreciate if you clarify this for me.

答:
This is kruskal's MST algorithm i think. Cut just partitions every subtree from the rest of the subtrees. We need to use the idea of the cut because when we join two subtrees we want no cycle and also the edge with minimum cost between those two subtrees.

In you image the cost of (d,e) is 9 so it's not a subtree. You can think of it as a not evaluated edge.  Your subtrees are (a,b) and (i,c,f,g,h) so a cut must differentiate these subtrees from other edges.

The shaded edges means that they are for sure in MST because they have minimum cost.

Here is just painted picture of your algorithm:

In the first iteration you get first cut black because the edge (g,h) has the minimum cost. Then you get red cut because after (g,h) gf has the minimum cost and because these two subtrees are attached to each other we use one cut. and so on ... I hope you can execute it further.You can see here visualization how Kruskal's algorithm works.

Title: Minimum Spanning Tree Algorithm


问:
Granting a role to a user on a replica set in MongoDB
Using Mongo commands, I can create and grant a role to a user on a UAT environment but not the Pre-Production environment, at least not permanently.  The difference between them?  UAT is a single DB, Pre-Production is a replica set.

After a few seconds the role "disappears" from the user.  If I run the commmand "show users", the role is visible for the user, when I run it again several seconds later, it "disappears".

Why is it disappearing, and how can I ensure the role is set permanently?

答:
You need to create role and user on Primary node:

use products
db.grantRolesToUser(
   "accountUser01",
   [ "readWrite" , { role: "read", db: "stock" } ],
   { w: "majority" , wtimeout: 4000 }
)

Please make sure it creates successfully and it will stay.


问:
Check Internet connection reachability in xamarin forms
I am using https://github.com/jamesmontemagno/ConnectivityPlugin plugin to check internet connection reachability in my xamarin forms mobile application. But it's taking some time to load. Is there any way to reduce the loading time?</p>

```<code>       if (CrossConnectivity.Current.IsConnected)
       {
           if (await CrossConnectivity.Current.IsRemoteReachable(new Uri("https://www.google.lk/").Authority))
           {
               //do some thing
           }
           else
           {
              //connection is not reachable
           }
       }
</code>```

答:
Refer the step 2 of the following blog : How to check network status from Xamarin.Forms app?
https://bsubramanyamraju.blogspot.in/2017/04/xamarinforms-consuming-rest-webserivce_17.html</p>

Body:
I am using https://github.com/jamesmontemagno/ConnectivityPlugin plugin to check internet connection reachability in my xamarin forms mobile application. But it's taking some time to load. Is there any way to reduce the loading time?

       if (CrossConnectivity.Current.IsConnected)
       {
           if (await CrossConnectivity.Current.IsRemoteReachable(new Uri("https://www.google.lk/").Authority))
           {
               //do some thing
           }
           else
           {
              //connection is not reachable
           }
       }


问:
How can I get Visual Studio 2008 Windows Forms designer to render a Form that implements an abstract base class?
I engaged a problem with inherited Controls in Windows Forms and need some advice on it.

I do use a base class for items in a List (selfmade GUI list made of a panel) and some inherited controls that are for each type of data that could be added to the list.

There was no problem with it, but I now found out, that it would be right, to make the base-control an abstract class, since it has methods, that need to be implemented in all inherited controls, called from the code inside the base-control, but must not and can not be implemented in the base class.

When I mark the base-control as abstract, the Visual Studio 2008 Designer refuses to load the window.

Is there a way to get the Designer work with the base-control made abstract?

答:
I had a similar problem but found a way to refactor things to use an interface in place of an abstract base class:

```<code>interface Base {....}

public class MyUserControl<T> : UserControl, Base
     where T : /constraint/
{ ... }
</code>```

This may not be applicable to every situation, but when possible it results in a cleaner solution than conditional compilation.

Body:
I had a similar problem but found a way to refactor things to use an interface in place of an abstract base class:

interface Base {....}

public class MyUserControl<T> : UserControl, Base
     where T : /constraint/
{ ... }

This may not be applicable to every situation, but when possible it results in a cleaner solution than conditional compilation.


问:
Remove python circular import
user.py:

```<code>from story import Story

class User:
    ...
    def get_stories(self):
        story_ids = [select from database]
        return [Story.get_by_id(id) for id in story_ids]
</code>```

story.py

```<code>from user import User

class Story:
    ...
    def __init__(self, id, user_id, content):
        self.id = id
        self.user = User.get_by_id(user_id)
        self.content = content
</code>```

as you can see, there is a circular import in this program, which causes an ImportError. I learned that I can move the import statement in method definition to prevent this error. But I still want to know, is there a way to remove circular import in this case, or, is it necessary (for a good design) ?

答:
There are a bunch of these python circular import questions on the web.  I chose to contribute to this thread because the query has a comment by Ray Hettinger that legitimizes the use case of a circular import, but recommends a solution that I believe is not especially good practice - moving the import to a method.

Apart from Hettinger's authority, three disclaimers to common objections are necessary:

I've never programmed in Java.  I'm not trying to do Java style.

Refactoring is not always useful or effective.  Logical API sometimes dictates a structure that makes recursive import references unavoidable.  Remember, code exists for users, not programmers.

Combining modules that are quite large can cause readability and maintainability issues that may be much worse than one or two recursive imports.

In addition, I believe maintainability and readability dictates that imports be grouped at the top of the file, occur only once for each needed name, and that the from module import name style is preferable (except perhaps for very short module names with many functions, e.g. gtk), as it avoids repetitive verbal clutter and makes dependencies explicit.

With that out of the way, I will posit a simplified version of my own use case that brought me here, and provide my solution.

I have two modules, each defining many classes.  surface defines geometric surfaces like planes, spheres, hyperboloids, etc.  path defines planar geometric figures like lines, circles hyperbolae, etc.  Logically, these are distinct categories and refactoring is not an option from the perspective of API requirements.  Nevertheless, these two categories are intimate.

A useful operation is intersecting two surfaces, for example, the intersection of two planes is a line, or the intersection of a plane and a sphere is a circle.

If for example, in surface.py you do the straight forward import needed to implement the return value for an intersection operation:

```<code>from path import Line
</code>```

you get:

```<code>Traceback (most recent call last):
  File "surface.py", line 62, in <module>
    from path import Line
  File ".../path.py", line 25, in <module>
    from surface import Plane
  File ".../surface.py", line 62, in <module>
    from path import Line
ImportError: cannot import name Line
</code>```

Geometrically, planes are used to define the paths, after all, they may be arbitrarily oriented in three (or more) dimensions.  The traceback tells you both what is happening and the solution.

Simply replace the import statement in surface.py with:

```<code>try: from path import Line
except ImportError: pass # skip circular import second pass
</code>```

The sequence of operations in the trace back is still happening.  It is just that the second time through, we ignore the import failure.  This does not matter, since Line is not used at the module level.  Therefore, the necessary namespace of surface is loaded into path. The namespace parsing of path can therefore complete, permitting it to be loaded into surface, completing the first encounter with from path import Line.  Thus the namespace parsing of surface can proceed and complete, continuing on to whatever else may be necessary.

It is an easy and very clear idiom.  The try: ... except ... syntax clearly and succinctly documents the circular import issue, easing whatever future maintenance may be required.  Use it whenever a refactor really is a bad idea.

Title: Remove python circular import

Body:
user.py:

from story import Story

class User:
    ...
    def get_stories(self):
        story_ids = [select from database]
        return [Story.get_by_id(id) for id in story_ids]

story.py

from user import User

class Story:
    ...
    def __init__(self, id, user_id, content):
        self.id = id
        self.user = User.get_by_id(user_id)
        self.content = content

as you can see, there is a circular import in this program, which causes an ImportError. I learned that I can move the import statement in method definition to prevent this error. But I still want to know, is there a way to remove circular import in this case, or, is it necessary (for a good design) ?

Body:
There are a bunch of these python circular import questions on the web.  I chose to contribute to this thread because the query has a comment by Ray Hettinger that legitimizes the use case of a circular import, but recommends a solution that I believe is not especially good practice - moving the import to a method.

Apart from Hettinger's authority, three disclaimers to common objections are necessary:

I've never programmed in Java.  I'm not trying to do Java style.

Refactoring is not always useful or effective.  Logical API sometimes dictates a structure that makes recursive import references unavoidable.  Remember, code exists for users, not programmers.

Combining modules that are quite large can cause readability and maintainability issues that may be much worse than one or two recursive imports.

In addition, I believe maintainability and readability dictates that imports be grouped at the top of the file, occur only once for each needed name, and that the from module import name style is preferable (except perhaps for very short module names with many functions, e.g. gtk), as it avoids repetitive verbal clutter and makes dependencies explicit.

With that out of the way, I will posit a simplified version of my own use case that brought me here, and provide my solution.

I have two modules, each defining many classes.  surface defines geometric surfaces like planes, spheres, hyperboloids, etc.  path defines planar geometric figures like lines, circles hyperbolae, etc.  Logically, these are distinct categories and refactoring is not an option from the perspective of API requirements.  Nevertheless, these two categories are intimate.

A useful operation is intersecting two surfaces, for example, the intersection of two planes is a line, or the intersection of a plane and a sphere is a circle.

If for example, in surface.py you do the straight forward import needed to implement the return value for an intersection operation:

from path import Line

you get:

Traceback (most recent call last):
  File "surface.py", line 62, in <module>
    from path import Line
  File ".../path.py", line 25, in <module>
    from surface import Plane
  File ".../surface.py", line 62, in <module>
    from path import Line
ImportError: cannot import name Line

Geometrically, planes are used to define the paths, after all, they may be arbitrarily oriented in three (or more) dimensions.  The traceback tells you both what is happening and the solution.

Simply replace the import statement in surface.py with:

try: from path import Line
except ImportError: pass # skip circular import second pass

The sequence of operations in the trace back is still happening.  It is just that the second time through, we ignore the import failure.  This does not matter, since Line is not used at the module level.  Therefore, the necessary namespace of surface is loaded into path. The namespace parsing of path can therefore complete, permitting it to be loaded into surface, completing the first encounter with from path import Line.  Thus the namespace parsing of surface can proceed and complete, continuing on to whatever else may be necessary.

It is an easy and very clear idiom.  The try: ... except ... syntax clearly and succinctly documents the circular import issue, easing whatever future maintenance may be required.  Use it whenever a refactor really is a bad idea.


问:
Filter rows based on ID over multiple data frames with for loop
How can I filter 180 .csv files from my global directory based on a matching ID in another df named 'Camera' in R? When I tried to incorporate my one by one file filtering code (see step 3b) into a for-loop (see step 3a) I get the error:

Error in paste("i")$SegmentID : $ operator is invalid for atomic vectors.

I'm quite new to for loop functions, so I really appreciate your help! All the 180 files have a unique name, are different in length, but have the same column structure & names. They look like:

```<code> df 'File1'             df 'Camera'
 ID  Speed  Location      ID  Time
 1   30    4              1   10
 2   35    5              3   11
 3   40    6              5   12
 4   30    7
 5   35    8

 Filtered df 'File1'
 ID  Speed  Location
 1   30    4
 3   40    6
 5   35    8
</code>```

These are some samples of my code:

```<code>#STEP 1: read files
filenames <- list.files(path="06-06-2017_0900-1200uur",
                        pattern="*.csv")

# STEP 2: import files
for(i in filenames){
  filepath <- file.path("06-06-2017_0900-1200uur",paste(i))
  assign(i, read.csv2(filepath, header = TRUE, skip = "1"))
}

# STEP 3a: delete rows that do not match ID in df 'Cameras'
for(i in filesnames){
    paste("i") <- paste("i")[paste("i")$ID %in% Cameras$ID,]
}

#STEP 3b: filtering one by one
    File1  <- File1[File1$ID   %in% Camera$ID,]
</code>```

答:
Here is an approach that makes use of lists (generally a better way to go).  First, utilize the include.names argument in list.files():

```<code>fns <- list.files(
  path = "06-06-2017_0900-1200uur",
  pattern = "*.csv",
  include.names = T
  )
</code>```

Now you have a list of your filenames.  Next, apply read.csv2 to each of the filenames in your list:

```<code>dat <- lapply(fns, read.csv2, header = T, skip = 1)
</code>```

Now you have a list of data frames (the output from calling read.csv).  Finally, apply subset() to each of the data frames to keep only those rows which match the ID column:

```<code>out <- lapply(dat, function(x) subset(x, ID %in% Camera$ID))
</code>```

Body:
How can I filter 180 .csv files from my global directory based on a matching ID in another df named 'Camera' in R? When I tried to incorporate my one by one file filtering code (see step 3b) into a for-loop (see step 3a) I get the error:

Error in paste("i")$SegmentID : $ operator is invalid for atomic vectors.

I'm quite new to for loop functions, so I really appreciate your help! All the 180 files have a unique name, are different in length, but have the same column structure & names. They look like:

 df 'File1'             df 'Camera'
 ID  Speed  Location      ID  Time
 1   30    4              1   10
 2   35    5              3   11
 3   40    6              5   12
 4   30    7
 5   35    8

 Filtered df 'File1'
 ID  Speed  Location
 1   30    4
 3   40    6
 5   35    8

These are some samples of my code:

#STEP 1: read files
filenames <- list.files(path="06-06-2017_0900-1200uur",
                        pattern="*.csv")

# STEP 2: import files
for(i in filenames){
  filepath <- file.path("06-06-2017_0900-1200uur",paste(i))
  assign(i, read.csv2(filepath, header = TRUE, skip = "1"))
}

# STEP 3a: delete rows that do not match ID in df 'Cameras'
for(i in filesnames){
    paste("i") <- paste("i")[paste("i")$ID %in% Cameras$ID,]
}

#STEP 3b: filtering one by one
    File1  <- File1[File1$ID   %in% Camera$ID,]

Body:
Here is an approach that makes use of lists (generally a better way to go).  First, utilize the include.names argument in list.files():

fns <- list.files(
  path = "06-06-2017_0900-1200uur",
  pattern = "*.csv",
  include.names = T
  )

Now you have a list of your filenames.  Next, apply read.csv2 to each of the filenames in your list:

dat <- lapply(fns, read.csv2, header = T, skip = 1)

Now you have a list of data frames (the output from calling read.csv).  Finally, apply subset() to each of the data frames to keep only those rows which match the ID column:

out <- lapply(dat, function(x) subset(x, ID %in% Camera$ID))


问:
how can I control mobx observer?
I had a problem when I used observer function in react-mobx.

My source code like following,

```<code>import React from 'react';
import { observer } from 'mobx-react';

@observer
class Test extends React.Component{
  render(){
    const { student } = this.props; // it's @observable object

    return (
      <div>{student.name}</div>
    )
  }
}
</code>```

This component will rerender when student object is changed.

but I want to control when to re-render.

In short, I want to catch the point when this component re-render.

(It means student component was changed)

It's similar shouldComponentUpdate.

so I thought I can control using shouldComponentUpdate. but it doesn't work.

so how can I control this?

The final result I want is I don't want to re-render when the student component has certain parameter when it's re-render.

答:
To answer you question, there actually is one way of doing it (very hacky), by monkey patching the shouldComponentUpdate method:

```<code>@observer
class Test extends React.Component {

  constructor(props) {
    super(props);
    this.mobxShouldComponentUpdate = this.shouldComponentUpdate;
    this.shouldComponentUpdate = this.customShouldComponentUpdate;
  }

  customShouldComponentUpdate = (props, ...args) => {
    if (props.student === 'foo') {
      return false;
    }
    return this.mobxShouldComponentUpdate(props, ...args);
  }

  render(){
    const { student } = this.props; // it's @observable object
    return (
      <div>{student.name}</div>
    )
  }
}
</code>```

That said, this is usually an indication that you are thinking about your data in the wrong way. Ideally your components should just be a pure render function of the current state of the application.

```<code>class Test extends React.Component {
  render(){
    if (student.name === 'foo') {
      return <div>Custom info</div>
    }
    return (
      <div>{student.name}</div>
    )
  }
}
</code>```

Title: how can I control mobx observer?

Body:
I had a problem when I used observer function in react-mobx.

My source code like following,

import React from 'react';
import { observer } from 'mobx-react';

@observer
class Test extends React.Component{
  render(){
    const { student } = this.props; // it's @observable object

    return (

{student.name}

    )
  }
}

This component will rerender when student object is changed.

but I want to control when to re-render.

In short, I want to catch the point when this component re-render.

(It means student component was changed)

It's similar shouldComponentUpdate.

so I thought I can control using shouldComponentUpdate. but it doesn't work.

so how can I control this?

The final result I want is I don't want to re-render when the student component has certain parameter when it's re-render.

Body:
To answer you question, there actually is one way of doing it (very hacky), by monkey patching the shouldComponentUpdate method:

@observer
class Test extends React.Component {

  constructor(props) {
    super(props);
    this.mobxShouldComponentUpdate = this.shouldComponentUpdate;
    this.shouldComponentUpdate = this.customShouldComponentUpdate;
  }

  customShouldComponentUpdate = (props, ...args) => {
    if (props.student === 'foo') {
      return false;
    }
    return this.mobxShouldComponentUpdate(props, ...args);
  }

  render(){
    const { student } = this.props; // it's @observable object
    return (
      <div>{student.name}</div>
    )
  }
}

That said, this is usually an indication that you are thinking about your data in the wrong way. Ideally your components should just be a pure render function of the current state of the application.

class Test extends React.Component {
  render(){
    if (student.name === 'foo') {
      return <div>Custom info</div>
    }
    return (
      <div>{student.name}</div>
    )
  }
}


问:
What's the best way to write a command-line app in Java?
Okay, I know there are probably a dozen ways to solve this, but I am looking for either a skeleton app or some sort of tutorial that will explain the best way to write a framework for creating Java-based command-line tools.  If my program requires a lot of switches/options/etc., what's the best way to handle all of them?

How do you decide which stuff should be placed into an options/settings file, and which stuff gets put on the command line?  Any sort of sample code would be great, that way I can put my time more towards the central focus of my app rather than the command-line plumbing.

答: The previous answer seems to cover what you want to know for writing the app. As for your question about what should go in config files and what should be command line options I would recommend this. If the option is something that is likely to have the same value most of the time put it in a config. If its something that changes frequently make it an option, but remember options SHOULD be optional, try not to create a program that someone has to type in allot of required stuff to make it do it's base function.</p>


问:
not boolean value but use ||
the below code get the window size in different browsers.

```<code><!DOCTYPE html>
<html>
<body>

    <p id="demo"></p>

    <script>
    var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

    var x = document.getElementById("demo");
    x.innerHTML = "Browser inner window width: " + w + ", height: " + h + ".";
    </script>

</body>
</html>
</code>```

I want to ask window.innerWidth OR document.documentElement.clientWidth etc.. they are not Boolean values, how can I use || to declare a variable?
w/h are numbers, it's like if I do the following:

```<code>var k = aaa || bbb || 45;
</code>```

k is supposed to be a number, this is illegal, right?
How can the first piece of code work then?
Thanks~

答:
I realize that you most probably have your answer now, but I am posting an answer anyways because: a. the question is important and will surely have a sufficient amount of future viewers. b. the other answer does not explain the relationship between ToBoolean and || very well c. I would have to change and add too much if i were to edit the other answer instead, so...

In JavaScript, both the || and && logical operators will coerce their operands to boolean if they aren't booleans already, using the abstract ToBoolean operation.

You can see the effects of this ToBoolean operation using the Boolean constructor or an implicit !! conversion:

```<code>Boolean(foo);
!!foo;
</code>```

Either of the 2 lines above will convert foo to a boolean.

But how do they do it ?

It's much simple: If the variable foo is either null, undefined, NaN, 0, or "" (you could also say false, but that's a tad obvious), it will become false; in all other cases, it will become true.

Values that become false after a ToBoolean coercion (which can be performed by either of the above lines) are called "falsy values". Can you guess what values which become true after a ToBoolean operation are called ?

Here is an example of some ToBoolean operations:

const foo = "abc";

console.log(!!foo); // Prints out "true"
console.log(Boolean(foo)); // Same thing as above

const bar = "";
const baz = undefined;

console.log(Boolean(bar)); // Prints out "false"
console.log(Boolean(baz)); // Prints out "false"

/* Prints out "abc", because both "bar" and "baz" will become "false" after "||" coerces them to "boolean"*/
console.log(bar || baz || foo);```

So, in your example, if aaa is either of the "falsy" values I listed above, JavaScript will skip it and go to the next operand of ||, if that operand is not a falsy value, it will be selected by ||.

As a sidenote, || will always stop at the first "truthy" value, if there are no truthy values, it will select the last operand.

Here is a link to ToBoolean in the specs.

Title: not boolean value but use ||

Body:
the below code get the window size in different browsers.

<!DOCTYPE html>

I want to ask window.innerWidth OR document.documentElement.clientWidth etc.. they are not Boolean values, how can I use || to declare a variable?
w/h are numbers, it's like if I do the following:

var k = aaa || bbb || 45;

k is supposed to be a number, this is illegal, right?
How can the first piece of code work then?
Thanks~

Body:
I realize that you most probably have your answer now, but I am posting an answer anyways because: a. the question is important and will surely have a sufficient amount of future viewers. b. the other answer does not explain the relationship between ToBoolean and || very well c. I would have to change and add too much if i were to edit the other answer instead, so...

In JavaScript, both the || and && logical operators will coerce their operands to boolean if they aren't booleans already, using the abstract ToBoolean operation.

You can see the effects of this ToBoolean operation using the Boolean constructor or an implicit !! conversion:

Boolean(foo);
!!foo;

Either of the 2 lines above will convert foo to a boolean.

But how do they do it ?

It's much simple: If the variable foo is either null, undefined, NaN, 0, or "" (you could also say false, but that's a tad obvious), it will become false; in all other cases, it will become true.

Values that become false after a ToBoolean coercion (which can be performed by either of the above lines) are called "falsy values". Can you guess what values which become true after a ToBoolean operation are called ?

Here is an example of some ToBoolean operations:

const foo = "abc";

console.log(!!foo); // Prints out "true"
console.log(Boolean(foo)); // Same thing as above

const bar = "";
const baz = undefined;

console.log(Boolean(bar)); // Prints out "false"
console.log(Boolean(baz)); // Prints out "false"

/* Prints out "abc", because both "bar" and "baz" will become "false" after "||" coerces them to "boolean"*/
console.log(bar || baz || foo);

So, in your example, if aaa is either of the "falsy" values I listed above, JavaScript will skip it and go to the next operand of ||, if that operand is not a falsy value, it will be selected by ||.

As a sidenote, || will always stop at the first "truthy" value, if there are no truthy values, it will select the last operand.

Here is a link to ToBoolean in the specs.


问:
How can I add the Hyperledger Fabric explorer to the "Hyperledger composer" environment
As I understand, the Hyperledger composer environment runs on a Hyperledger Fabric v1.0 (or 0.8?) blockchain.

Beside the REST server to interact with the blockchain or see the transaction, participants etc. is is possible to see which transactions are in which block, like on the Hyperledger explorer?
(https://github.com/hyperledger/blockchain-explorer)

答:
Yes it is possible to see which transactions are in which block, and Yes you can use Explorer to view the transactions on a Hyperledger Fabric blockchain.

All you need is to clone the repo in the link you shared and create the relevant database by executing the mysql script mysql -u<username> -p < db/fabricexplorer.sql. Afterwards, you can start your network and note the channel name. Then, edit the file blockchain-explorer/config.json and include the channel in the channel list. Then, go to http://localhost:8080 and you will see the statistics of the channel you had indicated.

Hope this helps.


问:
What is the best way to deal with the mandatory left margin that comes with grid-column in Bourbon Neat 2.0 above?
This is the output of a grid-column mixin as mentioned on the site -

.element {

```<code>  width: calc(25% - 25px);
  float: left;
  margin-left: 20px;
</code>```

}

My problem is that I don't want gutters before and after the first and last columns.

Bootstrap uses a row class that has negative left and right margins to adjust the column padding.Is a similar approach suggested for Neat layout?

答:
You can use @grid-collpase to consume the gutters of a container.

Output:

```<code>.element {
  margin-left: -20px;
  margin-right: -20px;
  width: calc(100% + 40px);
}
</code>```

Here is a pen example https://codepen.io/matthewelsom/pen/RjOEyb

Hope that is what you are looking for.

Body:
This is the output of a grid-column mixin as mentioned on the site -

.element {

  width: calc(25% - 25px);
  float: left;
  margin-left: 20px;

}

My problem is that I don't want gutters before and after the first and last columns.

Bootstrap uses a row class that has negative left and right margins to adjust the column padding.Is a similar approach suggested for Neat layout?

Body:
You can use @grid-collpase to consume the gutters of a container.

Output:

.element {
  margin-left: -20px;
  margin-right: -20px;
  width: calc(100% + 40px);
}

Here is a pen example https://codepen.io/matthewelsom/pen/RjOEyb

Hope that is what you are looking for.


问:
Swap values of x and y
How can I change the values of x and y in this code?

When I try to do it by x=y, y=x; it changes it to the same numbers.

How can I do this?

How can I do this for 3 values like (x y z)?

```<code>#include <iostream>
using namespace std;
int main()
{
    int x=4;
    int y=6;
    cout<<x<<y;
    return 0;
}
</code>```

I tried this code before but it isn't working the way I want it.

```<code>#include <iostream>
using namespace std;
int main()
{
    int x=4;
    int y=6;
    x=y,y=x;
    cout<<x<<y;
    return 0;
}
</code>```

答:
Here is code to swap 2 variables(1 line)

```<code>#include <iostream>
using namespace std;
int main()
{
    int x = 4;
    int y = 6;
    cout << x<< y;
    swap(x,y);
    cout << x << y;
    getchar();
    return 0;
}
</code>```

Here is code to swap 3 variables(1 line)

```<code>#include <iostream>
#include <tuple>
using namespace std;
int main()
{
    int x = 4;
    int y = 6;
    int z = 8;
    cout << x<< y<<z;
    tie(x, y, z) = make_tuple(y, z, x);
    cout << x << y << z;
    getchar();
    return 0;
}
</code>```

Title: Swap values of x and y

Body:
How can I change the values of x and y in this code?

When I try to do it by x=y, y=x; it changes it to the same numbers.

How can I do this?

How can I do this for 3 values like (x y z)?

#include <iostream>
using namespace std;
int main()
{
    int x=4;
    int y=6;
    cout<<x<<y;
    return 0;
}

I tried this code before but it isn't working the way I want it.

#include <iostream>
using namespace std;
int main()
{
    int x=4;
    int y=6;
    x=y,y=x;
    cout<<x<<y;
    return 0;
}

Body:
Here is code to swap 2 variables(1 line)

#include <iostream>
using namespace std;
int main()
{
    int x = 4;
    int y = 6;
    cout << x<< y;
    swap(x,y);
    cout << x << y;
    getchar();
    return 0;
}

Here is code to swap 3 variables(1 line)

#include <iostream>
#include <tuple>
using namespace std;
int main()
{
    int x = 4;
    int y = 6;
    int z = 8;
    cout << x<< y<<z;
    tie(x, y, z) = make_tuple(y, z, x);
    cout << x << y << z;
    getchar();
    return 0;
}


问:
new never fails?
In C++, we usually see and write code like,

```<code>Sample sample=new Sample();
if ( sample == NULL )
{
     std::cout<<"Memory allocation failed" << std::endl;
}
</code>```

But in C#, I rarely see this: (at least I've never seen this)

```<code>Sample sample = new Sample();
if ( sample == null )
{
     Console.WriteLine("Memory allocation failed\n");
}
</code>```

Means, in C#, we rarely check if a new failed or not. Why is it so? Does it have something to do with "In C#, new never fails"?  Is there such a thing in C# that new never fails?

If it fails, then why such "check" is so rare in C#? I'm not talking about OutOfMemoryException, that is after all exception, not "check". I'm talking about the coding style.

答:
According to msdn

If the new operator fails to allocate memory, it throws the exception OutOfMemoryException.

http://msdn.microsoft.com/en-us/library/51y09td4%28v=vs.71%29.aspx

By the way, only old C++ compilers return 0 when they  trying to allocate memory. Modern ones throwing std::bad_alloc exception. If you wish old behavior you need to write

```<code>Sample sample=new(std::nothrow) Sample();
</code>```

Title: new never fails?

Body:
In C++, we usually see and write code like,

Sample sample=new Sample();
if ( sample == NULL )
{
     std::cout<<"Memory allocation failed" << std::endl;
}

But in C#, I rarely see this: (at least I've never seen this)

Sample sample = new Sample();
if ( sample == null )
{
     Console.WriteLine("Memory allocation failed\n");
}

Means, in C#, we rarely check if a new failed or not. Why is it so? Does it have something to do with "In C#, new never fails"?  Is there such a thing in C# that new never fails?

If it fails, then why such "check" is so rare in C#? I'm not talking about OutOfMemoryException, that is after all exception, not "check". I'm talking about the coding style.

Body:
According to msdn

If the new operator fails to allocate memory, it throws the exception OutOfMemoryException.

http://msdn.microsoft.com/en-us/library/51y09td4%28v=vs.71%29.aspx

By the way, only old C++ compilers return 0 when they  trying to allocate memory. Modern ones throwing std::bad_alloc exception. If you wish old behavior you need to write

Sample sample=new(std::nothrow) Sample();


问:
Django URL using javascript to get client end information
My problem that I am trying to resolve is that I made an Ajax-autocorrect input feature and "onclick" of a button I get the value inside that input and attempt to make the page redirect to a Django URL.

Here is the URL inside my url.py file:

```<code>    url(r'^groups/add-member/(?:/(?P<pk_group>[-\w]+))?/(?:/(?P<pk_member>[-\w]+))?/$', views.add_member, name='add-member')
</code>```

inside the HTML I have this script:

```<code><script>
function add_member(id){
  var input=document.getElementById("myText").value
  console.log(id)   //Correctly gets ID #
  console.log(input)   //Correctly gets the name (string) of member instance

  url = "{% url 'add-member' 0 zzzz %}".replace('0', id).replace('zzzz',input);

}
</script>
</code>```

And the resulting error that I get is:

```<code>Reverse for 'add-member' with arguments '(0, '')' not found. 1 pattern(s) tried:
['flexfeed/groups/add-member/(?:/(?P<pk_group>[-\\w]+))?/(?:/(?P<pk_member>[-\\w]+))?/$']
</code>```

I'm having trouble understanding my error. If anyone could suggest how to fix this issue or possibly suggest a difdferent approach to this particular problem I'd really appreciate it!

The end goal is that I want my page to redirect to my update view at the correct link!

答:
Ok, so there is a problem with the order of what's happening. When Django renders your template it processes the tags. This happens before any javascript is called.

So you are trying to call the url with 0 and zzzz as the arguments. Django tries to fetch this and because the second argument is an empty variable here it doesn't match anything.

I would fix this by calling the url with two variables that are valid, then changing them with javascript.

```<code>    url = "{% url 'add-member' 0 'change-team' %}";
    url = url.replace(0, id).replace('change-team', input);
</code>```

You might also be able to just put quotation marks around the zzzz.

Body:
My problem that I am trying to resolve is that I made an Ajax-autocorrect input feature and "onclick" of a button I get the value inside that input and attempt to make the page redirect to a Django URL.

Here is the URL inside my url.py file:

    url(r'^groups/add-member/(?:/(?P<pk_group>[-\w]+))?/(?:/(?P<pk_member>[-\w]+))?/$', views.add_member, name='add-member')

inside the HTML I have this script:

And the resulting error that I get is:

Reverse for 'add-member' with arguments '(0, '')' not found. 1 pattern(s) tried:
['flexfeed/groups/add-member/(?:/(?P<pk_group>[-\\w]+))?/(?:/(?P<pk_member>[-\\w]+))?/$']

I'm having trouble understanding my error. If anyone could suggest how to fix this issue or possibly suggest a difdferent approach to this particular problem I'd really appreciate it!

The end goal is that I want my page to redirect to my update view at the correct link!

Body:
Ok, so there is a problem with the order of what's happening. When Django renders your template it processes the tags. This happens before any javascript is called.

So you are trying to call the url with 0 and zzzz as the arguments. Django tries to fetch this and because the second argument is an empty variable here it doesn't match anything.

I would fix this by calling the url with two variables that are valid, then changing them with javascript.

    url = "{% url 'add-member' 0 'change-team' %}";
    url = url.replace(0, id).replace('change-team', input);

You might also be able to just put quotation marks around the zzzz.


问:
Show Duplicate Values
I Have a table (#tempX) below.

```<code>BoxNumber | Location
----------|----------
ABC123    |Nowra
ABC123    |Sydney
KLM222    |Melbourne
XYZ444    |Karatha
XYZ444    |Mirabooka
XYZ444    |Logan
PQR888    |Brisbane
</code>```

I need to find the duplicate and display them.

```<code>BoxNumber | Location
----------|----------
ABC123    |Nowra
ABC123    |Sydney
XYZ444    |Karatha
XYZ444    |Mirabooka
XYZ444    |Logan
</code>```

I used the query below (you can copy and paste it to your SQL server) however it doesn't give me what I'm looking for. It gives me blank table as a result.

```<code>If(OBJECT_ID('tempdb..#tempX') Is Not Null)

Drop Table #tempX

create table #tempX (box varchar(max) ,location varchar(max))

insert into #tempX (box,location)
values ('ABC123','Nowra'),('ABC123','Sydney'),('KLM222', 'Melbourne'),('XYZ444','Karatha'),('XYZ444','Mirabooka'),('XYZ444','Logan'),('PQR888','Brisbane')

--select * from #tempx

select distinct Box, Location, count(*) from #tempX
group by Box, Location
having count(*) > 1
</code>```

I'm using SQL Server 2012. Thanks all.

答:
It is not working because you are trying to find duplicate values of Box AND Location.

```<code>Select a.* from
    #tempX a join
            (
            select Box from #tempX
            group by Box
            having count(Box) > 1
            ) b on a.box = b.box
order by a.box, a.Location
</code>```

or :

```<code>select box, Location
    from #tempX
    where box in (select Box from #tempX group by Box having count(Box) > 1)
order by box, Location
</code>```

Title: Show Duplicate Values

Body:
I Have a table (#tempX) below.

BoxNumber | Location
----------|----------
ABC123    |Nowra
ABC123    |Sydney
KLM222    |Melbourne
XYZ444    |Karatha
XYZ444    |Mirabooka
XYZ444    |Logan
PQR888    |Brisbane

I need to find the duplicate and display them.

BoxNumber | Location
----------|----------
ABC123    |Nowra
ABC123    |Sydney
XYZ444    |Karatha
XYZ444    |Mirabooka
XYZ444    |Logan

I used the query below (you can copy and paste it to your SQL server) however it doesn't give me what I'm looking for. It gives me blank table as a result.

If(OBJECT_ID('tempdb..#tempX') Is Not Null)

Drop Table #tempX

create table #tempX (box varchar(max) ,location varchar(max))

insert into #tempX (box,location)
values ('ABC123','Nowra'),('ABC123','Sydney'),('KLM222', 'Melbourne'),('XYZ444','Karatha'),('XYZ444','Mirabooka'),('XYZ444','Logan'),('PQR888','Brisbane')

--select * from #tempx

select distinct Box, Location, count(*) from #tempX
group by Box, Location
having count(*) > 1

I'm using SQL Server 2012. Thanks all.

Body:
It is not working because you are trying to find duplicate values of Box AND Location.

Select a.* from
    #tempX a join
            (
            select Box from #tempX
            group by Box
            having count(Box) > 1
            ) b on a.box = b.box
order by a.box, a.Location

or :

select box, Location
    from #tempX
    where box in (select Box from #tempX group by Box having count(Box) > 1)
order by box, Location


问:
Issue with workbox 2.1.0 precaching
I am using workbox 2.1.0 for generating service worker and need to precache some files from the assets directory (say index.html and clear.png) of the server and one file from a CDN (say https://akamai.com/dummy/path/app.js).
I am using gulp for building. This is how the code goes

```<code>gulp.task('sw', () => {
      return wbBuild.generateSW({
          globDirectory: '.',
          swDest: 'sw_gulp_generated.js',
          staticFileGlobs: [
              'index.html',
              'clear.png'
              ],
          verbose: true,
  })
      .then(() => {
        console.log('Service worker generated.');
      })
      .catch((err) => {
        console.log('[ERROR] This happened: ' + err);
      });
    });
</code>```

So, this works fine and the generated service worker has both the files in the precache list, here it goes:

```<code>const fileManifest = [
  {
    "url": "index.html",
    "revision": "b6eb7cd7599ed6584a715cdfc75a81c0"
  },
  {
    "url": "clear.png",
    "revision": "e17de36d2c2ddf7b068892fa4678cd31"
  },

];
const workboxSW = new self.WorkboxSW();
workboxSW.precache(fileManifest);
//more code follows ...
</code>```

I tested and it works perfectly

Now, the question is: How do I add the third asset (https://akamai.com/dummy/path/app.js) in the precache list. I tried putting it in staticFileGlobs but it errors out saying:

```<code>One of the glob patterns doesn't match any files
</code>```

Obviously because it tries to find the file https://akamai.com/dummy/path/app.js inside the globDirectory and can't find it.

So, basically, how can I have the CDN URL injected in the precache list of the generated service worker while using gulp(or any build tool)?

答:
It doesn't look like generateSW accepts custom precache rules. You can pass a runtimeCaching option though. It'll only cache the third-party files if they are requested by the client. Since it's a third-party request if the request results in an error response the error response will be cached and not updated.

```<code>wbBuild.generateSW({
  globDirectory: '.',
  swDest: 'sw_gulp_generated.js',
  staticFileGlobs: [
    'index.html',
    'clear.png'
  ],
  verbose: true,
  runtimeCaching: [{
    urlPattern: 'https://exapmle.com/file.min.js',
    handler: 'staleWhileRevalidate',
    options: {
      cacheableResponse: {
        statuses: [0],
      },
    },
  }]
})
</code>```

Title: Issue with workbox 2.1.0 precaching

Body:
I am using workbox 2.1.0 for generating service worker and need to precache some files from the assets directory (say index.html and clear.png) of the server and one file from a CDN (say https://akamai.com/dummy/path/app.js).
I am using gulp for building. This is how the code goes

gulp.task('sw', () => {
      return wbBuild.generateSW({
          globDirectory: '.',
          swDest: 'sw_gulp_generated.js',
          staticFileGlobs: [
              'index.html',
              'clear.png'
              ],
          verbose: true,
  })
      .then(() => {
        console.log('Service worker generated.');
      })
      .catch((err) => {
        console.log('[ERROR] This happened: ' + err);
      });
    });

So, this works fine and the generated service worker has both the files in the precache list, here it goes:

const fileManifest = [
  {
    "url": "index.html",
    "revision": "b6eb7cd7599ed6584a715cdfc75a81c0"
  },
  {
    "url": "clear.png",
    "revision": "e17de36d2c2ddf7b068892fa4678cd31"
  },

];
const workboxSW = new self.WorkboxSW();
workboxSW.precache(fileManifest);
//more code follows ...

I tested and it works perfectly

Now, the question is: How do I add the third asset (https://akamai.com/dummy/path/app.js) in the precache list. I tried putting it in staticFileGlobs but it errors out saying:

One of the glob patterns doesn't match any files

Obviously because it tries to find the file https://akamai.com/dummy/path/app.js inside the globDirectory and can't find it.

So, basically, how can I have the CDN URL injected in the precache list of the generated service worker while using gulp(or any build tool)?

Body:
It doesn't look like generateSW accepts custom precache rules. You can pass a runtimeCaching option though. It'll only cache the third-party files if they are requested by the client. Since it's a third-party request if the request results in an error response the error response will be cached and not updated.

wbBuild.generateSW({
  globDirectory: '.',
  swDest: 'sw_gulp_generated.js',
  staticFileGlobs: [
    'index.html',
    'clear.png'
  ],
  verbose: true,
  runtimeCaching: [{
    urlPattern: 'https://exapmle.com/file.min.js',
    handler: 'staleWhileRevalidate',
    options: {
      cacheableResponse: {
        statuses: [0],
      },
    },
  }]
})


问:
Passing cookies in request spec
I'm trying to pass a cookie when doing a GET request, using rspec 2 and rails 3.

I've tried the following so far.

```<code>get "/", {}, {"Cookie" => "uuid=10"} # cookies[:uuid] is nil
request.cookies[:uuid] = 10 # request is nil
@request.env["Cookie"] = "uuid=10" # @request is nil
helper.request.cookies[:uuid] # helper is not defined
cookies[:uuid] = 10 # cookies[:uuid] is nil
controller.cookies[:uuid] = 10 # cookies is nil
</code>```

Is it possible?

答:
In spec/requests/some_spec.rb you can use Rack::Test::Methods to set and read cookies.

```<code>describe 'Something' do

  include Rack::Test::Methods

  it 'can set cookies' do
    set_cookie "foo=red"
    post '/some/endpoint', params, headers
    expect(last_request.cookies[:foo]).to eq('red')
  end

end
</code>```

Documentation:

http://www.rubydoc.info/github/brynary/rack-test/Rack/MockSession#set_cookie-instance_method

Title: Passing cookies in request spec

Body:
I'm trying to pass a cookie when doing a GET request, using rspec 2 and rails 3.

I've tried the following so far.

get "/", {}, {"Cookie" => "uuid=10"} # cookies[:uuid] is nil
request.cookies[:uuid] = 10 # request is nil
@request.env["Cookie"] = "uuid=10" # @request is nil
helper.request.cookies[:uuid] # helper is not defined
cookies[:uuid] = 10 # cookies[:uuid] is nil
controller.cookies[:uuid] = 10 # cookies is nil

Is it possible?

Body:
In spec/requests/some_spec.rb you can use Rack::Test::Methods to set and read cookies.

describe 'Something' do

  include Rack::Test::Methods

  it 'can set cookies' do
    set_cookie "foo=red"
    post '/some/endpoint', params, headers
    expect(last_request.cookies[:foo]).to eq('red')
  end

end

Documentation:

http://www.rubydoc.info/github/brynary/rack-test/Rack/MockSession#set_cookie-instance_method


问:
Get data from another model cakephp 3.5
I have table questions which contains id, questions and marks. Then, I have table quizzes which contains id and quiz_name. I created bridge table named question_quizzes which contains id from quiz table and id from question table. How can I display all of the data (id, questions, marks) in questions table into add form of question_quizzes?

EDIT:

This is existingQuestion function inside questionQuizzes controller. In existingQuestion function, I want to display all of the questions table

```<code> class QuestionQuizzesController extends AppController
   public function existingQuestion()
  {
    $query = $questionQuizzes->find('all')->contain('Questions');
    foreach ($query as $questionQuizzes) {
        echo $questionQuiz->question->id;
    }
}
</code>```

This is questionQuizzesTable

```<code>class QuestionQuizzesTable extends Table
{

/**
 * Initialize method
 *
 * @param array $config The configuration for the Table.
 * @return void
 */

 var $name = 'QuestionQuizzes';

public function initialize(array $config)
{
    parent::initialize($config);

    $this->setTable('question_quizzes');

    $this->belongsTo('Quizzes', [
        'foreignKey' => 'quiz_id',
        'joinType' => 'INNER'
    ]);
    $this->belongsTo('Questions', [
        'foreignKey' => 'question_id',
        'joinType' => 'INNER'
    ]);
}

/**
 * Returns a rules checker object that will be used for validating
 * application integrity.
 *
 * @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
 * @return \Cake\ORM\RulesChecker
 */
public function buildRules(RulesChecker $rules)
{
    $rules->add($rules->existsIn(['quiz_id'], 'Quizzes'));
    $rules->add($rules->existsIn(['question_id'], 'Questions'));

    return $rules;
}
}
</code>```

I have edited my coding but still there is an error "Call to a member function find() on null". Can anybody help me?? I'm stucked

答:
When you write $query = $questionQuizzes->find(), you have not declared $questionQuizzes anywhere. Variables don't just spring fully-formed into being. Hence, it's null, and you are trying to call a function on it. This should all have been fairly self-evident from the error message you got, surely it directed you right to the line in question? (There are snippets of code in the link @urfusion provided that just reference $articles, but those are shown without context and assume that you have created the variable in advance.)

The fix would be to use $this->questionQuizzes->find(). The questionQuizzes member of $this should have been initialized by Cake thanks to what you're doing in your initialize function. The relevant part of the manual would be the section on the Query Builder.

Note that Cake conventions would have you name your table questions_quizzes, not question_quizzes; both parts are plural. Or quizzes_questions would work too, and makes more sense to me personally (it tracks the quizzes' questions, after all). There's nothing wrong with the name you've chosen, but examples might fit themselves into your code more easily if you follow the conventions more completely.

Title: Get data from another model cakephp 3.5

Body:
I have table questions which contains id, questions and marks. Then, I have table quizzes which contains id and quiz_name. I created bridge table named question_quizzes which contains id from quiz table and id from question table. How can I display all of the data (id, questions, marks) in questions table into add form of question_quizzes?

EDIT:

This is existingQuestion function inside questionQuizzes controller. In existingQuestion function, I want to display all of the questions table

 class QuestionQuizzesController extends AppController
   public function existingQuestion()
  {
    $query = $questionQuizzes->find('all')->contain('Questions');
    foreach ($query as $questionQuizzes) {
        echo $questionQuiz->question->id;
    }
}

This is questionQuizzesTable

class QuestionQuizzesTable extends Table
{

/**
 * Initialize method
 *
 * @param array $config The configuration for the Table.
 * @return void
 */

 var $name = 'QuestionQuizzes';

public function initialize(array $config)
{
    parent::initialize($config);

    $this->setTable('question_quizzes');

    $this->belongsTo('Quizzes', [
        'foreignKey' => 'quiz_id',
        'joinType' => 'INNER'
    ]);
    $this->belongsTo('Questions', [
        'foreignKey' => 'question_id',
        'joinType' => 'INNER'
    ]);
}

/**
 * Returns a rules checker object that will be used for validating
 * application integrity.
 *
 * @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
 * @return \Cake\ORM\RulesChecker
 */
public function buildRules(RulesChecker $rules)
{
    $rules->add($rules->existsIn(['quiz_id'], 'Quizzes'));
    $rules->add($rules->existsIn(['question_id'], 'Questions'));

    return $rules;
}
}

I have edited my coding but still there is an error "Call to a member function find() on null". Can anybody help me?? I'm stucked


问:
Can't find GoogleService-info.plist in Xcode 9.0?
I just update to Xcode 9 and after installing Firebase libraries the project can not find the GoogleService-info.plist file, even if it is there!! Any suggestions?</p>

答: I had the same issue. Instead of dragging the Google file into your Xcode project, right click the folder (inside your Xcode project) that you would like to save the Google file and click "Add Files to '[App Name]'..." and add GoogleService-info.plist that way. Also make sure the file is called "GoogleService-info.plist".</p>