问:
Endless Date List Generator
I have a column from a table with a lot of different dates. I know how to generate a list of endless amount of weeks from any date BUT only one date that has to be hard coded in.

For example, if I throw in the date of '1/1/2000' and I want all the weeks after this date, then I get a column of every week after this date (see below):

Input field:

```<code>1/1/2000
</code>```

Output column:

```<code>1/1/2000
1/8/2000
1/15/2000
1/22/2000
1/29/2000
</code>```

...and so on

However, that is just one date. What I'm asking for is doing the same thing as above but showing the next X amount of weeks (in this example 5 weeks) for all the dates (see below):

Input column:

```<code>1/1/2000
1/1/2001
1/1/2002
1/1/2003
1/1/2004
</code>```

Output column:

```<code>1/1/2000
1/8/2000
1/15/2000
1/22/2000
1/29/2000
1/1/2001
1/8/2001
1/15/2001
1/22/2001
1/29/2001
1/1/2002
1/8/2002
1/15/2002
1/22/2002
1/29/2002
1/1/2003
1/8/2003
1/15/2003
1/22/2003
1/29/2003
1/1/2004
1/8/2004
1/15/2004
1/22/2004
1/29/2004
</code>```

The input column for this example is only 5 dates but in reality I have columns with hundreds of dates and it will not be just 5 weeks into the future, but more like 5 years into the future

Using the explanation above, how do you generate this recurring list for all dates in a column? Not just 5 weeks for the first date in the column (which I can do), but the next 5 weeks for each date in the column.

答:
Ok, folks. The OP said the following in a comment on my previous post...

However, as much as I would like to use this solution, sadly I have
  only read-only access to our server, so I am unable to create temp
  tables or custom functions, so the rCTE option works best for us.

No... the rCTE does NOT work the best for you even in this situation.

First of all, the use of the Temp Tables were just to build test data because I don't have access to the original tables posted by the OP.  They're just for testing... they're NOT a part of the solution.  Creating test data in this fashion is a VERY common practice among respondents and you simply need to recognize that fact and replace the name of the Temp Tables with the actual name(s) of your real tables.

The OP also wrote the following...

However, we have been getting performance issues on our servers, so
  I'm glad you gave me this better alternate solution that hopefully we
  can use one day when we really need to optimize.

My take on this is... why wait?  Start now.  Submit the code for the fnTally function to the DBA with a justification as to why it should be a part of every database or at least included in an accessible utility database.  If the DBA is really on the ball, he may already have something like it (hopefully NOT based on an rCTE or While Loop) available and you just need to ask about it.

If that's not possible, then this problem can still be done to the same effect (high performance, short code, correct answers) but, since you can't do the "think OUTSIDE the box" thing,  you do have to take some time to "think INSIDE the box".

With that being said and with the understanding that you're going to need to change the name of the Temp Table to a real table (I used the Temp Table from my previous reply to test it with), the following slightly longer code uses similar cCTE (Cascading CTE) code to replace the fnTally function you can't make.

```<code>WITH
     H1(N) AS (SELECT 1 FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1))H0(N)) --16^1 or 16 rows
,    H8(N) AS (SELECT 1 FROM H1 a, H1 b, H1 c, H1 d, H1 e, H1 f, H1 g, H1 h) --16^8 or 4,294,967,296 rows
, Tally(N) AS (SELECT N = ROW_NUMBER() OVER (ORDER BY N) - 1 FROM H8)
    SELECT  SomeDate
           ,Week#             = wk.N+1
           ,WeekStartDate     = DATEADD(wk,wk.N  ,tt.SomeDate)
           ,NextWeekStartDate = DATEADD(wk,wk.N+1,tt.SomeDate)
      FROM #TestTable tt
     CROSS APPLY (SELECT TOP (tt.ContractWeeks+1) N FROM Tally) wk
;
</code>```

The bottom line is that it's pretty easy to avoid the horror of an rCTE that produces and incremental count even for something like this.  You just have to teach yourself how to think "INSIDE" the box you're limited to. :D

Title: Endless Date List Generator

Body:
I have a column from a table with a lot of different dates. I know how to generate a list of endless amount of weeks from any date BUT only one date that has to be hard coded in.

For example, if I throw in the date of '1/1/2000' and I want all the weeks after this date, then I get a column of every week after this date (see below):

Input field:

1/1/2000

Output column:

1/1/2000
1/8/2000
1/15/2000
1/22/2000
1/29/2000

...and so on

However, that is just one date. What I'm asking for is doing the same thing as above but showing the next X amount of weeks (in this example 5 weeks) for all the dates (see below):

Input column:

1/1/2000
1/1/2001
1/1/2002
1/1/2003
1/1/2004

Output column:

1/1/2000
1/8/2000
1/15/2000
1/22/2000
1/29/2000
1/1/2001
1/8/2001
1/15/2001
1/22/2001
1/29/2001
1/1/2002
1/8/2002
1/15/2002
1/22/2002
1/29/2002
1/1/2003
1/8/2003
1/15/2003
1/22/2003
1/29/2003
1/1/2004
1/8/2004
1/15/2004
1/22/2004
1/29/2004

The input column for this example is only 5 dates but in reality I have columns with hundreds of dates and it will not be just 5 weeks into the future, but more like 5 years into the future

Using the explanation above, how do you generate this recurring list for all dates in a column? Not just 5 weeks for the first date in the column (which I can do), but the next 5 weeks for each date in the column.

Body:
Ok, folks. The OP said the following in a comment on my previous post...

However, as much as I would like to use this solution, sadly I have
  only read-only access to our server, so I am unable to create temp
  tables or custom functions, so the rCTE option works best for us.

No... the rCTE does NOT work the best for you even in this situation.

First of all, the use of the Temp Tables were just to build test data because I don't have access to the original tables posted by the OP.  They're just for testing... they're NOT a part of the solution.  Creating test data in this fashion is a VERY common practice among respondents and you simply need to recognize that fact and replace the name of the Temp Tables with the actual name(s) of your real tables.

The OP also wrote the following...

However, we have been getting performance issues on our servers, so
  I'm glad you gave me this better alternate solution that hopefully we
  can use one day when we really need to optimize.

My take on this is... why wait?  Start now.  Submit the code for the fnTally function to the DBA with a justification as to why it should be a part of every database or at least included in an accessible utility database.  If the DBA is really on the ball, he may already have something like it (hopefully NOT based on an rCTE or While Loop) available and you just need to ask about it.

If that's not possible, then this problem can still be done to the same effect (high performance, short code, correct answers) but, since you can't do the "think OUTSIDE the box" thing,  you do have to take some time to "think INSIDE the box".

With that being said and with the understanding that you're going to need to change the name of the Temp Table to a real table (I used the Temp Table from my previous reply to test it with), the following slightly longer code uses similar cCTE (Cascading CTE) code to replace the fnTally function you can't make.

WITH
     H1(N) AS (SELECT 1 FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1),(1))H0(N)) --16^1 or 16 rows
,    H8(N) AS (SELECT 1 FROM H1 a, H1 b, H1 c, H1 d, H1 e, H1 f, H1 g, H1 h) --16^8 or 4,294,967,296 rows
, Tally(N) AS (SELECT N = ROW_NUMBER() OVER (ORDER BY N) - 1 FROM H8)
    SELECT  SomeDate
           ,Week#             = wk.N+1
           ,WeekStartDate     = DATEADD(wk,wk.N  ,tt.SomeDate)
           ,NextWeekStartDate = DATEADD(wk,wk.N+1,tt.SomeDate)
      FROM #TestTable tt
     CROSS APPLY (SELECT TOP (tt.ContractWeeks+1) N FROM Tally) wk
;

The bottom line is that it's pretty easy to avoid the horror of an rCTE that produces and incremental count even for something like this.  You just have to teach yourself how to think "INSIDE" the box you're limited to. :D


来源: stackexchange

问:
Why is looking for an item in a hash map faster than looking for an item in an array?
You might have come across someplace where it is mentioned that it is faster to find elements in hashmap/dictionary/table than list/array. My question is WHY?

(inference so far I made: Why should it be faster, as far I see, in both data structure, it has to travel throughout till it reaches the required element)

答:
Let’s reason by analogy. Suppose you want to find a specific shirt to put on in the morning. I assume that, in doing so, you don’t have to look at literally every item of clothing you have. Rather, you probably do something like checking a specific drawer in your dresser or a specific section of your closet and only look there. After all, you’re not (I hope) going to find your shirt in your sock drawer.

Hash tables are faster to search than lists because they employ a similar strategy - they organize data according to the principle that every item has a place it “should” be, then search for the item by just looking in that place. Contrast this with a list, where items are organized based on the order in which they were added and where there isn’t a a particular pattern as to why each item is where it is.

More specifically: one common way to implement a hash table is with a strategy called chained hashing. The idea goes something like this: we maintain an array of buckets. We then come up with a rule that assigns each object a bucket number. When we add something to the table, we determine which bucket number it should go to, then jump to that bucket and then put the item there. To search for an item, we determine the bucket number, then jump there and only look at the items in that bucket. Assuming that the strategy we use to distribute items ends up distributing the items more or less evenly across the buckets, this means that we won’t have to look at most of the items in the hash table when doing a search, which is why the hash table tends to be much faster to search than a list.

For more details on this, check out these lecture slides on hash tables, which fills in more of the details about how this is done.

Hope this helps!

ContentLicense: CC BY-SA 4.0


问:
Log wrapper in makefile?
I m trying to write a simple log wrapper in makefile as shown below

```<code>define do_log
ifeq ($(1),1)
  $(info ---------- $(shell date +%H:%M:%S) $(2))
else ifeq ($(1),2)
  $(warning ^^^^^^^^^^ $(shell date +%H:%M:%S) $(2))
else ifeq ($(1),3)
  $(error !!!!!!!!!! $(shell date +%H:%M:%S) $(2))
endif
endef
</code>```

But every-time i call this function

```<code>$(call do_log,1,"hello")
</code>```

All statements are getting executed

```<code>$ make
---------- 18:22:45 "hello"
Makefile:16: ^^^^^^^^^^ 18:22:45 "hello"
Makefile:16: *** !!!!!!!!!! 18:22:45 "hello".  Stop.
</code>```

Can someone please help me understand, on what am i doing wrong ?

答:
ifeq etc. are more like preprocessor statements.  They are only meaningful to make's makefile parser.  They have no special meaning or significance to variable expansion etc., just like how you can't use C/C++ preprocessor statements at runtime.

The behavior you see is because call first expands the variable, and when that happens only variables are considered.  This means that call sees something like this:

```<code><text> $(1) <text>
  $(info ---------- $(shell date +%H:%M:%S) $(2))
<text> $(1) <text>
  $(warning ^^^^^^^^^^ $(shell date +%H:%M:%S) $(2))
<text> $(1) <text>
  $(error !!!!!!!!!! $(shell date +%H:%M:%S) $(2))
<text>
</code>```

and all those variable/function references are expanded.  In general you cannot use ifeq etc. in a define variable unless you expect to use it with eval (which parses its string using the makefile parser).

Since you've not really shown us how you want to use this it's hard to suggest The best alternative, but to literally translate what you're doing here you could use:

```<code>define do_log
$(if $(filter-out 1,$(1)),,$(info    ---------- $(shell date +%H:%M:%S) $(2)))
$(if $(filter-out 2,$(1)),,$(warning ^^^^^^^^^^ $(shell date +%H:%M:%S) $(2)))
$(if $(filter-out 3,$(1)),,$(error   !!!!!!!!!! $(shell date +%H:%M:%S) $(2)))
endef
</code>```

Title: Log wrapper in makefile?

Body:
I m trying to write a simple log wrapper in makefile as shown below

define do_log
ifeq ($(1),1)
  $(info ---------- $(shell date +%H:%M:%S) $(2))
else ifeq ($(1),2)
  $(warning ^^^^^^^^^^ $(shell date +%H:%M:%S) $(2))
else ifeq ($(1),3)
  $(error !!!!!!!!!! $(shell date +%H:%M:%S) $(2))
endif
endef

But every-time i call this function

$(call do_log,1,"hello")

All statements are getting executed

$ make
---------- 18:22:45 "hello"
Makefile:16: ^^^^^^^^^^ 18:22:45 "hello"
Makefile:16: *** !!!!!!!!!! 18:22:45 "hello".  Stop.

Can someone please help me understand, on what am i doing wrong ?

Body:
ifeq etc. are more like preprocessor statements.  They are only meaningful to make's makefile parser.  They have no special meaning or significance to variable expansion etc., just like how you can't use C/C++ preprocessor statements at runtime.

The behavior you see is because call first expands the variable, and when that happens only variables are considered.  This means that call sees something like this:

<text> $(1) <text>
  $(info ---------- $(shell date +%H:%M:%S) $(2))
<text> $(1) <text>
  $(warning ^^^^^^^^^^ $(shell date +%H:%M:%S) $(2))
<text> $(1) <text>
  $(error !!!!!!!!!! $(shell date +%H:%M:%S) $(2))
<text>

and all those variable/function references are expanded.  In general you cannot use ifeq etc. in a define variable unless you expect to use it with eval (which parses its string using the makefile parser).

Since you've not really shown us how you want to use this it's hard to suggest The best alternative, but to literally translate what you're doing here you could use:

define do_log
$(if $(filter-out 1,$(1)),,$(info    ---------- $(shell date +%H:%M:%S) $(2)))
$(if $(filter-out 2,$(1)),,$(warning ^^^^^^^^^^ $(shell date +%H:%M:%S) $(2)))
$(if $(filter-out 3,$(1)),,$(error   !!!!!!!!!! $(shell date +%H:%M:%S) $(2)))
endef


问:
Evaluate model result for multitask learning with keras
I designed a CNN for a multitask classification in keras, where I have one input and two different class of classes in output.

I compiled the model in this way:

```<code> model.compile(loss='categorical_crossentropy',
               optimizer=tf.keras.optimizers.Adam(lr=0.00002, decay=1e-6),
               metrics=['accuracy'])
</code>```

I wanted to know what is the meaning of the results obtained with this instruction:

```<code>preds = model.evaluate(x=X_test, y=[Y1_test, Y2_test])
</code>```

I get 5 elements and i suppose the first and second are the losses for first and second class, the third seems like the difference between the two losses and the last two are the accuracies maybe. Is it correct? I did not find the explanation of the output for a multitask classification

答:
In this dummy example, I provide you a multi-output model and try to make evaluation

```<code>X = np.random.uniform(0,1, (1000,10))
y1 = np.random.randint(0,2, 1000)
y2 = np.random.randint(0,2, 1000)

inp = Input((10))
x = Dense(32, activation='relu')(inp)
out1 = Dense(2, activation='softmax')(x)
out2 = Dense(2, activation='softmax')(x)
m = Model(inp, [out1,out2])
m.compile(loss='sparse_categorical_crossentropy',
          optimizer='adam',
          metrics=['accuracy'])

m.fit(X, [y1,y2], epochs=10, verbose=2)

m.evaluate(X, [y1,y2])
</code>```

the evaluate method return 5 numbers:

total loss (given by the sum of two output loss)

output1 loss

output2 loss

output1 accuracy

output2 accuracy

Body:
I designed a CNN for a multitask classification in keras, where I have one input and two different class of classes in output.

I compiled the model in this way:

 model.compile(loss='categorical_crossentropy',
               optimizer=tf.keras.optimizers.Adam(lr=0.00002, decay=1e-6),
               metrics=['accuracy'])

I wanted to know what is the meaning of the results obtained with this instruction:

preds = model.evaluate(x=X_test, y=[Y1_test, Y2_test])

I get 5 elements and i suppose the first and second are the losses for first and second class, the third seems like the difference between the two losses and the last two are the accuracies maybe. Is it correct? I did not find the explanation of the output for a multitask classification

Body:
In this dummy example, I provide you a multi-output model and try to make evaluation

X = np.random.uniform(0,1, (1000,10))
y1 = np.random.randint(0,2, 1000)
y2 = np.random.randint(0,2, 1000)

inp = Input((10))
x = Dense(32, activation='relu')(inp)
out1 = Dense(2, activation='softmax')(x)
out2 = Dense(2, activation='softmax')(x)
m = Model(inp, [out1,out2])
m.compile(loss='sparse_categorical_crossentropy',
          optimizer='adam',
          metrics=['accuracy'])

m.fit(X, [y1,y2], epochs=10, verbose=2)

m.evaluate(X, [y1,y2])

the evaluate method return 5 numbers:

total loss (given by the sum of two output loss)

output1 loss

output2 loss

output1 accuracy

output2 accuracy


问:
How to copy an image in JTextPane java?
I want to know how to copy an image and text in JTextPane.
When I use this code, it copies just text but I want to copy text and image. How can be done this?</p>

```<code>import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;

/**
  *
     * @author admin
                     */
public class Main extends JFrame implements KeyListener, ActionListener{
public static JTextPane textPane;
/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here
                JFrame Frame = new Main();
                Frame.setVisible(true);
                Frame.setSize(400, 400);

}
public Main()
{
    JMenuBar mb = new JMenuBar();
    setJMenuBar(mb);

    JMenu menu = new JMenu("File");
    JMenuItem mi = new JMenuItem("select all");
    mi.addActionListener(this);
    menu.setMnemonic(KeyEvent.VK_F);
    menu.add(mi);
    mi = new JMenuItem("copy");
    mi.addActionListener(this);
    menu.add(mi);
    mi = new JMenuItem("Exit");
    mi.addActionListener(this);
    menu.add(mi);
     mi = new JMenuItem("insert image");
    mi.addActionListener(this);
    menu.add(mi);
    mb.add(menu);
    textPane = new JTextPane();

    JScrollPane scrollPane = new JScrollPane(textPane);
    getContentPane().add(scrollPane);

}

public void keyTyped(KeyEvent e) {
    throw new UnsupportedOperationException("Not supported yet.");
}

public void keyPressed(KeyEvent e) {
    throw new UnsupportedOperationException("Not supported yet.");
}

public void keyReleased(KeyEvent e) {
    throw new UnsupportedOperationException("Not supported yet.");
}

public void actionPerformed(ActionEvent e) {
    String cmd=e.getActionCommand();
    if ("Exit".equals(cmd)) {
        System.exit(0);
    } else if ("select all".equals(cmd)) {
        textPane.selectAll();
    }
    else if ("copy".equals(cmd)) {
      textPane.copy();

    }
    else if("insert image".equals(cmd))
    {
        try {
            JFileChooser file = new JFileChooser();
            file.showOpenDialog(null);
            File selFile = file.getSelectedFile();
            Image img = ImageIO.read(selFile);
            textPane.insertIcon(new ImageIcon(img));
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
 }

}
</code>```

答:
I'm afraid there is no simple way to do this.
All the default EditorKits (StyledEditorKit, HTMLEditorKit, RTFEditorKit) don't support images copying.

The closest one is HTMLEditorKit but it will generate HTML with links to images.

You can implement your own Reader/Writer. See http://java-sl.com/editor_kit_tutorial.html chapter about reader and writer.

ContentLicense: CC BY-SA 3.0

Title: How to copy an image in JTextPane java?

Body:
I want to know how to copy an image and text in JTextPane.
When I use this code, it copies just text but I want to copy text and image. How can be done this?

import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;

/**
  *
     * @author admin
                     */
public class Main extends JFrame implements KeyListener, ActionListener{
public static JTextPane textPane;
/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here
                JFrame Frame = new Main();
                Frame.setVisible(true);
                Frame.setSize(400, 400);

}
public Main()
{
    JMenuBar mb = new JMenuBar();
    setJMenuBar(mb);

    JMenu menu = new JMenu("File");
    JMenuItem mi = new JMenuItem("select all");
    mi.addActionListener(this);
    menu.setMnemonic(KeyEvent.VK_F);
    menu.add(mi);
    mi = new JMenuItem("copy");
    mi.addActionListener(this);
    menu.add(mi);
    mi = new JMenuItem("Exit");
    mi.addActionListener(this);
    menu.add(mi);
     mi = new JMenuItem("insert image");
    mi.addActionListener(this);
    menu.add(mi);
    mb.add(menu);
    textPane = new JTextPane();

    JScrollPane scrollPane = new JScrollPane(textPane);
    getContentPane().add(scrollPane);

}

public void keyTyped(KeyEvent e) {
    throw new UnsupportedOperationException("Not supported yet.");
}

public void keyPressed(KeyEvent e) {
    throw new UnsupportedOperationException("Not supported yet.");
}

public void keyReleased(KeyEvent e) {
    throw new UnsupportedOperationException("Not supported yet.");
}

public void actionPerformed(ActionEvent e) {
    String cmd=e.getActionCommand();
    if ("Exit".equals(cmd)) {
        System.exit(0);
    } else if ("select all".equals(cmd)) {
        textPane.selectAll();
    }
    else if ("copy".equals(cmd)) {
      textPane.copy();

    }
    else if("insert image".equals(cmd))
    {
        try {
            JFileChooser file = new JFileChooser();
            file.showOpenDialog(null);
            File selFile = file.getSelectedFile();
            Image img = ImageIO.read(selFile);
            textPane.insertIcon(new ImageIcon(img));
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
 }

}


问:
Mandelbrot Set drawing and ZeroDivisionError in complex numbers
I am making a code that draws versions of the Mandelbrot Set. When it runs, it takes in two inputs, a and b, and converts it to a complex number (e.g. complex(a,b).) Then it draws a Mandelbrot set with z to the power of the complex number, plus c, unlike the normal version which is z**2+c. But some inputs for the complex number, like 5 and 6, sometimes give an error, ZeroDivisionError: complex division by zero, or sometimes, it gives no output whatsoever. Sometimes, when I put in 1 and 1, it works, and puts an output like this:

This is my first question on stackoverflow, so I'm not sure if that picture worked, but anyway, it looks nothing like the normal Mandelbrot set. What is happening? Also, this is my code:

```<code>import turtle
s=turtle.Screen()
t=turtle.Turtle()
a=int(input())
b=int(input())
h=complex(a,b)
t.pu()
t.goto(-200, 200)
turtle.tracer(0,0)
t.speed(0)
for y in range(200,-200,-1):
  turtle.update()
  for x in range(-250,200):
    t.goto(x,y)
    r=float(float(x)/170)
    i=float(float(y)/170)
    c=complex(float(r),float(i))
    z=complex(0,1)
    for exptest in range(50):
      z=(z**h)+c
      if abs(z)>2:
        if exptest>0:
          t.color('black')
          if exptest>1:
            t.color('yellow')
            if exptest>2:
              t.color('green')
              if exptest>3:
                t.color('red')
                if exptest>5:
                  t.color('orange')
                  if exptest>10:
                    t.color('purple')
                    if exptest>20:
                      t.color('blue')
                      if exptest>30:
                        t.color('light blue')
        else:
          t.color('light green')
        t.dot(1)
        break
</code>```

答: exponentiation is not well-defined for complex numbers. You can define a ** b ax exp(log(a) * b), but log(a) is only defined up to 2pi i, so you have an infinite number of possibilities. for integer powers, you can define z**k as z * z * ... *z k times, but this is almost certainly not what python does for k defined as complex as you do above.

Body:
I am making a code that draws versions of the Mandelbrot Set. When it runs, it takes in two inputs, a and b, and converts it to a complex number (e.g. complex(a,b).) Then it draws a Mandelbrot set with z to the power of the complex number, plus c, unlike the normal version which is z**2+c. But some inputs for the complex number, like 5 and 6, sometimes give an error, ZeroDivisionError: complex division by zero, or sometimes, it gives no output whatsoever. Sometimes, when I put in 1 and 1, it works, and puts an output like this:

This is my first question on stackoverflow, so I'm not sure if that picture worked, but anyway, it looks nothing like the normal Mandelbrot set. What is happening? Also, this is my code:

import turtle
s=turtle.Screen()
t=turtle.Turtle()
a=int(input())
b=int(input())
h=complex(a,b)
t.pu()
t.goto(-200, 200)
turtle.tracer(0,0)
t.speed(0)
for y in range(200,-200,-1):
  turtle.update()
  for x in range(-250,200):
    t.goto(x,y)
    r=float(float(x)/170)
    i=float(float(y)/170)
    c=complex(float(r),float(i))
    z=complex(0,1)
    for exptest in range(50):
      z=(z**h)+c
      if abs(z)>2:
        if exptest>0:
          t.color('black')
          if exptest>1:
            t.color('yellow')
            if exptest>2:
              t.color('green')
              if exptest>3:
                t.color('red')
                if exptest>5:
                  t.color('orange')
                  if exptest>10:
                    t.color('purple')
                    if exptest>20:
                      t.color('blue')
                      if exptest>30:
                        t.color('light blue')
        else:
          t.color('light green')
        t.dot(1)
        break


问:
Display a different logo on mobile and desktop?
I'm looking to change the logo on my header on a mobile. This is the code from the current header that shows up on both the desktop and the mobile (on desktop it's the link back to the home screen). Is there any easy way of changing it on just the mobile version?

HTML:

```<code><div id="mainlogo">
<a class="main logo" href="http://sheisbiddy.com/home/" title="Main Logo" alt="main logo">
<img src="http://sheisbiddy.com/wp-content/uploads/2016/01/SHEISBIDDY-main-logo-smaller-6.png" border="0" alt="" />
</a>
</code>```

CSS:

```<code>#mainlogo {text-align:center;}
</code>```

Appreciate it guys!

答:
if you are using bootstrap, there is a simple and fast method I have used,
use 2  tag, hide 1st image in mobile by using class "d-none d-sm-block"
and hide 2nd image in desktop by using class "d-block d-sm-none"
check the code below:

```<code><div>
<img  src="img5.jpg"  class="d-none d-sm-block"  />

<img src="img5-mobile.jpg"  class=" d-block d-sm-none" />
</div>
</code>```

Body:
I'm looking to change the logo on my header on a mobile. This is the code from the current header that shows up on both the desktop and the mobile (on desktop it's the link back to the home screen). Is there any easy way of changing it on just the mobile version?

HTML:

CSS:

#mainlogo {text-align:center;}

Appreciate it guys!

Body:
if you are using bootstrap, there is a simple and fast method I have used,
use 2  tag, hide 1st image in mobile by using class "d-none d-sm-block"
and hide 2nd image in desktop by using class "d-block d-sm-none"
check the code below:

<div>
<img  src="img5.jpg"  class="d-none d-sm-block"  />

<img src="img5-mobile.jpg"  class=" d-block d-sm-none" />
</div>


问:
create all possible combinations with multiple variants from list
Ok so the problem is as follows:

let's say I have a list like this [12R,102A,102L,250L] what I would want is a list of all possible combinations, however for only one combination/number. so for the example above, the output I would like is:

```<code>[12R,102A,250L]
[12R,102L,250L]
</code>```

my actual problem is a lot more complex with many more sites. Thanks for your help

edit: after reading some comments I guess this is slightly unclear. I have 3 unique numbers here, [12, 102, and 250] and for some numbers, I have different variations, for example [102A, 102L]. what I need is a way to combine the different positions[12,102,250] and all possible variations within. just like the lists, I presented above. they are the only valid solutions. [12R] is not. neither is [12R,102A,102L,250L]. so far I have done this with nested loops, but I have a LOT of variation within these numbers, so I can't really do that anymore

ill edit this again: ok so it seems as though there is still some confusion so I might extend the point I made before. what I am dealing with there is DNA. 12R means the 12th position in the sequence was changed to an R. so the solution     [12R,102A,250L] means that the amino acid on position 12 is R, 102 is A 250 is L.

this is why a solution like [102L, 102R, 250L] is not usable, because the same position can not be occupied by 2 different amino acids.

thank you

答:
```<code>import re

def get_grouped_options(input):
     options = {}
     for option in input:
          m = re.match('([\d]+)([A-Z])$', option)
          if m:
               position = int(m.group(1))
               acid = m.group(2)
          else:
               continue
          if position not in options:
               options[position] = []
          options[position].append(acid)
     return options

def yield_all_combos(options):
     n = len(options)
     positions = list(options.keys())
     indices = [0] * n
     while True:
          yield ["{}{}".format(position, options[position][indices[i]])
                 for i, position in enumerate(positions)]
          j = 0
          indices[j] += 1
          while indices[j] == len(options[positions[j]]):
               # carry
               indices[j] = 0
               j += 1
               if j == n:
                    # overflow
                    return
               indices[j] += 1

input = ['12R', '102A', '102L', '250L']

options = get_grouped_options(input)

for combo in yield_all_combos(options):
     print("[{}]".format(",".join(combo)))
</code>```

Gives:

```<code>[12R,102A,250L]
[12R,102L,250L]
</code>```

Body:
Ok so the problem is as follows:

let's say I have a list like this [12R,102A,102L,250L] what I would want is a list of all possible combinations, however for only one combination/number. so for the example above, the output I would like is:

[12R,102A,250L]
[12R,102L,250L]

my actual problem is a lot more complex with many more sites. Thanks for your help

edit: after reading some comments I guess this is slightly unclear. I have 3 unique numbers here, [12, 102, and 250] and for some numbers, I have different variations, for example [102A, 102L]. what I need is a way to combine the different positions[12,102,250] and all possible variations within. just like the lists, I presented above. they are the only valid solutions. [12R] is not. neither is [12R,102A,102L,250L]. so far I have done this with nested loops, but I have a LOT of variation within these numbers, so I can't really do that anymore

ill edit this again: ok so it seems as though there is still some confusion so I might extend the point I made before. what I am dealing with there is DNA. 12R means the 12th position in the sequence was changed to an R. so the solution     [12R,102A,250L] means that the amino acid on position 12 is R, 102 is A 250 is L.

this is why a solution like [102L, 102R, 250L] is not usable, because the same position can not be occupied by 2 different amino acids.

thank you

Body:
import re

def get_grouped_options(input):
     options = {}
     for option in input:
          m = re.match('([\d]+)([A-Z])$', option)
          if m:
               position = int(m.group(1))
               acid = m.group(2)
          else:
               continue
          if position not in options:
               options[position] = []
          options[position].append(acid)
     return options

def yield_all_combos(options):
     n = len(options)
     positions = list(options.keys())
     indices = [0] * n
     while True:
          yield ["{}{}".format(position, options[position][indices[i]])
                 for i, position in enumerate(positions)]
          j = 0
          indices[j] += 1
          while indices[j] == len(options[positions[j]]):
               # carry
               indices[j] = 0
               j += 1
               if j == n:
                    # overflow
                    return
               indices[j] += 1

input = ['12R', '102A', '102L', '250L']

options = get_grouped_options(input)

for combo in yield_all_combos(options):
     print("[{}]".format(",".join(combo)))

Gives:

[12R,102A,250L]
[12R,102L,250L]


问:
ag-Grid - how to force custom sorting after data is added or modified
I am trying to use custom sorting on a column in ag-Grid in my Ionic 4/Angular 8 application.

I have a sample application here, or on Stackblitz I can't get it to run on Stackblitz, but it definatley runs locally,

At any rate a couple of things to note are I want the grid to run in virtual mode (eg may have 1000 rows of data), and also I have set this.gridOptions.immutableData = true; to handle my data from ng/rx.

Also I am using a component as a cell template, but I think we can ignore that here (using an existing example)

I wish to have the rows sorted, and so calling my dateComparator function both

When I first load the data

If I have any data added or updated

To emulate new data coming in from a server, I have an add button which calls the add method.

I have added a comparator on the column...

        public ngAfterViewInit(): void {
            const self = this;
            this.gridOptions.immutableData = true;
            this.gridOptions.animateRows = true
            this.gridOptions.api.setColumnDefs([
            {
                    headerName: 'myheader',
                    comparator: self.dateComparator,
                    sortable: true,
                    field: 'equipment',
                    cellStyle: { padding: 0 },
                    cellRendererFramework: TemplateRendererComponent,
                    cellRendererParams: {
                        ngTemplate: this.itemCard
                    },
                },
            ]);

            this.setData();
            }

    private dateComparator(valueA, valueB, nodeA, nodeB, isInverted): number {
       console.log('sorting');
       return 1;
     }
```

However, when I load the grid, or call the above add method, my dateComparator is not being called. It is only called if I click the column header.

I have tried calling this.gridOptions.api.redrawRows() but this does not cause it to sort. I can't see any other obvious sort function to call.

My question is, how can I have this sorting applied automatically without clicking the column header (ie when I load or update my data)?

答:
To sort a column by default, you have to specify the sorting attribute in the colDef -

```<code>sort: 'desc', // asc or desc
</code>```

You can also do this after grid is initialized using sorting api -

```<code>var sort = [
  {
    colId: 'country',
    sort: 'asc',
  },
  {
    colId: 'sport',
    sort: 'asc',
  },
];
this.gridApi.setSortModel(sort); // provide sort model here
</code>```

Now, when your data is updated and you need to let the grid know to maintain the sorting as per your custom comparator, you need to call -  onSortChanged()

As per docs-

onSortChanged()

  Gets the grid to act as if the sort was changed. Useful if you update some values and want to get the grid to
  reorder them according to the new values.

Example on applying sort model here

Body:
I am trying to use custom sorting on a column in ag-Grid in my Ionic 4/Angular 8 application.

I have a sample application here, or on Stackblitz I can't get it to run on Stackblitz, but it definatley runs locally,

At any rate a couple of things to note are I want the grid to run in virtual mode (eg may have 1000 rows of data), and also I have set this.gridOptions.immutableData = true; to handle my data from ng/rx.

Also I am using a component as a cell template, but I think we can ignore that here (using an existing example)

I wish to have the rows sorted, and so calling my dateComparator function both

When I first load the data

If I have any data added or updated

To emulate new data coming in from a server, I have an add button which calls the add method.

I have added a comparator on the column...

        public ngAfterViewInit(): void {
            const self = this;
            this.gridOptions.immutableData = true;
            this.gridOptions.animateRows = true
            this.gridOptions.api.setColumnDefs([
            {
                    headerName: 'myheader',
                    comparator: self.dateComparator,
                    sortable: true,
                    field: 'equipment',
                    cellStyle: { padding: 0 },
                    cellRendererFramework: TemplateRendererComponent,
                    cellRendererParams: {
                        ngTemplate: this.itemCard
                    },
                },
            ]);

            this.setData();
            }

    private dateComparator(valueA, valueB, nodeA, nodeB, isInverted): number {
       console.log('sorting');
       return 1;
     }

However, when I load the grid, or call the above add method, my dateComparator is not being called. It is only called if I click the column header.

I have tried calling this.gridOptions.api.redrawRows() but this does not cause it to sort. I can't see any other obvious sort function to call.

My question is, how can I have this sorting applied automatically without clicking the column header (ie when I load or update my data)?

Body:
To sort a column by default, you have to specify the sorting attribute in the colDef -

sort: 'desc', // asc or desc

You can also do this after grid is initialized using sorting api -

var sort = [
  {
    colId: 'country',
    sort: 'asc',
  },
  {
    colId: 'sport',
    sort: 'asc',
  },
];
this.gridApi.setSortModel(sort); // provide sort model here

Now, when your data is updated and you need to let the grid know to maintain the sorting as per your custom comparator, you need to call -  onSortChanged()

As per docs-

onSortChanged()

  Gets the grid to act as if the sort was changed. Useful if you update some values and want to get the grid to
  reorder them according to the new values.

Example on applying sort model here


问:
Keep getting "Cannot assign to value: 'calculateBMI' is a method" when using a struct
I keep getting "Cannot assign to value: 'calculateBMI' is a method" error message when using a struct property. any way around this. This is my code from the struct:

```<code>import UIKit

struct Calculations {

var bmi : Float = 0.0

func getBMIValue() -> String {
   let BMIRounded = String(format: "%.1f", bmi)
    return BMIRounded
}

mutating func calculateBMI (height: Float, weight: Float) {
    bmi = weight / (height * height)
}
}
</code>```

and this is where I get the error message on my First Page View controller:

```<code>import UIKit

class HomeViewController: UIViewController {

var calculations = Calculations()

@IBOutlet weak var heightLabel: UILabel!
@IBOutlet weak var weightLabel: UILabel!
@IBOutlet weak var heightSlider: UISlider!
@IBOutlet weak var weightSlider: UISlider!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

@IBAction func HeightSliderChange(_ sender: UISlider) {
    var height = String (format: "%.2f", sender.value)
    heightLabel.text = "\(height)m"
    print(height)

}

@IBAction func WeightSliderChange(_ sender: UISlider) {
    var weight = String (format: "%.0f", sender.value)
    weightLabel.text = "\(weight)kg"

}

@IBAction func calculatePressed(_ sender: Any) {
    let height = heightSlider.value
    let weight = weightSlider.value

    calculations.calculateBMI = (height: height, weight: weight)
    self.performSegue(withIdentifier: "GettingResults", sender: self)

}
}
</code>```

The error happens on line 43 (calculations.calculateBMI)

答:
As the error states clearly you are trying to set calculateBMI which is a function and not a variable. To fix this issue modify your calculatePressed method like this:

@IBAction func calculatePressed(_ sender: Any) {
    let height = heightSlider.value
    let weight = weightSlider.value

    calculations.calculateBMI(height: height, weight: weight)
    self.performSegue(withIdentifier: "GettingResults", sender: self)
}
```

Body:
I keep getting "Cannot assign to value: 'calculateBMI' is a method" error message when using a struct property. any way around this. This is my code from the struct:

import UIKit

struct Calculations {

var bmi : Float = 0.0

func getBMIValue() -> String {
   let BMIRounded = String(format: "%.1f", bmi)
    return BMIRounded
}

mutating func calculateBMI (height: Float, weight: Float) {
    bmi = weight / (height * height)
}
}

and this is where I get the error message on my First Page View controller:

import UIKit

class HomeViewController: UIViewController {

var calculations = Calculations()

@IBOutlet weak var heightLabel: UILabel!
@IBOutlet weak var weightLabel: UILabel!
@IBOutlet weak var heightSlider: UISlider!
@IBOutlet weak var weightSlider: UISlider!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

@IBAction func HeightSliderChange(_ sender: UISlider) {
    var height = String (format: "%.2f", sender.value)
    heightLabel.text = "\(height)m"
    print(height)

}

@IBAction func WeightSliderChange(_ sender: UISlider) {
    var weight = String (format: "%.0f", sender.value)
    weightLabel.text = "\(weight)kg"

}

@IBAction func calculatePressed(_ sender: Any) {
    let height = heightSlider.value
    let weight = weightSlider.value

    calculations.calculateBMI = (height: height, weight: weight)
    self.performSegue(withIdentifier: "GettingResults", sender: self)

}
}

The error happens on line 43 (calculations.calculateBMI)


问:
ruby Nokogiri requests 403 Forbidden
Hi I use gem Nokogiri to  scrape the gem getails from ruby-toolbox

```<code>Nokogiri::HTML(open("https://www.ruby-toolbox.com/categories/by_name"))
</code>```

but I get the error: "403 Forbidden"

Can anyone tell me why I am getting this error?

Thanks in advance

答:
I spent ~1 hour trying solutions for a 403 forbidden, including tinkering with the User-Agent argument to Nokogiri::HTML(open(www.something.com, User-Agent: "Safari")), looking into proxies, and other things.

But the whole time there was nothing wrong with my code, the website I had been automated browsing had subtly changed url, and the url it previously visited was fobidden.

I hope this may save someone else some time.

Title: ruby Nokogiri requests 403 Forbidden

Body:
Hi I use gem Nokogiri to  scrape the gem getails from ruby-toolbox

Nokogiri::HTML(open("https://www.ruby-toolbox.com/categories/by_name"))

but I get the error: "403 Forbidden"

Can anyone tell me why I am getting this error?

Thanks in advance


问:
Can't get defaultRedirect to work
In my web.config, I have:

```<code><system.web>
    <customErrors mode="On" defaultRedirect="Error.cshtml" />
</system.web>
</code>```

In Views/Shared/Error.cshtml, I have:

```<code>@model System.Web.Mvc.HandleErrorInfo
@{
    ViewBag.Title = "Error";
}
<h2>
    Sorry, an error occurred while processing your request.
</h2>
</code>```

If I put an invalid URL/route into my browser, I get this:

Server Error in '/' Application.

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /Error.cshtml

Why can't Error.cshtml be found? The file is definitely in Views/Shared.

答:
You should mark your controller action with [HandleError] attribute or register it as a global filter

EDIT:
It happens because of custom errors' redirects functionality belongs to ASP.NET infrastructure and knows nothing about ASP.NET MVC.

You should create separate controller for managing redirects and specify url to it in your Web.config. Or you could create static html file and put it into root directory (or wherever else except Views directory)

Title: Can't get defaultRedirect to work

Body:
In my web.config, I have:

<system.web>
    <customErrors mode="On" defaultRedirect="Error.cshtml" />
</system.web>

In Views/Shared/Error.cshtml, I have:

@model System.Web.Mvc.HandleErrorInfo
@{
    ViewBag.Title = "Error";
}

    Sorry, an error occurred while processing your request.

If I put an invalid URL/route into my browser, I get this:

Server Error in '/' Application.

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /Error.cshtml

Why can't Error.cshtml be found? The file is definitely in Views/Shared.


问:
How can i instantiate a different subclass based on common identifier (java)
I have a class for a tile.

```<code>public abstract class Tile {
    public Position pos;
    public char chr;
}
</code>```

And many different classes that extend tile. Each subclass has its own identifier char.
Now I have a function that receives a char and a position and needs to create and return a new instance of a tile subclass fitting the char in given position.
Is there an elegant OOP way to do this other than run through all of the options?

答:
So for me use of an identifier like this is a bit of a design flaw.

You could add something like the following to the abstract class:

```<code>public static Tile factory(char identifier, Position p) {
   Tile value = null;
   switch (identifier) {
      case `x`: {
        value = new XTile(p);
        break;
      }
      default {
        // throw an exception or provide a default
      }
   }
   return value
}
</code>```

Effective Java (third edition) Item 21 "Prefer Class hierarchies to tagged classes" might provide an alternative to your design.

Body:
I have a class for a tile.

public abstract class Tile {
    public Position pos;
    public char chr;
}

And many different classes that extend tile. Each subclass has its own identifier char.
Now I have a function that receives a char and a position and needs to create and return a new instance of a tile subclass fitting the char in given position.
Is there an elegant OOP way to do this other than run through all of the options?

Body:
So for me use of an identifier like this is a bit of a design flaw.

You could add something like the following to the abstract class:

public static Tile factory(char identifier, Position p) {
   Tile value = null;
   switch (identifier) {
      case `x`: {
        value = new XTile(p);
        break;
      }
      default {
        // throw an exception or provide a default
      }
   }
   return value
}

Effective Java (third edition) Item 21 "Prefer Class hierarchies to tagged classes" might provide an alternative to your design.


问:
No idea how being on service class to get float from seekbar on layoutt. Android Studio
My aim is to  manage volume by seekbar of background music.
I created background music by service.
I have media player in Service class:

```<code>public class ModernService extends Service  {

private MediaPlayer modernsong;
private SeekBar volumeSeekBar;
AudioManager am;

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

public ModernService() {
    super();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
     am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    modernsong =MediaPlayer.create(this,R.raw.modern);
    modernsong.setLooping(true);
    modernsong.start();
    return START_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();

    modernsong.stop();
}
</code>```

}

The question is how can i get float from a seekbar that is on layout.
Thanks in advance

答:
First initialize the volumeSeekbar and set the max value.

volumeSeekBar = findViewById(R.id.seekBarId);
volumeSeekBar.setMax(100);

Then you need to add OnSeekBarChangeListener to the veiw.

volumeSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

```<code>        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,
                boolean fromUser) {
          //any ui changes you wanted to do on user action on seekbar
        }
    });
</code>```

Now you can get the value from the seekbar as volumeSeekBar.getProgress();

In service class onStartCommand is having direct access to intent.
So while starting the service through intent you can pass the seekbar value.

Intent mIntent = new Intent(this, Service.class);
    Bundle extras = mIntent.getExtras();
    extras.putString(key, seekbarValue);

Body:
My aim is to  manage volume by seekbar of background music.
I created background music by service.
I have media player in Service class:

public class ModernService extends Service  {

private MediaPlayer modernsong;
private SeekBar volumeSeekBar;
AudioManager am;

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

public ModernService() {
    super();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
     am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    modernsong =MediaPlayer.create(this,R.raw.modern);
    modernsong.setLooping(true);
    modernsong.start();
    return START_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();

    modernsong.stop();
}

}

The question is how can i get float from a seekbar that is on layout.
Thanks in advance

Body:
First initialize the volumeSeekbar and set the max value.

volumeSeekBar = findViewById(R.id.seekBarId);
volumeSeekBar.setMax(100);

Then you need to add OnSeekBarChangeListener to the veiw.

volumeSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,
                boolean fromUser) {
          //any ui changes you wanted to do on user action on seekbar
        }
    });

Now you can get the value from the seekbar as volumeSeekBar.getProgress();

In service class onStartCommand is having direct access to intent.
So while starting the service through intent you can pass the seekbar value.

Intent mIntent = new Intent(this, Service.class);
    Bundle extras = mIntent.getExtras();
    extras.putString(key, seekbarValue);


问:
Admob Banner ad is not displaying
Ads are not showing. I have configured my device as a test unit.

```<code>MobileAds.initialize(getActivity(), new OnInitializationCompleteListener() {
        @Override
        public void onInitializationComplete(InitializationStatus initializationStatus) {
        }
    });
    //setup test device
    MobileAds.setRequestConfiguration(
            new RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("A222ECB948AFB6D392596135E7D33D35"))
                    .build());
    mAdView = root.findViewById(R.id.adView);
    final AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);
    mAdView.setAdListener( new AdListener(){
        @Override
        public void onAdLoaded() {
            Log.i("nonsinglefragment","ad loaded");
            super.onAdLoaded();
        }

        @Override
        public void onAdFailedToLoad(int i) {
            Log.i("nonsinglefragment","ad load failed "+i);
            super.onAdFailedToLoad(i);
        }

    });
</code>```

Xml code

```<code><com.google.android.gms.ads.AdView
    android:id="@+id/adView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:adSize="BANNER"
    app:adUnitId="@string/ad_id1"/>
</code>```

This is the logcat

```<code>I/Ads: Updating ad debug logging enablement.
I/Ads: This request is sent from a test device.
W/Ads: Not retrying to fetch app settings
I/Ads: This request is sent from a test device.
W/Ads: Not retrying to fetch app settings
W/Ads: Update ad debug logging enablement as false
I/Ads: Ad failed to load : 0
I/Ads: Ad failed to load : 0
</code>```

Everything was working fine with google's sample test ids. The problem started when I implemented my unit ID.

答:
Please make sure your Admob account is active. if it is active then you can wait for some hours sometimes Ads take time to appear.

this is what google documentation says :

"It could be that you have only recently created a new Ad Unit ID and requesting for live ads. It could take a few hours for ads to start getting served if that is that case. If you are receiving test ads then your implementation is fine. Just wait a few hours and see if you are able to receive live ads then. If not, can send us your Ad Unit ID for us to look into."

Title: Admob Banner ad is not displaying

Body:
Ads are not showing. I have configured my device as a test unit.

MobileAds.initialize(getActivity(), new OnInitializationCompleteListener() {
        @Override
        public void onInitializationComplete(InitializationStatus initializationStatus) {
        }
    });
    //setup test device
    MobileAds.setRequestConfiguration(
            new RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("A222ECB948AFB6D392596135E7D33D35"))
                    .build());
    mAdView = root.findViewById(R.id.adView);
    final AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);
    mAdView.setAdListener( new AdListener(){
        @Override
        public void onAdLoaded() {
            Log.i("nonsinglefragment","ad loaded");
            super.onAdLoaded();
        }

        @Override
        public void onAdFailedToLoad(int i) {
            Log.i("nonsinglefragment","ad load failed "+i);
            super.onAdFailedToLoad(i);
        }

    });

Xml code

<com.google.android.gms.ads.AdView
    android:id="@+id/adView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:adSize="BANNER"
    app:adUnitId="@string/ad_id1"/>

This is the logcat

I/Ads: Updating ad debug logging enablement.
I/Ads: This request is sent from a test device.
W/Ads: Not retrying to fetch app settings
I/Ads: This request is sent from a test device.
W/Ads: Not retrying to fetch app settings
W/Ads: Update ad debug logging enablement as false
I/Ads: Ad failed to load : 0
I/Ads: Ad failed to load : 0

Everything was working fine with google's sample test ids. The problem started when I implemented my unit ID.


问:
Rotate vertices selected using weight map on UVs in Unity3D's Shader Graph around pivot point
TLDR: Can't figure out the correct Shader Graph setup for using UV and vertex displacement to cheaply animate a (unrigged) mesh.

I am trying to rotate a part of the mesh based on the UV coordinates, e.g: fromX 0 toX 0.4, fromY 0 toY 0.6. The mesh is created uv-mapped with this in mind.

I have no problem getting the affected vertices in this area. Problem is that I want to rotate these verts for customizable axis e.g. axis(X:1, Y:0, Z:1) using a weight so that the rotation takes place around a pivoted point. I want the bottom selection to stay connected to the rest of the mesh while the other affected vertices neatly rotate around this point.
The weight can be painted by using split UV channels as seen in the picture:

I multiply the weighted area with a rotation node to rotate it.
And I add that to the negative multiplied position (the rest of the verts, excluding the rotated area) to get the final output displacement.

But the rotated mesh is bent. I need it to be stiff as in the whole part rotated with weight=1 except for the very pivoting vertex.

I can get it as described using a weight=1 based rotation, but the pivot point becomes the center of the mesh, not the desired point.

How can I do this correctly?
Been at it for days, please help :')

答:
I started using Unity about a month ago, and this is one of the first issues I faced.

The node you are using will always transform the vertices around the origin.

I think you have two options available:

Translate the vertices by the offset of where you want to rotate the wings.  This would require storing the pivot point of the wings in the mesh somehow - This could done by utilizing a spare UV channel, or by using the vertex color channel.

Use bones and paint the weights in your chosen 3D package.  This way, you can record the animation, and use Unity's skinned mesh shader to render it.

Hope that helps.


问:
updating state of a python class
I am trying to simulate a 3 x 3 board in python 3.6+ in which the 0 "tile" can move up, down, left or right. I am implementing the state as a list.

```<code>class Tiles(object):

    def __init__(self, state, n):

        self.n = n
        self.state = state

        self.blank_index = self.state.index(0)

    def display(self):
        """ Tile state as a n*n board """
        for i in range(self.n):
            print(self.state[3 * i: 3 * (i + 1)])

    def move_up(self):
        blank = self.blank_index
        print("Blank is at position {}.".format(blank))
        if blank <= 2:
            return None
        else:
            up = self.state
            up[blank], up[blank - 3] = up[blank - 3], up[blank]
            Tiles.display(self)
            return Tiles(up, self.n)

    def move_down(self):
        blank = self.blank_index
        print("Blank is at position {}.".format(blank))
        if blank > 5:
            return None
        else:
            down = self.state
            down[blank], down[blank + 3] = down[blank + 3], down[blank]
            Tiles.display(self)
            return Tiles(down, self.n)

    def move_left(self):
        blank = self.blank_index
        print("Blank is at position {}.".format(blank))
        if blank == 0 or blank == 3 or blank == 6:
            return None
        else:
            left = self.state
            left[blank], left[blank - 1] = left[blank - 1], left[blank]
            Tiles.display(self)
            return Tiles(left, self.n)

    def move_right(self):
        blank = self.blank_index
        print("Blank is at position {}.".format(blank))
        if blank == 2 or blank == 5 or blank == 8:
            return None
        else:
            right = self.state
            right[blank], right[blank + 1] = right[blank + 1], right[blank]
            Tiles.display(self)
            return Tiles(right, self.n)

def move_seq(self):
    self.display()
    self.move_up()
    self.move_left()
    self.move_right()

def main():
    initial = [4,3,2,1,0,8,7,6,5]
    new_tiles = Tiles(initial, 9)
    move_seq(new_tiles)

if __name__ == '__main__':
    main()

</code>```

But my output is unexpected...

```<code>[4, 3, 2]
[1, 0, 8]
[7, 6, 5]
[]
[]
[]
[]
[]
[]
Blank is at position 4.
[4, 0, 2]
[1, 3, 8]
[7, 6, 5]
[]
[]
[]
[]
[]
[]
Blank is at position 4.
[4, 0, 2]
[3, 1, 8]
[7, 6, 5]
[]
[]
[]
[]
[]
[]
Blank is at position 4.
[4, 0, 2]
[3, 8, 1]
[7, 6, 5]
[]
[]
[]
[]
[]
[]
</code>```

I am having trouble comprehending why (1) the self.move_up() call in function move_seq(self) displays the desired output but the subsequent method calls do not, (2) why the updated state isn't saved i.e. Blank is at position 4 and (3) why there are extra empty list objects printing in display.

Thank you in advance for aiding me in my understanding!

答:
Try this:

```<code>class Tiles(object):
    def __init__(self, state, n):

        self.n = n
        self.state = state

        self.blank_index = self.state.index(0)

    def display(self):
        """ Tile state as a n*n board """
        for i in range(self.n//3):
            print(self.state[3 * i : 3 * (i + 1)])

    def move_up(self):
        blank = self.blank_index
        print("Blank is at position {}.".format(blank))
        if blank <= 2:
            return None
        else:
            up = self.state
            up[blank], up[blank - 3] = up[blank - 3], up[blank]
            self.blank_index = self.state.index(0)
            self.display()

    def move_down(self):
        blank = self.blank_index
        print("Blank is at position {}.".format(blank))
        if blank > 5:
            return None
        else:
            down = self.state
            down[blank], down[blank + 3] = down[blank + 3], down[blank]
            self.blank_index = self.state.index(0)
            self.display()

    def move_left(self):
        blank = self.blank_index
        print("Blank is at position {}.".format(blank))
        if blank == 0 or blank == 3 or blank == 6:
            return None
        else:
            left = self.state
            left[blank], left[blank - 1] = left[blank - 1], left[blank]
            self.blank_index = self.state.index(0)
            self.display()

    def move_right(self):
        blank = self.blank_index
        print("Blank is at position {}.".format(blank))
        if blank == 2 or blank == 5 or blank == 8:
            return None
        else:
            right = self.state
            right[blank], right[blank + 1] = right[blank + 1], right[blank]
            self.blank_index = self.state.index(0)
            self.display()

def move_seq(obj):
    obj.display()
    obj.move_up()
    obj.move_left()
    obj.move_right()

def main():
    initial = [4, 3, 2, 1, 0, 8, 7, 6, 5]
    new_tiles = Tiles(initial, 9)
    move_seq(new_tiles)

if __name__ == "__main__":
    main()
</code>```

EXPLANATION:

Firstly, you are never updating the blank_index instance attribute of the initial object.  For example, in this code:

```<code>    def move_up(self):
        blank = self.blank_index
        print("Blank is at position {}.".format(blank))
        if blank <= 2:
            return None
        else:
            up = self.state
            up[blank], up[blank - 3] = up[blank - 3], up[blank]
            self.display()
            return Tiles(up, self.n)
</code>```

blank will always be the initial "4", for move_up, move_left, move_right, and move_down.  You should instead update this attribute after modifying the state attribute as such:

```<code>    def move_up(self):
        blank = self.blank_index
        print("Blank is at position {}.".format(blank))
        if blank <= 2:
            return None
        else:
            up = self.state
            up[blank], up[blank - 3] = up[blank - 3], up[blank]
            self.blank_index = self.state.index(0)
            self.display()
</code>```

You are then creating new Tiles instances and returning them... and yet, you are never using these new objects because you are never assigning these returned objects to new variables, and all of your calls in

```<code># Note: You should not use the variable "self" outside of a class... in this instance it would make more sense to use something like "obj" (short for object).
def move_seq(obj):
    obj.display()
    obj.move_up()
    obj.move_left()
    obj.move_right()
</code>```

are calling methods of the INITIAL object!

Also, you are printing out a bunch of blank cells since you're iterating through the full size of the board, when really you want to be iterating across the number of rows you intend to print, in this case 3.

Title: updating state of a python class

Body:
I am trying to simulate a 3 x 3 board in python 3.6+ in which the 0 "tile" can move up, down, left or right. I am implementing the state as a list.

class Tiles(object):

    def __init__(self, state, n):

        self.n = n
        self.state = state

        self.blank_index = self.state.index(0)

    def display(self):
        """ Tile state as a n*n board """
        for i in range(self.n):
            print(self.state[3 * i: 3 * (i + 1)])

    def move_up(self):
        blank = self.blank_index
        print("Blank is at position {}.".format(blank))
        if blank <= 2:
            return None
        else:
            up = self.state
            up[blank], up[blank - 3] = up[blank - 3], up[blank]
            Tiles.display(self)
            return Tiles(up, self.n)

    def move_down(self):
        blank = self.blank_index
        print("Blank is at position {}.".format(blank))
        if blank > 5:
            return None
        else:
            down = self.state
            down[blank], down[blank + 3] = down[blank + 3], down[blank]
            Tiles.display(self)
            return Tiles(down, self.n)

    def move_left(self):
        blank = self.blank_index
        print("Blank is at position {}.".format(blank))
        if blank == 0 or blank == 3 or blank == 6:
            return None
        else:
            left = self.state
            left[blank], left[blank - 1] = left[blank - 1], left[blank]
            Tiles.display(self)
            return Tiles(left, self.n)

    def move_right(self):
        blank = self.blank_index
        print("Blank is at position {}.".format(blank))
        if blank == 2 or blank == 5 or blank == 8:
            return None
        else:
            right = self.state
            right[blank], right[blank + 1] = right[blank + 1], right[blank]
            Tiles.display(self)
            return Tiles(right, self.n)

def move_seq(self):
    self.display()
    self.move_up()
    self.move_left()
    self.move_right()

def main():
    initial = [4,3,2,1,0,8,7,6,5]
    new_tiles = Tiles(initial, 9)
    move_seq(new_tiles)

if __name__ == '__main__':
    main()

But my output is unexpected...

[4, 3, 2]
[1, 0, 8]
[7, 6, 5]
[]
[]
[]
[]
[]
[]
Blank is at position 4.
[4, 0, 2]
[1, 3, 8]
[7, 6, 5]
[]
[]
[]
[]
[]
[]
Blank is at position 4.
[4, 0, 2]
[3, 1, 8]
[7, 6, 5]
[]
[]
[]
[]
[]
[]
Blank is at position 4.
[4, 0, 2]
[3, 8, 1]
[7, 6, 5]
[]
[]
[]
[]
[]
[]

I am having trouble comprehending why (1) the self.move_up() call in function move_seq(self) displays the desired output but the subsequent method calls do not, (2) why the updated state isn't saved i.e. Blank is at position 4 and (3) why there are extra empty list objects printing in display.

Thank you in advance for aiding me in my understanding!

Body:
Try this:

class Tiles(object):
    def __init__(self, state, n):

        self.n = n
        self.state = state

        self.blank_index = self.state.index(0)

    def display(self):
        """ Tile state as a n*n board """
        for i in range(self.n//3):
            print(self.state[3 * i : 3 * (i + 1)])

    def move_up(self):
        blank = self.blank_index
        print("Blank is at position {}.".format(blank))
        if blank <= 2:
            return None
        else:
            up = self.state
            up[blank], up[blank - 3] = up[blank - 3], up[blank]
            self.blank_index = self.state.index(0)
            self.display()

    def move_down(self):
        blank = self.blank_index
        print("Blank is at position {}.".format(blank))
        if blank > 5:
            return None
        else:
            down = self.state
            down[blank], down[blank + 3] = down[blank + 3], down[blank]
            self.blank_index = self.state.index(0)
            self.display()

    def move_left(self):
        blank = self.blank_index
        print("Blank is at position {}.".format(blank))
        if blank == 0 or blank == 3 or blank == 6:
            return None
        else:
            left = self.state
            left[blank], left[blank - 1] = left[blank - 1], left[blank]
            self.blank_index = self.state.index(0)
            self.display()

    def move_right(self):
        blank = self.blank_index
        print("Blank is at position {}.".format(blank))
        if blank == 2 or blank == 5 or blank == 8:
            return None
        else:
            right = self.state
            right[blank], right[blank + 1] = right[blank + 1], right[blank]
            self.blank_index = self.state.index(0)
            self.display()

def move_seq(obj):
    obj.display()
    obj.move_up()
    obj.move_left()
    obj.move_right()

def main():
    initial = [4, 3, 2, 1, 0, 8, 7, 6, 5]
    new_tiles = Tiles(initial, 9)
    move_seq(new_tiles)

if __name__ == "__main__":
    main()

EXPLANATION:

Firstly, you are never updating the blank_index instance attribute of the initial object.  For example, in this code:

    def move_up(self):
        blank = self.blank_index
        print("Blank is at position {}.".format(blank))
        if blank <= 2:
            return None
        else:
            up = self.state
            up[blank], up[blank - 3] = up[blank - 3], up[blank]
            self.display()
            return Tiles(up, self.n)

blank will always be the initial "4", for move_up, move_left, move_right, and move_down.  You should instead update this attribute after modifying the state attribute as such:

    def move_up(self):
        blank = self.blank_index
        print("Blank is at position {}.".format(blank))
        if blank <= 2:
            return None
        else:
            up = self.state
            up[blank], up[blank - 3] = up[blank - 3], up[blank]
            self.blank_index = self.state.index(0)
            self.display()

You are then creating new Tiles instances and returning them... and yet, you are never using these new objects because you are never assigning these returned objects to new variables, and all of your calls in

# Note: You should not use the variable "self" outside of a class... in this instance it would make more sense to use something like "obj" (short for object).
def move_seq(obj):
    obj.display()
    obj.move_up()
    obj.move_left()
    obj.move_right()

are calling methods of the INITIAL object!

Also, you are printing out a bunch of blank cells since you're iterating through the full size of the board, when really you want to be iterating across the number of rows you intend to print, in this case 3.


问:
Which classes should have access to a ViewModel
I'm wondering what is a good/best practice to deal with ViewModels and multiple Activities referring to a specific piece of data in my database.

Assuming I have a FriendViewModel which provides access to my friend_database (throught a Repository and a Dao of course) and a RecyclerView displaying all FriendEntities.

If I now want to edit a friend in a different Activity: is it better (or more efficient) to pass one or more FriendEntities (implementing Serializable) to the intent, or should I rather pass the friendId + FriendViewModel and retrieve the FriendEntity from the friend_database using the passed FriendViewModel and friendId?

As this seems to be a common scenario: is there a best practice for that situation?

答:
We usually have separate ViewModels for different Activities/Fragments unless we have common data we want to handle and that's where SharedViewModel comes into play. In your situation, I don't see using a ShareViewModel necessary at all.

FirstActivity:

ListActivity -> ListViewModel -> FriendRepository -> FriendDao

SecondActivity

EditActivity -> EditViewModel -> FriendRepository -> FriendDao

So the only things shared here are your Repository and FriendDao which wraps around Friend model.

Pass friend id from ListActivity to EditActivity, ask FriendRepository to retrieve that friend by using DAO.

That's the approach I personally use and most of the samples out there will use.


问:
Show or hide checkout postcode field based on chosen city in WooCommerce
In Woocommerce, I am trying to hide the checkout postcode field if a specific city field is selected. I found a working code that hides the billing phone if company field is empty:

```<code>add_action( 'woocommerce_after_checkout_form', 'conditionally_hide_show_checkout_field', 9999 );
function conditionally_hide_show_checkout_field() {
wc_enqueue_js( "
  jQuery('#billing_company').keyup(function() {
     if (jQuery(this).val().length == 0) {
        jQuery('#billing_phone').hide();
     } else {
        jQuery('#billing_phone').show();
     }
  }).keyup();
");
}
</code>```

I don't know how to alter this code to make the required postcode field to be hidden when a specific billing city is selected. Any help is appreciated.

答:
You can do it like this:

$("#billing_city").on("change", function() {
  if ($(this).val() != "") {
    $("#postcode").removeAttr('required');
  } else {
    $("#postcode").prop("required", true);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="billing_city">
  <option value="">Select City</option>
  <option value="losangeles">LosAngeles</option>
  <option value="newyork">New York</option>
</select>
<input type="text" id="postcode" placeholder="Postcode" required /></code>```

Body:
In Woocommerce, I am trying to hide the checkout postcode field if a specific city field is selected. I found a working code that hides the billing phone if company field is empty:

add_action( 'woocommerce_after_checkout_form', 'conditionally_hide_show_checkout_field', 9999 );
function conditionally_hide_show_checkout_field() {
wc_enqueue_js( "
  jQuery('#billing_company').keyup(function() {
     if (jQuery(this).val().length == 0) {
        jQuery('#billing_phone').hide();
     } else {
        jQuery('#billing_phone').show();
     }
  }).keyup();
");
}

I don't know how to alter this code to make the required postcode field to be hidden when a specific billing city is selected. Any help is appreciated.

Body:
You can do it like this:

$("#billing_city").on("change", function() {
  if ($(this).val() != "") {
    $("#postcode").removeAttr('required');
  } else {
    $("#postcode").prop("required", true);
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="billing_city">
  <option value="">Select City</option>
  <option value="losangeles">LosAngeles</option>
  <option value="newyork">New York</option>
</select>
<input type="text" id="postcode" placeholder="Postcode" required />


问:
PrimeNG Paginator set Page
I'm using the primeng paginator component inside an Angular 9 Project to page a huge list of profiles. If a user is on page 3, opens a profile and returns to search, the current page is 1, but it should be 3. I have saved the page inside a service, so the right data is shown, but the paginator is showing the wrong page. I could not find a way to set the current page of the paginator. Using the [first] attribute is not working.</p>

答:
You need to set the page manually. You can use Angular @ViewChild decorator to get access to PrimeNg Paginator component.

Give an id to that paginator in template:

```<code><p-paginator #paginator ...></p-paginator>
</code>```

And use it in component:

```<code>import { Paginator } from 'primeng/paginator';

@ViewChild('paginator', { static: true }) paginator: Paginator

private updateCurrentPage(currentPage: number): void {
  setTimeout(() => this.paginator.changePage(currentPage));
}
</code>```

Title: PrimeNG Paginator set Page

Body:
You need to set the page manually. You can use Angular @ViewChild decorator to get access to PrimeNg Paginator component.

Give an id to that paginator in template:

<p-paginator #paginator ...></p-paginator>

And use it in component:

import { Paginator } from 'primeng/paginator';

@ViewChild('paginator', { static: true }) paginator: Paginator

private updateCurrentPage(currentPage: number): void {
  setTimeout(() => this.paginator.changePage(currentPage));
}


问:
R: Substituting missing values (NAs) with two different values
I might be overcomplicating things - would love to know if if there is an easier way to solve this. I have a data frame (df) with 5654 observations - 1332 are foreign-born, and 4322 Canada-born subjects.

The variable df$YR_IMM captures: "In what year did you come to live in Canada?"
See the following distribution of observations per immigration year table(df$YR_IMM) :

```<code>1920 1926 1928 1930 1939 1942 1944 1946 1947 1948 1949 1950 1951 1952 1953 1954
2    1    1    2    1    2    1    1    1    9    5    1    7   13    3    5
1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
10    5    8    6    6    1    5    1    6    3    7   16   18   12   15   13
1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986
10   17    8   18   25   16   15   12   16   27   13   16   11    9   17   16
1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003
24   21   31   36   26   30   26   24   22   30   29   26   47   52   53   28   9
</code>```

Naturally these are only foreign-born individuals (mean = 1985) - however, 348 foreign-borns are missing. There are a total of 4670 NAs that also include Canada-borns subjects.

How can I code these df$YR_IMM NAs in such a way that

```<code>348 (NA) --> 1985
4322(NA) --> 100
</code>```

Additionally, the status is given by df$Brthcoun with 0 = "born in Canada" and 1 = "born outside of Canada.

Hope this makes sense - thank you!

EDIT: This was the solution ->

df$YR_IMM[is.na(df$YR_IMM) & df$Brthcoun == 0] <- 100
df$YR_IMM[is.na(df$YR_IMM) & df$Brthcoun == 1] <- 1985

答:
Try the below code:

```<code>df$YR_IMM[is.na(df$YR_IMM) & df$Brthcoun == 0] <- 100
df$YR_IMM[is.na(df$YR_IMM) & df$Brthcoun == 1] <- 1985
</code>```

I hope this helps!

Body:
I might be overcomplicating things - would love to know if if there is an easier way to solve this. I have a data frame (df) with 5654 observations - 1332 are foreign-born, and 4322 Canada-born subjects.

The variable df$YR_IMM captures: "In what year did you come to live in Canada?"
See the following distribution of observations per immigration year table(df$YR_IMM) :

1920 1926 1928 1930 1939 1942 1944 1946 1947 1948 1949 1950 1951 1952 1953 1954
2    1    1    2    1    2    1    1    1    9    5    1    7   13    3    5
1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
10    5    8    6    6    1    5    1    6    3    7   16   18   12   15   13
1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986
10   17    8   18   25   16   15   12   16   27   13   16   11    9   17   16
1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003
24   21   31   36   26   30   26   24   22   30   29   26   47   52   53   28   9

Naturally these are only foreign-born individuals (mean = 1985) - however, 348 foreign-borns are missing. There are a total of 4670 NAs that also include Canada-borns subjects.

How can I code these df$YR_IMM NAs in such a way that

348 (NA) --> 1985
4322(NA) --> 100

Additionally, the status is given by df$Brthcoun with 0 = "born in Canada" and 1 = "born outside of Canada.

Hope this makes sense - thank you!

EDIT: This was the solution ->

df$YR_IMM[is.na(df$YR_IMM) & df$Brthcoun == 0] <- 100
df$YR_IMM[is.na(df$YR_IMM) & df$Brthcoun == 1] <- 1985

Body:
Try the below code:

df$YR_IMM[is.na(df$YR_IMM) & df$Brthcoun == 0] <- 100
df$YR_IMM[is.na(df$YR_IMM) & df$Brthcoun == 1] <- 1985

I hope this helps!


问:
How can I initialize this semaphore
I asked this question about multithreading in servlet, and many people suggest using a static variable.

If I set a static variable and I need to initialize it. For example public static Semaphore permits;

At first, I tried to initialize it in the init() method of a filter associated with the servlet:

```<code>public void init(FilterConfig conf) throws ServletException {
        // TODO Auto-generated method stub
    try{
            limit = Integer.parseInt(conf.getInitParameter("filterLimit"));
            permits = new Semaphore(limit);
    }catch(Exception ex){
            conf.getServletContext().log("Fail to set the parameter : permits.");
            throw new ServletException(ex.getMessage());
    }

}
</code>```

Then I thought that with so many threads, every threads executing the init() method will initialize the semaphore, it should be not working.

Then I tried to use a static initializer:

```<code>static{
        try{
            limit = Integer.parseInt(conf.getInitParameter("filterLimit"));
            permits = new Semaphore(limit);
        }catch(Exception ex){
            conf.getServletContext().log("Fail to set the parameter : permits.");
            throw new ServletException(ex.getMessage());
        }

 }
</code>```

But I cannot use the conf object as it is passed from the init() method. I want to get the limit number from web.xml, instead of hardcoding it. Any idea to solve this?

答:
Then I thought that with so many threads, every threads executing the init() method will initialize the semaphore, it should be not working.

I don't understand. Your init() method should be called by the Servlet container, only once. How are you using these filters / servlets? Is the Thread created within the servlet, or is it created outside the servlet?

If it's created inside the servlet, it should be fine to use a variable created in the init() method.

Title: How can I initialize this semaphore

Body:
I asked this question about multithreading in servlet, and many people suggest using a static variable.

If I set a static variable and I need to initialize it. For example public static Semaphore permits;

At first, I tried to initialize it in the init() method of a filter associated with the servlet:

public void init(FilterConfig conf) throws ServletException {
        // TODO Auto-generated method stub
    try{
            limit = Integer.parseInt(conf.getInitParameter("filterLimit"));
            permits = new Semaphore(limit);
    }catch(Exception ex){
            conf.getServletContext().log("Fail to set the parameter : permits.");
            throw new ServletException(ex.getMessage());
    }

}

Then I thought that with so many threads, every threads executing the init() method will initialize the semaphore, it should be not working.

Then I tried to use a static initializer:

static{
        try{
            limit = Integer.parseInt(conf.getInitParameter("filterLimit"));
            permits = new Semaphore(limit);
        }catch(Exception ex){
            conf.getServletContext().log("Fail to set the parameter : permits.");
            throw new ServletException(ex.getMessage());
        }

 }

But I cannot use the conf object as it is passed from the init() method. I want to get the limit number from web.xml, instead of hardcoding it. Any idea to solve this?


问:
Inspect hovered element in Chrome?
I am trying to view, through Chrome's developer tools, how tooltips are structured on a site. However, even when I am hovered over the item, when I "inspect element", nothing shows for the tooltip in the html. I know I can set the Style to :hover, but I still can't see the html or css of the tooltip.

Any ideas?

答:
Hit command-option-j to open the console. Click the window-looking button on the top right corner of the console to open the console in a different window.

Then, in the Chrome window, hover over the element that triggers the popover, hit command- however many times you need to focus on the console, then type debugger. That'll freeze the page; then you can inspect the element in the Elements tab.

Title: Inspect hovered element in Chrome?


问:
What is the time complexity for the given C++ code?
What is the time-complexity of the code fragment?

```<code>for (i = 0; i < N * N; i += N)
    k++;
</code>```

I am not sure if it is N^2 or N since N is added to i in each loop.

答:
The complexity of above program is O(n), as there is only one 'for' loop.

The order of nesting of 'for' loops provides a rough estimation of the worst case complexity.

(Please refer the comment from Cigien below for more information)

A rough estimation of worst-case complexity:

If there are 2 for-loops with one nested inside the other, then the complexity may become o(n^2).

If there are 3 nested loops, then the complexity may become O(n^3)

...

An example of O(n^2) complexity:

```<code>for ( i = 1; i < P ; i ++ ) {
    for ( j = 1; j < Q; j++ ) {
        // some simple statements only
    }
}
</code>```

An example of O(n^3) complexity:

```<code>for ( i = 1; i < P ; i ++ ) {
    for ( j = 1; j < Q; j++ ) {
        for ( k = 1; k < R; k++ ) {
            // some simple statements only
        }
    }
}
</code>```

Body:
What is the time-complexity of the code fragment?

for (i = 0; i < N * N; i += N)
    k++;

I am not sure if it is N^2 or N since N is added to i in each loop.

Body:
The complexity of above program is O(n), as there is only one 'for' loop.

The order of nesting of 'for' loops provides a rough estimation of the worst case complexity.

(Please refer the comment from Cigien below for more information)

A rough estimation of worst-case complexity:

If there are 2 for-loops with one nested inside the other, then the complexity may become o(n^2).

If there are 3 nested loops, then the complexity may become O(n^3)

...

An example of O(n^2) complexity:

for ( i = 1; i < P ; i ++ ) {
    for ( j = 1; j < Q; j++ ) {
        // some simple statements only
    }
}

An example of O(n^3) complexity:

for ( i = 1; i < P ; i ++ ) {
    for ( j = 1; j < Q; j++ ) {
        for ( k = 1; k < R; k++ ) {
            // some simple statements only
        }
    }
}


问:
Garbage collection for a simple python class
I am writing a python class like this:

```<code>class MyImageProcessor:
   def __init__ (self, image, metadata):
     self.image=image
     self.metadata=metadata
</code>```

Both image and metadata are objects of a class written by a
colleague. Now I need to  make sure there is no waste of memory.  I am thinking of defining a quit() method like this,

```<code>  def quit():
    self.image=None
    self.metadata=None
    import gc
    gc.collect()
</code>```

and suggest users to call quit() systematically. I would like to know whether this is the right way. In particular, do the instructions in quit() above guarantee that unused memories being well collected?

Alternatively, I could rename quit() to the build-in __exit__(), and suggest users to use the "with" syntax. But my question is
more about whether the instructions in quit() indeed fulfill the garbage collection work one would need in this situation.

Thank you for your help.

答:
Not sure if it make sense but to my logic you could

Use :

gc.get_count()

before and after

gc.collect()

to see if something has been removed.

what are count0, count1 and count2 values returned by the Python gc.get_count()

Body:
I am writing a python class like this:

class MyImageProcessor:
   def __init__ (self, image, metadata):
     self.image=image
     self.metadata=metadata

Both image and metadata are objects of a class written by a
colleague. Now I need to  make sure there is no waste of memory.  I am thinking of defining a quit() method like this,

  def quit():
    self.image=None
    self.metadata=None
    import gc
    gc.collect()

and suggest users to call quit() systematically. I would like to know whether this is the right way. In particular, do the instructions in quit() above guarantee that unused memories being well collected?

Alternatively, I could rename quit() to the build-in __exit__(), and suggest users to use the "with" syntax. But my question is
more about whether the instructions in quit() indeed fulfill the garbage collection work one would need in this situation.

Thank you for your help.


问:
Terraform - List to String to create the azure subscription list
I am creating a new custom Azure role and trying to pass all the subscription IDs to the assignable scope argument using the below code but I am having issues converting from list to string with the correct string format. Here is the role definition module doc - https://www.terraform.io/docs/providers/azurerm/r/role_definition.html

Appreciate any inputs or guidance!

```<code>locals {
 subscription_list  = formatlist("/subscriptions/%s", data.azurerm_subscriptions.all.subscriptions[*].subscription_id)
  quoted_subsciption_list = formatlist("%q", local.sub_list)
}
</code>```

When I use join function to convert this into a string using the below code,
join(",", local.quoted_subsciption_list)

I am getting the output as "\"/subscriptions/7yed1028-4525-4533-b608-fb74c2a9c1rr\",\"/subscriptions/7uef9fad-dabf-8icf-8379-a3df99e7613c\",

I want the output to be "/subscriptions/7yed1028-4525-4533-b608-fb74c2a9c1rr", "/subscriptions/7uef9fad-dabf-8icf-8379-a3df99e7613c".```
locals {
 subscription_list  = formatlist("/subscriptions/%s", data.azurerm_subscriptions.all.subscriptions[*].subscription_id)
  quoted_subsciption_list = formatlist("%q", local.sub_list)
}</p>

```When I use join function to convert this into a string using the below code,
```join(",", local.quoted_subsciption_list)```

I am getting the output as **"\"/subscriptions/7yed1028-4525-4533-b608-fb74c2a9c1rr\",\"/subscriptions/7uef9fad-dabf-8icf-8379-a3df99e7613c\",**

I want the output to be **"/subscriptions/7yed1028-4525-4533-b608-fb74c2a9c1rr", "/subscriptions/7uef9fad-dabf-8icf-8379-a3df99e7613c".**
```

答:
local.subscription_list is already list(string) which is what azurerm_role_definition's assignable_scopes needs, so you can do this in your azurerm_role_definition resource block:

```<code>assignable_scopes = local.subsciption_list
</code>```

Body:
I am creating a new custom Azure role and trying to pass all the subscription IDs to the assignable scope argument using the below code but I am having issues converting from list to string with the correct string format. Here is the role definition module doc - https://www.terraform.io/docs/providers/azurerm/r/role_definition.html

Appreciate any inputs or guidance!

locals {
 subscription_list  = formatlist("/subscriptions/%s", data.azurerm_subscriptions.all.subscriptions[*].subscription_id)
  quoted_subsciption_list = formatlist("%q", local.sub_list)
}

When I use join function to convert this into a string using the below code,
join(",", local.quoted_subsciption_list)

I am getting the output as "\"/subscriptions/7yed1028-4525-4533-b608-fb74c2a9c1rr\",\"/subscriptions/7uef9fad-dabf-8icf-8379-a3df99e7613c\",

I want the output to be "/subscriptions/7yed1028-4525-4533-b608-fb74c2a9c1rr", "/subscriptions/7uef9fad-dabf-8icf-8379-a3df99e7613c".```
locals {
 subscription_list  = formatlist("/subscriptions/%s", data.azurerm_subscriptions.all.subscriptions[*].subscription_id)
  quoted_subsciption_list = formatlist("%q", local.sub_list)
}</p>

<pre><code>When I use join function to convert this into a string using the below code,
```join(",", local.quoted_subsciption_list)```

I am getting the output as **"\"/subscriptions/7yed1028-4525-4533-b608-fb74c2a9c1rr\",\"/subscriptions/7uef9fad-dabf-8icf-8379-a3df99e7613c\",**

I want the output to be **"/subscriptions/7yed1028-4525-4533-b608-fb74c2a9c1rr", "/subscriptions/7uef9fad-dabf-8icf-8379-a3df99e7613c".**

Body:
local.subscription_list is already list(string) which is what azurerm_role_definition's assignable_scopes needs, so you can do this in your azurerm_role_definition resource block:

assignable_scopes = local.subsciption_list


问:
Mauritus national flag problem
I've made a solution for the Dutch national flag problem already.

But this time, I want to try something more difficult: the Mauritus national flag problem - 4 colours, instead of 3. Any suggestions for an effective algorithm?

Basically, The Mauritius National Flag Problem focuses on how you would be able to sort the given list of pairs based on the order of colors in the Mauritius National Flag (Red, Blue, Yellow, Green). And the numbers must be sorted in ascending order too.

Scheme Programming Sample Input:

( (R . 3) (G . 6) (Y . 1) (B . 2) (Y . 7) (G . 3) (R . 1) (B . 8) )

Output:

( (R . 1) (R . 3) (B . 2) (B . 8) (Y . 1) (Y . 7) (G . 3) (G . 6) )

答:
```<code>function sort3(a:string[]):void{
    let low = 0;
    let mid1 = 0;
    let mid2 = 0;
    let high = a.length - 1;
    while(mid2<=high){
        switch(a[mid2]){
            case '0': [a[mid2],a[low]] = [a[low],a[mid2]];
                    low++;
                    if(mid1<low)
                    mid1++;
                    if(mid2<mid1)
                    mid2++;
                    break;

            case '1': [a[mid2],a[mid1]] = [a[mid1],a[mid2]];
                    mid1++;
                    mid2++;
                    break;

            case '2':mid2++
                   break;

            case '3':[a[mid2],a[high]] = [a[high],a[mid2]];
                    high--;
        }
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Mauritus national flag problem


问:
To integrate ant-design with next.js
I am trying to integrate ant-design with next.js. I have installed next in a default node project instead of using create-next-app.

I have followed zeit example of integrating next with antd.

My package.json file is

```<code>{
  "name": "crowd-funding",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "next dev"
  },
  "author": "Thananjaya Chakravarthy S",
  "license": "ISC",
  "dependencies": {
    "@zeit/next-css": "^1.0.1",
    "antd": "^3.13.6",
    "next": "^4.1.4",
    "react": "^16.8.3",
    "react-dom": "^16.8.3",

  },
  "devDependencies": {
    "babel-plugin-import": "^1.11.0"
  }
}
</code>```

And my .babelrc file is

```<code>{
    "presets": ["next/babel"],
    "plugins": [
      ["import", { "libraryName": "antd", "style": "css" }]
    ],
}
</code>```

But I am getting an error like You may need an appropriate loader to handle this file type, pointing towards the path /node_modules/antd/dist/antd.css.

How to resolve this?

答:
Create styles.css file

in styles.css:

@import "~antd/dist/antd.css";
```

<p>in _app.js:</p>

<pre class="lang-js prettyprint-override"><code>import "./styles.css";
</code>```

now you can use ant design components anywhere in the project

Title: To integrate ant-design with next.js

Body:
I am trying to integrate ant-design with next.js. I have installed next in a default node project instead of using create-next-app.

I have followed zeit example of integrating next with antd.

My package.json file is

{
  "name": "crowd-funding",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "next dev"
  },
  "author": "Thananjaya Chakravarthy S",
  "license": "ISC",
  "dependencies": {
    "@zeit/next-css": "^1.0.1",
    "antd": "^3.13.6",
    "next": "^4.1.4",
    "react": "^16.8.3",
    "react-dom": "^16.8.3",

  },
  "devDependencies": {
    "babel-plugin-import": "^1.11.0"
  }
}

And my .babelrc file is

{
    "presets": ["next/babel"],
    "plugins": [
      ["import", { "libraryName": "antd", "style": "css" }]
    ],
}

But I am getting an error like You may need an appropriate loader to handle this file type, pointing towards the path /node_modules/antd/dist/antd.css.

How to resolve this?

Body:
Create styles.css file

in styles.css:

@import "~antd/dist/antd.css";

in _app.js:

import "./styles.css";

now you can use ant design components anywhere in the project


问:
Generic collection support in WCF
Does WCF support generic collections?
I looked at the proxy object, and it seems to generate object array from a generic list collection.

Thanks

答: Using generics are fine as long as you are using WCF at both ends. If you haven't already; you must carefully consider the scenarios where a non-wcf client might need to use your services.</p>

OwnerDisplayName: Jeremy Thomson

Title: Generic collection support in WCF

LastEditorDisplayName: Daniel Auger

OwnerDisplayName: Hemant