问:
How does the indexing work to find MIN() or MAX() value for a specific indexed column and sort a table in following scenario?
Following is the text from MySQL Documentation :

To find the MIN() or MAX() value for a specific indexed column
  key_col. This is optimized by a preprocessor that checks whether you
  are using WHERE key_part_N = constant on all key parts that occur
  before key_col in the index. In this case, MySQL does a single key
  lookup for each MIN() or MAX() expression and replaces it with a
  constant. If all expressions are replaced with constants, the query
  returns at once. For example:

```<code>SELECT MIN(key_part2),MAX(key_part2)
  FROM tbl_name WHERE key_part1=10;
</code>```

To sort or group a table if the sorting or grouping is done on a
  leftmost prefix of a usable index (for example, ORDER BY key_part1,
  key_part2). If all key parts are followed by DESC, the key is read in
  reverse order.

In some cases, a query can be optimized to retrieve values without
  consulting the data rows. (An index that provides all the necessary
  results for a query is called a covering index.) If a query uses from
  a table only columns that are included in some index, the selected
  values can be retrieved from the index tree for greater speed:

```<code>SELECT key_part3 FROM tbl_name
  WHERE key_part1=1
</code>```

I'm not at all able to understand these points and the respective code from the MySQL Documentation.

Someone please make the things easy in order to clarify the things to make me understand.

I am not asking what is Indexing and how does work, etc. etc.

I just want to understand what these sentences are trying to say and what's happening out there in the code?

What are key_par_N and what's the purpose of using them here?

What does actually mean by the term key part in this context?

What does mean by all key parts that occur before key_col in the index?

Where is the column key_col of which we are supposed to fine MIN() and MAX() values (See the first line : To find the MIN() or MAX() value for a specific indexed column key_col.)?

Someone please make me clear everything.

Note : I've already seen this question which is asking the same thing but it has received a generalized answer which is not specific to the explanation and code given in the manual. So, I'm asking this question to get precise and specific answer. So, please don't mark my question duplicate.

答:
Imagine a list of people names.  And you want to find the first and last (alphabetically) "Smith"  How would you do that on paper?  You would flip to the beginning of the Smiths to find Aaron, then flip to the end of the Smiths to find Ziggy.

What about a table with INDEX(lastname, firstname) and the SQL:

```<code>SELECT MIN(firstname), MAX(firstname)
    FROM names
    WHERE lastname = 'Smith';
</code>```

It would work pretty much the same way.

(I find "lastname" more user-friendly than "key_part_1".)

Many Index issues can be deduced by thinking about how it would be done with paper or a Rolodex or a Library "card catalog" (if you are old enough to remember such).

My Index Cookbook does not happen to discuss that, but it provides other insights into indexing.

To generalize on the "key_part" and max and min...  If you can visualize flipping to a list of things and reaching to the first (for min) or last (for max), and it will be the 'right' answer, then the equivalent INDEX will probably work that way.

Here is a common place where max and min get tripped up.  Suppose some of the names are marked as "deleted" or "deceased" (or whatever), and you don't want them.  Now it is not as simple a finding the first and last Smith.  Rather you would need to go to the start and end and scan.  This is a case where the following code is not well optimized:

```<code>SELECT MIN(firstname), MAX(firstname)
    FROM names
    WHERE lastname = 'Smith'
      AND deleted = 0;     -- This is a monkey wrench
</code>```

So, INDEX(lastname, firstname) will not help much.

OTOH, INDEX(deleted, lastname, firstname) will help.  However this is unrealistic for a paper list, and clumsy for a Rolodex.  For a paper list, you would be erasing names from where they are and moving them to the end of the list, which contains the deleted people.  With a Rolodex, you pull a card and move it to another spot.  Guess what -- that is what MySQL has to do in the index when you say

```<code> UPDATE list
     SET deleted = 1
     WHERE lastname = 'Smith'
       AND firstname = 'John';
</code>```

Body:
Following is the text from MySQL Documentation :

To find the MIN() or MAX() value for a specific indexed column
  key_col. This is optimized by a preprocessor that checks whether you
  are using WHERE key_part_N = constant on all key parts that occur
  before key_col in the index. In this case, MySQL does a single key
  lookup for each MIN() or MAX() expression and replaces it with a
  constant. If all expressions are replaced with constants, the query
  returns at once. For example:

SELECT MIN(key_part2),MAX(key_part2)
  FROM tbl_name WHERE key_part1=10;

To sort or group a table if the sorting or grouping is done on a
  leftmost prefix of a usable index (for example, ORDER BY key_part1,
  key_part2). If all key parts are followed by DESC, the key is read in
  reverse order.

In some cases, a query can be optimized to retrieve values without
  consulting the data rows. (An index that provides all the necessary
  results for a query is called a covering index.) If a query uses from
  a table only columns that are included in some index, the selected
  values can be retrieved from the index tree for greater speed:

SELECT key_part3 FROM tbl_name
  WHERE key_part1=1

I'm not at all able to understand these points and the respective code from the MySQL Documentation.

Someone please make the things easy in order to clarify the things to make me understand.

I am not asking what is Indexing and how does work, etc. etc.

I just want to understand what these sentences are trying to say and what's happening out there in the code?

What are key_par_N and what's the purpose of using them here?

What does actually mean by the term key part in this context?

What does mean by all key parts that occur before key_col in the index?

Where is the column key_col of which we are supposed to fine MIN() and MAX() values (See the first line : To find the MIN() or MAX() value for a specific indexed column key_col.)?

Someone please make me clear everything.

Note : I've already seen this question which is asking the same thing but it has received a generalized answer which is not specific to the explanation and code given in the manual. So, I'm asking this question to get precise and specific answer. So, please don't mark my question duplicate.

Body:
Imagine a list of people names.  And you want to find the first and last (alphabetically) "Smith"  How would you do that on paper?  You would flip to the beginning of the Smiths to find Aaron, then flip to the end of the Smiths to find Ziggy.

What about a table with INDEX(lastname, firstname) and the SQL:

SELECT MIN(firstname), MAX(firstname)
    FROM names
    WHERE lastname = 'Smith';

It would work pretty much the same way.

(I find "lastname" more user-friendly than "key_part_1".)

Many Index issues can be deduced by thinking about how it would be done with paper or a Rolodex or a Library "card catalog" (if you are old enough to remember such).

My Index Cookbook does not happen to discuss that, but it provides other insights into indexing.

To generalize on the "key_part" and max and min...  If you can visualize flipping to a list of things and reaching to the first (for min) or last (for max), and it will be the 'right' answer, then the equivalent INDEX will probably work that way.

Here is a common place where max and min get tripped up.  Suppose some of the names are marked as "deleted" or "deceased" (or whatever), and you don't want them.  Now it is not as simple a finding the first and last Smith.  Rather you would need to go to the start and end and scan.  This is a case where the following code is not well optimized:

SELECT MIN(firstname), MAX(firstname)
    FROM names
    WHERE lastname = 'Smith'
      AND deleted = 0;     -- This is a monkey wrench

So, INDEX(lastname, firstname) will not help much.

OTOH, INDEX(deleted, lastname, firstname) will help.  However this is unrealistic for a paper list, and clumsy for a Rolodex.  For a paper list, you would be erasing names from where they are and moving them to the end of the list, which contains the deleted people.  With a Rolodex, you pull a card and move it to another spot.  Guess what -- that is what MySQL has to do in the index when you say

 UPDATE list
     SET deleted = 1
     WHERE lastname = 'Smith'
       AND firstname = 'John';


来源: stackexchange

问:
Installing Java libraries
As I'm quite new to Java, I would like to know the proper procedure of installing new libraries (those that are no available in my linux dist repositories).
Where should I place them? and how to install them?
For instance, I downloaded openCsv (http://opencsv.sourceforge.net/), and I have no idea how to install it.</p>

答:
You could use Maven to manage any dependencies to those libraries.
Maven will automatically download all needed JAR files and put them in a local repository (the location is configurable).

This makes upgrading to new versions of various libraries very easy as you just declare the version you want and Maven does the rest.

Beware: Maven is something to get used to and the initial learning curve is steep.
The rewards come if you have everything set up properly and maven takes care of compiling, packaging, distribution, site creation, release management etc. etc. etc.

ContentLicense: CC BY-SA 3.0

Title: Installing Java libraries

ContentLicense: CC BY-SA 2.5


问:
What is the difference between NEVPNManager and NETunnelProvider?
I'm trying to find out what's the difference between the two. I get the NETunnel is for ssl-vpn's and custom vpn's, but can they still be used interchangeably?
Can I use NETunnel to connect to an IPSec VPN?

My main need is to set my dns for the VPN, but I can't seem to do it with NEVPN

答:
NEVPNManager is designed to control VPNs based on one of the built-in VPN plug-in types.  NETunnelProviderManager is designed to control custom VPN plug-ins (and requires a special entitlement for those plug-ins).

Normally, with most VPNs, you would change the DNS on the other end of the VPN tunnel, by having the actual VPN server send a list of DNS server IPs to the client, this making that a server configuration detail, rather than something the app itself would need to control.  NETunnelProviderManager offers that ability because it is designed to handle arbitrary VPN types that might not work that way.


问:
C# script task in SSIS

try
{
    DirectoryInfo d = new DirectoryInfo(@"\\filepath\format");
    foreach (var f in d.GetFiles("*.csv"))
    {
        File.Copy(f.FullName.ToString(), @"filepath\out\", true);
    };

    Dts.TaskResult = (int)ScriptResults.Success;
}
```

When i am trying the above script, i am getting the below error message

File.Copy error - C# - IOException The filename, directory name, or volume label syntax is incorrect

答:
You need to copy to a file rather than a folder. The following will work:</p>

```<code>try
{
    DirectoryInfo d = new DirectoryInfo(@"\\filepath\format");
    foreach (var f in d.GetFiles("*.csv"))
    {
        File.Copy(f.FullName.ToString(), @"filepath\out\" + Path.GetFileName(f.FullName), true);
    };

    Dts.TaskResult = (int)ScriptResults.Success;
}
</code>```

Title: C# script task in SSIS

Body:
try
{
    DirectoryInfo d = new DirectoryInfo(@"\\filepath\format");
    foreach (var f in d.GetFiles("*.csv"))
    {
        File.Copy(f.FullName.ToString(), @"filepath\out\", true);
    };

    Dts.TaskResult = (int)ScriptResults.Success;
}

When i am trying the above script, i am getting the below error message

File.Copy error - C# - IOException The filename, directory name, or volume label syntax is incorrect

Body:
You need to copy to a file rather than a folder. The following will work:

try
{
    DirectoryInfo d = new DirectoryInfo(@"\\filepath\format");
    foreach (var f in d.GetFiles("*.csv"))
    {
        File.Copy(f.FullName.ToString(), @"filepath\out\" + Path.GetFileName(f.FullName), true);
    };

    Dts.TaskResult = (int)ScriptResults.Success;
}


问:
What is the correct type for returning a C99 `bool` to Rust via the FFI?
A colleague and I have been scratching our heads over how to return a bool from <stdbool.h> (a.k.a. _Bool) back to Rust via the FFI.

We have our C99 code we want to use from Rust:

bool
myfunc(void) {
   ...
}
```

<p>We let Rust know about <code>myfunc</code> using an <code>extern C</code> block:</p>

```extern "C" {
    fn myfunc() -> T;
}
```

What concrete type should T be?

Rust doesn't have a c_bool in the libc crate, and if you search the internet, you will find various GitHub issues and RFCs where people discuss this, but don't really come to any consensus as to what is both correct and portable:

https://github.com/rust-lang/rfcs/issues/1982#issuecomment-297534238

https://github.com/rust-lang/rust/issues/14608

https://github.com/rust-lang/rfcs/issues/992

https://github.com/rust-lang/rust/pull/46156

As far as I can gather:

The size of a bool in C99 is undefined other than the fact it must be at least large enough to store true (1) and false (0). In other words, at least one bit long.

It could even be one bit wide.

Its size might be ABI defined.

This comment suggests that if a C99 bool is passed into a function as a parameter or out of a function as the return value, and the bool is smaller than a C int then it is promoted to the same size as an int. Under this scenario, we can tell Rust T is u32.

All right, but what if (for some reason) a C99 bool is 64 bits wide? Is u32 still safe? Perhaps under this scenario we truncate the 4 most significant bytes, which would be fine, since the 4 least significant bytes are more than enough to represent true and false.

Is my reasoning correct? Until Rust gets a libc::c_bool, what would you use for T and why is it safe and portable for all possible sizes of a C99 bool (>=1 bit)?

答:
As of 2018-02-01, the size of Rust's bool is officially the same as C's _Bool.

This means that bool is the correct type to use in FFI.

The rest of this answer applies to versions of Rust before the official decision was made

Until Rust gets a libc::c_bool, what would you use for T and why is it safe and portable for all possible sizes of a C99 bool (>=1 bit)?

As you've already linked to, the official answer is still "to be determined". That means that the only possibility that is guaranteed to be correct is: nothing.

That's right, as sad as it may be. The only truly safe thing would be to convert your bool to a known, fixed-size integral type, such as u8, for the purpose of FFI. That means you need to marshal it on both sides.

Practically, I'd keep using bool in my FFI code. As people have pointed out, it magically lines up on all the platforms that are in wide use at the moment. If the language decides to make bool FFI compatible, you are good to go. If they decide something else, I'd be highly surprised if they didn't introduce a lint to allow us to catch the errors quickly.

See also:

Is bool guaranteed to be 1 byte?

Body:
A colleague and I have been scratching our heads over how to return a bool from <stdbool.h> (a.k.a. _Bool) back to Rust via the FFI.

We have our C99 code we want to use from Rust:

bool
myfunc(void) {
   ...
}

We let Rust know about myfunc using an extern C block:

extern "C" {
    fn myfunc() -> T;
}

What concrete type should T be?

Rust doesn't have a c_bool in the libc crate, and if you search the internet, you will find various GitHub issues and RFCs where people discuss this, but don't really come to any consensus as to what is both correct and portable:

https://github.com/rust-lang/rfcs/issues/1982#issuecomment-297534238

https://github.com/rust-lang/rust/issues/14608

https://github.com/rust-lang/rfcs/issues/992

https://github.com/rust-lang/rust/pull/46156

As far as I can gather:

The size of a bool in C99 is undefined other than the fact it must be at least large enough to store true (1) and false (0). In other words, at least one bit long.

It could even be one bit wide.

Its size might be ABI defined.

This comment suggests that if a C99 bool is passed into a function as a parameter or out of a function as the return value, and the bool is smaller than a C int then it is promoted to the same size as an int. Under this scenario, we can tell Rust T is u32.

All right, but what if (for some reason) a C99 bool is 64 bits wide? Is u32 still safe? Perhaps under this scenario we truncate the 4 most significant bytes, which would be fine, since the 4 least significant bytes are more than enough to represent true and false.

Is my reasoning correct? Until Rust gets a libc::c_bool, what would you use for T and why is it safe and portable for all possible sizes of a C99 bool (>=1 bit)?

ContentLicense: CC BY-SA 4.0


问:
How to create an Austrian flag in Python?
I am trying to create the Austrian flag using turtle graphics. Here is my sample code:

```<code> import turtle

def rectangle(t,wdth,ht,c):
 t.fillcolor(c)
 t.begin_fill()
 for i in range(2):
    t.forward(ht)
    t.left(90)
    t.forward(wdth)
    t.left(90)
 t.end_fill()

def rectangle2(t,wdth,ht,c):
 t.fillcolor(c)
 t.begin_fill()
 for i in range(2):
    t.forward(ht)
    t.left(90)
    t.forward(wdth)
    t.left(90)
 t.end_fill()

def flag():
 flag = turtle.Turtle()
 rectangle(flag,50,250,"red")

turtle.up()

def flag2():
 flag= turtle.Turtle()
 rectangle(flag, 50, 250, "white")

flag()
flag2()
turtle.done()
</code>```

My code creates a single red rectangle, which I intended to be the bottom third of the flag. I wanted the turtle to move upward and become the middle portion of the Austrian flag which is a white rectangle.

My code creates the red rectangle as intended, and then the turtle recolors the red rectangle white. This leaves me with a single white rectangle instead of a red rectangle and a white rectangle on top of it.

答:
EDIT: I replaced width with height as @cdlane corretly pointed out in the comment.

Use forward/left/right or goto(x, y) to move turtle in correct place before you draw white rectangle.

```<code>import turtle

def rectangle(height, width, color):
    turtle.fillcolor(color)
    turtle.begin_fill()
    for _ in range(2):
        turtle.forward(width)
        turtle.left(90)
        turtle.forward(height)
        turtle.left(90)
    turtle.end_fill()

rectangle(50, 250, "red") # bottom red

turtle.left(90)     #
turtle.forward(50)  # go 50 pixel up
turtle.right(90)    #

rectangle(50, 250, "white") # middle white

turtle.left(90)     #
turtle.forward(50)  # go 50 pixel up
turtle.right(90)    #

rectangle(50, 250, "red") # top red

turtle.done()
</code>```

Body:
I am trying to create the Austrian flag using turtle graphics. Here is my sample code:

 import turtle

def rectangle(t,wdth,ht,c):
 t.fillcolor(c)
 t.begin_fill()
 for i in range(2):
    t.forward(ht)
    t.left(90)
    t.forward(wdth)
    t.left(90)
 t.end_fill()

def rectangle2(t,wdth,ht,c):
 t.fillcolor(c)
 t.begin_fill()
 for i in range(2):
    t.forward(ht)
    t.left(90)
    t.forward(wdth)
    t.left(90)
 t.end_fill()

def flag():
 flag = turtle.Turtle()
 rectangle(flag,50,250,"red")

turtle.up()

def flag2():
 flag= turtle.Turtle()
 rectangle(flag, 50, 250, "white")

flag()
flag2()
turtle.done()

My code creates a single red rectangle, which I intended to be the bottom third of the flag. I wanted the turtle to move upward and become the middle portion of the Austrian flag which is a white rectangle.

My code creates the red rectangle as intended, and then the turtle recolors the red rectangle white. This leaves me with a single white rectangle instead of a red rectangle and a white rectangle on top of it.

Body:
EDIT: I replaced width with height as @cdlane corretly pointed out in the comment.

Use forward/left/right or goto(x, y) to move turtle in correct place before you draw white rectangle.

import turtle

def rectangle(height, width, color):
    turtle.fillcolor(color)
    turtle.begin_fill()
    for _ in range(2):
        turtle.forward(width)
        turtle.left(90)
        turtle.forward(height)
        turtle.left(90)
    turtle.end_fill()

rectangle(50, 250, "red") # bottom red

turtle.left(90)     #
turtle.forward(50)  # go 50 pixel up
turtle.right(90)    #

rectangle(50, 250, "white") # middle white

turtle.left(90)     #
turtle.forward(50)  # go 50 pixel up
turtle.right(90)    #

rectangle(50, 250, "red") # top red

turtle.done()


Body:
I want to replace data.frame using specified data set

> test_data
     support count
1 0.01235235   663
2 0.01373104   737
3 0.01393598   748
4 0.01265045   679
5 0.01548236   831
6 0.01565004   840
> replace_support
           2            3            4            6
-0.008884196 -0.007991622 -0.011675116 -0.013086012

names of replace_support corresponds with row name of test_data
my expect is replace the column support

     support count
1 0.01235235   663
2 -0.008884196   737
3 -0.007991622   748
4 -0.011675116   679
5 0.01548236   831
6 -0.013086012   840

hare are the example data

test_data <- structure(list(support = c(0.0123523493684093, 0.0137310429630734,
0.0139359839028207, 0.0126504452807691, 0.0154823564481872, 0.0156500353988896
), count = c(663, 737, 748, 679, 831, 840)), .Names = c("support",
"count"), row.names = c(NA, 6L), class = "data.frame")

replace_support <- structure(c(-0.00888419577036815, -0.00799162193023339, -0.0116751160488589,
-0.0130860121134779), .Names = c("2", "3", "4", "6"))

Body:
How about:

test_data$support[as.integer(names(replace_support))] <- replace_support

test_data
#>        support count
#> 1  0.012352349   663
#> 2 -0.008884196   737
#> 3 -0.007991622   748
#> 4 -0.011675116   679
#> 5  0.015482356   831
#> 6 -0.013086012   840


问:
Haskell Lambda Alpha Equivalence
I am trying to  write down an alpha equivalence function in Haskell for lambda.

data Expr = App Expr Expr | Lam Int Expr | Var Int  deriving (Show,Eq)

I've read some online resources but I can't transform them into code.
Thank you

答:
So two expressions are alpha equivalent if you can turn one into the other by renaming variables. So how could we capture this? There are two main ways:

Keep track of which variable names must correspond to one another in the two expressions.

(Explicitly or implicitly) convert into a form where instead of variable names, the number of the enclosing scope is used.

Let’s go for the first one

```<code>-- helper functions for association lists
type Alist a = [(a,a)]
assoc, rassoc :: Eq a => a -> Alist a -> a
assoc x ((a,b):ps) = if x == a then b else assoc x ps
rassoc x = assoc x . map (\(a,b) -> (b,a))
acons a b l = (a,b):l

(=*=) :: Expr -> Expr -> Bool
a =*= b = eq [] a b where
  eq l (Lam n x) (Lam m y) = eq (acons n m l) x y
  eq l (Var n) (Var m) = assoc n l == m && n == rassoc m l
  eq l (App f u) (App g v) = eq l f g && eq l u v
  eq l _ _ = False
</code>```

The only real subtlety here is the case of comparing variables. To check that x and y are alpha equivalent we need to check that the binding for x corresponds to a binding of y AND the binding for y corresponds to a binding for x. Otherwise we might say that \x.\y.x is alpha equivalent to \y.\y.y.

It’s also worth noting that malformed expressions will result in match failures.

Here’s how to implicitly do the second option:

```<code>varN :: Eq a => a -> [a] -> Int
varN a xs = v 0 xs where
  v n (x:xs) = if a == x then n else v (n+1) xs

a =*= b = eq [] [] a b in where
  eq k l (Lam n x) (Lam m y) = eq (n:k) (m:l) x y
  eq k l (Var n) (Var m) = varN n k == varN m l
  eq k l (App f u) (App g v) = eq k l f g && eq k l u v
  eq k l _ _ = False
</code>```

Hopefully you can see that these are equivalent

Title: Haskell Lambda Alpha Equivalence

Body:
So two expressions are alpha equivalent if you can turn one into the other by renaming variables. So how could we capture this? There are two main ways:

Keep track of which variable names must correspond to one another in the two expressions.

(Explicitly or implicitly) convert into a form where instead of variable names, the number of the enclosing scope is used.

Let’s go for the first one

-- helper functions for association lists
type Alist a = [(a,a)]
assoc, rassoc :: Eq a => a -> Alist a -> a
assoc x ((a,b):ps) = if x == a then b else assoc x ps
rassoc x = assoc x . map (\(a,b) -> (b,a))
acons a b l = (a,b):l

(=*=) :: Expr -> Expr -> Bool
a =*= b = eq [] a b where
  eq l (Lam n x) (Lam m y) = eq (acons n m l) x y
  eq l (Var n) (Var m) = assoc n l == m && n == rassoc m l
  eq l (App f u) (App g v) = eq l f g && eq l u v
  eq l _ _ = False

The only real subtlety here is the case of comparing variables. To check that x and y are alpha equivalent we need to check that the binding for x corresponds to a binding of y AND the binding for y corresponds to a binding for x. Otherwise we might say that \x.\y.x is alpha equivalent to \y.\y.y.

It’s also worth noting that malformed expressions will result in match failures.

Here’s how to implicitly do the second option:

varN :: Eq a => a -> [a] -> Int
varN a xs = v 0 xs where
  v n (x:xs) = if a == x then n else v (n+1) xs

a =*= b = eq [] [] a b in where
  eq k l (Lam n x) (Lam m y) = eq (n:k) (m:l) x y
  eq k l (Var n) (Var m) = varN n k == varN m l
  eq k l (App f u) (App g v) = eq k l f g && eq k l u v
  eq k l _ _ = False

Hopefully you can see that these are equivalent


答:
Three thoughts: you're making it harder than necessary; you need to lookup the Austrian flag in Wikipedia to get the proper aspect ratio; there's more than one way to do it.

First, let's simplify and clean up your code:

```<code>from turtle import Turtle, Screen

HEIGHT = 120
WIDTH = 3 * HEIGHT / 2

def rectangle(turtle, width, height, color):
    turtle.fillcolor(color)

    turtle.begin_fill()
    for _ in range(2):
        turtle.forward(width)
        turtle.left(90)
        turtle.forward(height)
        turtle.left(90)
    turtle.end_fill()

def flag(turtle):
    turtle.pencolor('black')
    rectangle(turtle, WIDTH, HEIGHT, 'white')
    rectangle(turtle, WIDTH, HEIGHT / 3, 'red')
    turtle.sety(turtle.ycor() + 2 * HEIGHT / 3)
    rectangle(turtle, WIDTH, HEIGHT / 3, 'red')

yertle = Turtle(visible=False)

screen = Screen()

flag(yertle)

screen.mainloop()
</code>```

But for blocks of color like this, I prefer stamping to drawing:

```<code>from turtle import Turtle, Screen

HEIGHT = 120
WIDTH = 3 * HEIGHT / 2

STAMP_SIZE = 20

def flag(turtle, width, height):
    turtle.penup()

    turtle.color('black', 'white')
    turtle.shapesize(height / STAMP_SIZE, width / STAMP_SIZE)
    turtle.stamp()

    turtle.color('black', 'red')
    turtle.sety(turtle.ycor() - height / 3)
    turtle.shapesize(height / 3 / STAMP_SIZE, width / STAMP_SIZE)
    turtle.stamp()

    turtle.sety(turtle.ycor() + 2 * height / 3)
    turtle.stamp()

yertle = Turtle('square', visible=False)

screen = Screen()

flag(yertle, WIDTH, HEIGHT)

screen.mainloop()
</code>```

And finally, let's reduce it to really simple turtle logic:

```<code>from turtle import Turtle, Screen

import tkinter as _
_.ROUND = _.BUTT

HEIGHT = 120
WIDTH = 3 * HEIGHT / 2

def flag(turtle, width, height):
    turtle.pensize(height)
    turtle.color('red')
    turtle.forward(width)

    turtle.pensize(height / 3)
    turtle.color('white')
    turtle.backward(width)

yertle = Turtle(visible=False)

screen = Screen()
screen.bgcolor('black')

flag(yertle, WIDTH, HEIGHT)

screen.mainloop()
</code>```

Title: How to create an Austrian flag in Python?

Body:
Three thoughts: you're making it harder than necessary; you need to lookup the Austrian flag in Wikipedia to get the proper aspect ratio; there's more than one way to do it.

First, let's simplify and clean up your code:

from turtle import Turtle, Screen

HEIGHT = 120
WIDTH = 3 * HEIGHT / 2

def rectangle(turtle, width, height, color):
    turtle.fillcolor(color)

    turtle.begin_fill()
    for _ in range(2):
        turtle.forward(width)
        turtle.left(90)
        turtle.forward(height)
        turtle.left(90)
    turtle.end_fill()

def flag(turtle):
    turtle.pencolor('black')
    rectangle(turtle, WIDTH, HEIGHT, 'white')
    rectangle(turtle, WIDTH, HEIGHT / 3, 'red')
    turtle.sety(turtle.ycor() + 2 * HEIGHT / 3)
    rectangle(turtle, WIDTH, HEIGHT / 3, 'red')

yertle = Turtle(visible=False)

screen = Screen()

flag(yertle)

screen.mainloop()

But for blocks of color like this, I prefer stamping to drawing:

from turtle import Turtle, Screen

HEIGHT = 120
WIDTH = 3 * HEIGHT / 2

STAMP_SIZE = 20

def flag(turtle, width, height):
    turtle.penup()

    turtle.color('black', 'white')
    turtle.shapesize(height / STAMP_SIZE, width / STAMP_SIZE)
    turtle.stamp()

    turtle.color('black', 'red')
    turtle.sety(turtle.ycor() - height / 3)
    turtle.shapesize(height / 3 / STAMP_SIZE, width / STAMP_SIZE)
    turtle.stamp()

    turtle.sety(turtle.ycor() + 2 * height / 3)
    turtle.stamp()

yertle = Turtle('square', visible=False)

screen = Screen()

flag(yertle, WIDTH, HEIGHT)

screen.mainloop()

And finally, let's reduce it to really simple turtle logic:

from turtle import Turtle, Screen

import tkinter as _
_.ROUND = _.BUTT

HEIGHT = 120
WIDTH = 3 * HEIGHT / 2

def flag(turtle, width, height):
    turtle.pensize(height)
    turtle.color('red')
    turtle.forward(width)

    turtle.pensize(height / 3)
    turtle.color('white')
    turtle.backward(width)

yertle = Turtle(visible=False)

screen = Screen()
screen.bgcolor('black')

flag(yertle, WIDTH, HEIGHT)

screen.mainloop()


问:
Connect to Amazon RDS Postgresql with IAM Role
I try to give my EC2 instance access to my AWS RDS Postgresql database via IAM.

First, I've created a policy:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "rds:connect"
            ],
            "Resource": [
                "arn:aws:rds:eu-west-1:824224273455:db:instance-name/db-name"
            ]
        }
    ]
}
</code>```

After that I attached this policy to a role, which I attached to this specific EC2-instance. Everything seems to be fine till now.

When ssh to that specific EC2 instance and try to connect to the database, psql still prompts for a password.

Anyone knows how to accomplish it that I can connect without needing to use a password?

答:
This is not possible.

AWS Identity and Access Management (IAM) is used to grant permissions for the RDS service (eg creating, backing up and deleting clusters). However, it cannot be used to grant login access to an Amazon RDS PostgreSQL database. Instead, use normal Users defined within PostgreSQL.

Such access is only available for MySQL and Aurora.

Body:
I try to give my EC2 instance access to my AWS RDS Postgresql database via IAM.

First, I've created a policy:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "rds:connect"
            ],
            "Resource": [
                "arn:aws:rds:eu-west-1:824224273455:db:instance-name/db-name"
            ]
        }
    ]
}

After that I attached this policy to a role, which I attached to this specific EC2-instance. Everything seems to be fine till now.

When ssh to that specific EC2 instance and try to connect to the database, psql still prompts for a password.

Anyone knows how to accomplish it that I can connect without needing to use a password?


问:
injecting JSON record to HTML
I'm trying to get the artist name, among other fields, to be visible within the HTML page. As you can see from the code posted, the image is already showing on the page, so we don't quite understand where the issue lies.

window.addEventListener("load", function() {
  document.getElementById('searchform').addEventListener('submit', search);
})

//load V&A museum objects
function search(evt) {
  evt.preventDefault();
  var query = document.getElementById('query').value.trim();
  var url = "http://www.vam.ac.uk/api/json/museumobject/search?images=1&q=" + encodeURIComponent(query);

  console.log(url);

  var xhr = new XMLHttpRequest();
  xhr.addEventListener("load", function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
      var i, item, img_id, img_url, img, artist,
        target = document.getElementById("result"),
        json = JSON.parse(xhr.responseText);
      console.log(json);

      for (i = 0; i < json.records.length; i++) {
        item = json.records[i];
        console.log("artist = " + item.fields.artist);
        img_id = item.fields.primary_image_id;
        img_url = "http://media.vam.ac.uk/media/thira/collection_images/" +
          img_id.substr(0, 6) +
          "/" +
          img_id +
          "_jpg_o.jpg";

        img = document.createElement("img");
        img.setAttribute("src", img_url, );
        target.appendChild(img);

        artist = item.fields.artist;
        artist = document.createElement("h1");
        artist.setAttribute("h1", artist);
        artist = document.createElement("br");
        target.appendChild(artist);
      }
    }
  });
  xhr.open('GET', url, true); //true for asynchronous
  xhr.send();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="va.css">
  <title>Victoria & Albert Museum API TEST</title>
  <script src="va.js"></script>
</head>

<body>
  <!--<button id="button">Search</button>
    <br><br>
    <h1>Museum Objects</h1>
    <div id="objects"></div>-->

  <form id="searchform" class="form">
    <input type="text" id="query">
    <input type="submit" id="button">
  </form>

  <div id="result" class="objects">
    <!-- <div id="artists"><h1>Artists</h1></div> -->
  </div>

</body>

</html></code>```

The result is an image being pulled from the VA API, followed by the artist name. The image is visible but the artist only gets printed to the console.

答:
I think the issue is the setting of attribute, along with the overwriting of artist as suggested.</p>

```<code>artistName = item.fields.artist;
artist = document.createElement("h1");
var newContent = document.createTextNode(artistName);
artist.appendChild(newContent);
target.appendChild(artist);
</code>```

Title: injecting JSON record to HTML

Body:
I'm trying to get the artist name, among other fields, to be visible within the HTML page. As you can see from the code posted, the image is already showing on the page, so we don't quite understand where the issue lies.

window.addEventListener("load", function() {
  document.getElementById('searchform').addEventListener('submit', search);
})

//load V&A museum objects
function search(evt) {
  evt.preventDefault();
  var query = document.getElementById('query').value.trim();
  var url = "http://www.vam.ac.uk/api/json/museumobject/search?images=1&q=" + encodeURIComponent(query);

  console.log(url);

  var xhr = new XMLHttpRequest();
  xhr.addEventListener("load", function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
      var i, item, img_id, img_url, img, artist,
        target = document.getElementById("result"),
        json = JSON.parse(xhr.responseText);
      console.log(json);

      for (i = 0; i < json.records.length; i++) {
        item = json.records[i];
        console.log("artist = " + item.fields.artist);
        img_id = item.fields.primary_image_id;
        img_url = "http://media.vam.ac.uk/media/thira/collection_images/" +
          img_id.substr(0, 6) +
          "/" +
          img_id +
          "_jpg_o.jpg";

        img = document.createElement("img");
        img.setAttribute("src", img_url, );
        target.appendChild(img);

        artist = item.fields.artist;
        artist = document.createElement("h1");
        artist.setAttribute("h1", artist);
        artist = document.createElement("br");
        target.appendChild(artist);
      }
    }
  });
  xhr.open('GET', url, true); //true for asynchronous
  xhr.send();
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="va.css">
  <title>Victoria & Albert Museum API TEST</title>

  <form id="searchform" class="form">
    <input type="text" id="query">
    <input type="submit" id="button">
  </form>

The result is an image being pulled from the VA API, followed by the artist name. The image is visible but the artist only gets printed to the console.

Body:
I think the issue is the setting of attribute, along with the overwriting of artist as suggested.

artistName = item.fields.artist;
artist = document.createElement("h1");
var newContent = document.createTextNode(artistName);
artist.appendChild(newContent);
target.appendChild(artist);


问:
Is it possible to check he bitrate of a twilio video stream?
I am developing a video chat application using twilio. I would like to check the bitrate of a video stream playing in the browser to study how the bitrate will be affected at different bandwidths. How can I do this?</p>

答:
Twilio developer evangelist here.

You can measure various data about the incoming and outgoing streams using the WebRTC getStats API. There's a really good article that walks through the available stats that you should read to understand it. I would try to write more about it here, but reading the spec and checking out that article will be more accurate and useful to you.

Hope this helps.


问:
How to pop-over a UIViewController
I am trying to get a UIViewController transition effect where ViewControllerB pops over ViewContorllerA- while still revealing ViewcontrllerA in the background. Any idea how I can accomplish this?

Transition:

答:
!1. create a uiview

```<code>@IBOutlet weak var viewTemp: UIView!
</code>```

!2. positioning

```<code>let theScreenWidth = self.view.frame.size.width
let theScreenHeight = self.view.frame.height
viewTemp.frame = CGRect(x: 0, y: theScreenHeight+64, width: theScreenWidth, height: theScreenHeight-64)
</code>```

!3. use animate to open

```<code>UIView.animate(withDuration: 0.5, delay: 0, options: .curveLinear, animations: {
    viewTemp.transform = CGAffineTransform(translationX: 0, y: -self.view.frame.height)
}) { (success: Bool) in
}
</code>```

!4.  use animate to close

```<code>UIView.animate(withDuration: 0.5, delay: 0, options: .curveLinear, animations: {
    viewTemp.transform = CGAffineTransform(translationX: 0, y: self.view.frame.height)
}) { (success: Bool) in
}
</code>```

Title: How to pop-over a UIViewController

Body:
!1. create a uiview

@IBOutlet weak var viewTemp: UIView!

!2. positioning

let theScreenWidth = self.view.frame.size.width
let theScreenHeight = self.view.frame.height
viewTemp.frame = CGRect(x: 0, y: theScreenHeight+64, width: theScreenWidth, height: theScreenHeight-64)

!3. use animate to open

UIView.animate(withDuration: 0.5, delay: 0, options: .curveLinear, animations: {
    viewTemp.transform = CGAffineTransform(translationX: 0, y: -self.view.frame.height)
}) { (success: Bool) in
}

!4.  use animate to close

UIView.animate(withDuration: 0.5, delay: 0, options: .curveLinear, animations: {
    viewTemp.transform = CGAffineTransform(translationX: 0, y: self.view.frame.height)
}) { (success: Bool) in
}


问:
Errors fetching records within a month
I am having issues trying to fetch records for dates within a month. The records usually stops at the penultimate day.  If for example, I try to select records between October 1 and 31, I only get records ending at October 30. Same thing applies to August, records stop at August 29.
This is a snippet</p>

```<code>SELECT * FROM transactions where date BETWEEN date(CONCAT('2017', '-', '08','-01')) AND date(CONCAT('2017', '-', '08','-30')
</code>```

答:
try using YEAR() and MONTH():</p>

```<code> SELECT * FROM transactions
 WHERE YEAR([date]) = 2017 AND MONTH([date]) = 8
</code>```

Title: Errors fetching records within a month

Body:
I am having issues trying to fetch records for dates within a month. The records usually stops at the penultimate day.  If for example, I try to select records between October 1 and 31, I only get records ending at October 30. Same thing applies to August, records stop at August 29.
This is a snippet

SELECT * FROM transactions where date BETWEEN date(CONCAT('2017', '-', '08','-01')) AND date(CONCAT('2017', '-', '08','-30')

Body:
try using YEAR() and MONTH():

 SELECT * FROM transactions
 WHERE YEAR([date]) = 2017 AND MONTH([date]) = 8


问:
url to open facebook messenger app if installed, else open web messenger
I am looking for a single url to open facebook messenger chat session across different devices:

On mobile, if fb messenger app is installed, it opens fb-messenger://user-thread/

On mobile, if fb messenger app is not installed, it opens http://m.me/

On desktop, it opens http://m.me/

Example: For Google map, I just need use href="http://www.google.com/maps/place/{{lat}},{{lng}}", it will automatically open Google map app if installed, else it open google map on browser.

答:
√ On mobile, if fb messenger app is installed, it opens fb-messenger://user-thread/

√ On mobile, if fb messenger app is not installed, it opens http://m.me/ with call to action "install messenger"

On desktop, it opens https://m.facebook.com/ (bad because mobile)

In short you need to check if device is mobile or not:

```<code>if(mobile) {
  <a href="https://m.facebook.com/messages/compose?ids=USER_NAME_OR_ID">messenger mobile test</a>
} else {
  <a href="https://m.me/USER_NAME_OR_ID">messenger desktop test</a>
}
</code>```

Body:
√ On mobile, if fb messenger app is installed, it opens fb-messenger://user-thread/

√ On mobile, if fb messenger app is not installed, it opens http://m.me/ with call to action "install messenger"

On desktop, it opens https://m.facebook.com/ (bad because mobile)

In short you need to check if device is mobile or not:

if(mobile) {
  <a href="https://m.facebook.com/messages/compose?ids=USER_NAME_OR_ID">messenger mobile test</a>
} else {
  <a href="https://m.me/USER_NAME_OR_ID">messenger desktop test</a>
}


问:
Sorting data into appropriate key in an object
I'm trying to loop & sort a large number of data ( the whole ethereum blockchain lol )

I'm trying to create a record of all transactions for every address.

Obviously this is a very intensive process and I'm not sure how to make it more efficient beyond what I have (which isn't that efficient)

It starts out quick but I'm thinking now it has slowed because of the lookup for the address in the txs object.

Any help opinions / help is greatly appreciated.

https://giphy.com/gifs/3o6fJ7KWqxESY9okk8

```<code>var txs = {};

var i = 0;
// Loop over blocks
(function loop () {
setTimeout(function () {
  // Get current block
  var block = web3.eth.getBlock(i, true, (error, block) => {
    // debugger;
    // Loop over transactions in block
    for(var j = 0; j < block.transactions.length; j++) {
      // debugger;
      if(txs[block.transactions[j].to]) {

        txs[block.transactions[j].to].transactions.push(block.transactions[j]);
      } else if (txs[block.transactions[j].to]) {
        txs[block.transactions[j].from].transactions.push(block.transactions[j]);
      } else {
        txs[block.transactions[j].to] = {
          transactions: [block.transactions[j]]
        }
        txs[block.transactions[j].from] = {
          transactions: [block.transactions[j]]
        }
      }
    }
  });
  i++
  if (i < highestBlock) {
    loop();
  }
 }, 50);
})();
</code>```

答: I think that your code has an error in it located at "else-if", it seems that you should use the txs[block.transactions[j].from] property instead of the txs[block.transactions[j].to]. If you simply want to accomplish a recursive pattern you could use the setImmediate function or the process.nextTick method. If you use node.js v6+ you could use a Map instead of the object.

Body:
I'm trying to loop & sort a large number of data ( the whole ethereum blockchain lol )

I'm trying to create a record of all transactions for every address.

Obviously this is a very intensive process and I'm not sure how to make it more efficient beyond what I have (which isn't that efficient)

It starts out quick but I'm thinking now it has slowed because of the lookup for the address in the txs object.

Any help opinions / help is greatly appreciated.

https://giphy.com/gifs/3o6fJ7KWqxESY9okk8

var txs = {};

var i = 0;
// Loop over blocks
(function loop () {
setTimeout(function () {
  // Get current block
  var block = web3.eth.getBlock(i, true, (error, block) => {
    // debugger;
    // Loop over transactions in block
    for(var j = 0; j < block.transactions.length; j++) {
      // debugger;
      if(txs[block.transactions[j].to]) {

        txs[block.transactions[j].to].transactions.push(block.transactions[j]);
      } else if (txs[block.transactions[j].to]) {
        txs[block.transactions[j].from].transactions.push(block.transactions[j]);
      } else {
        txs[block.transactions[j].to] = {
          transactions: [block.transactions[j]]
        }
        txs[block.transactions[j].from] = {
          transactions: [block.transactions[j]]
        }
      }
    }
  });
  i++
  if (i < highestBlock) {
    loop();
  }
 }, 50);
})();


问:
How to send object in params without object name - HttpClientModule
I know that with new HttpClientModule I should set headers and params in new way:

```<code>const headers = this.auth.getHeaders(); // here i get headers from another service
const params = new HttpParams()
  .set('paramName', JSON.stringify(paramIWantToSend));
return this.http.put(`${this.API_PATH}/${id}`, {headers, params})
</code>```

Is there a way to send it without a name, just as an object?

not like this:

    {paramName: {ObjectIWantToSend}

but like this:

    {ObjectIWantToSend}

答:
From what I Understand, you probably need to send the JSON as part of the request body rather than as a parameter, If that is the case, you can send like this,

```<code> _httpClient.put(endPoint, paramIWantToSend, headers)
</code>```

HttpClient Reference

Body:
I know that with new HttpClientModule I should set headers and params in new way:

const headers = this.auth.getHeaders(); // here i get headers from another service
const params = new HttpParams()
  .set('paramName', JSON.stringify(paramIWantToSend));
return this.http.put(`${this.API_PATH}/${id}`, {headers, params})

Is there a way to send it without a name, just as an object?

not like this:

    {paramName: {ObjectIWantToSend}

but like this:

    {ObjectIWantToSend}

Body:
From what I Understand, you probably need to send the JSON as part of the request body rather than as a parameter, If that is the case, you can send like this,

 _httpClient.put(endPoint, paramIWantToSend, headers)

HttpClient Reference


问:
enabling/ disabling combobox when selected index is selected
I'm trying to enable comboxbox when specific country is selected, otherwise should be disabled. </p>

```<code>Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    cboCountry.Items.AddRange(File.ReadAllLines("..\..\TextFiles\countries.txt"))
    cboCounty.Items.AddRange(File.ReadAllLines("..\..\TextFiles\county.txt"))

End Sub

Private Sub cboCountry_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCountry.SelectedIndexChanged
    If cboCountry.SelectedIndex = cboCountry.Items.IndexOf("Ireland") Then

        cboCounty.Enabled = True

    Else
        cboCounty.Enabled = False

    End If
End Sub
</code>```

<p>When I select any country including "Ireland" combobox is disabled </p>

答:
Maybe try

Private Sub cboCountry_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCountry.SelectedIndexChanged
    If not cboCountry.SelectedIndex = cboCountry.Items.IndexOf("Ireland") Then

        cboCounty.Enabled = True

    Else
        cboCounty.Enabled = False

    End If
End Sub
```
<p>'Or just convert the output to string instead of selected index and compare it</p>
```Private Sub cboCountry_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCountry.SelectedIndexChanged
    If not cboCountry.SelectedItem.ToString() == "Ireland" Then

        cboCounty.Enabled = True

    Else
        cboCounty.Enabled = False

    End If
End Sub
```

Body:
I'm trying to enable comboxbox when specific country is selected, otherwise should be disabled.

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    cboCountry.Items.AddRange(File.ReadAllLines("..\..\TextFiles\countries.txt"))
    cboCounty.Items.AddRange(File.ReadAllLines("..\..\TextFiles\county.txt"))

End Sub

Private Sub cboCountry_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCountry.SelectedIndexChanged
    If cboCountry.SelectedIndex = cboCountry.Items.IndexOf("Ireland") Then

        cboCounty.Enabled = True

    Else
        cboCounty.Enabled = False

    End If
End Sub

When I select any country including "Ireland" combobox is disabled

Body:
Maybe try

Private Sub cboCountry_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCountry.SelectedIndexChanged
    If not cboCountry.SelectedIndex = cboCountry.Items.IndexOf("Ireland") Then

        cboCounty.Enabled = True

    Else
        cboCounty.Enabled = False

    End If
End Sub

'Or just convert the output to string instead of selected index and compare it

Private Sub cboCountry_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboCountry.SelectedIndexChanged
    If not cboCountry.SelectedItem.ToString() == "Ireland" Then

        cboCounty.Enabled = True

    Else
        cboCounty.Enabled = False

    End If
End Sub


问:
how to get value from html tag "div" to php variable
I have the code tag "div" its value will change cause i use jquery on click.
i using code ob_get_contents() for passing to php variable, but tag "div" also join.
how can i get value only?

Example :
inbox.js

```<code>jQuery(document).ready(function($) {
var cols = {}, messageIsOpen = false;
cols.showMessage = function() {
    $('body').addClass('show-message');
    messageIsOpen = true;
};
cols.hideMessage = function() {
    $('body').removeClass('show-message');
    $('.message-list li').removeClass('active');
messageIsOpen = false;
};
$('.messagelist .li')on('click', function(e){
  var item = $(this);
  if(messageIsOpen && item.is('.active')) {
    cols.hideMessage();
  }else{
    item.addClass('active');
    cols.showMessage();
    var drnm = $(".active .darinama").text();
    $(".from").text(drnm);
  }
});
});
</code>```

inbox.php

```<code><div class="messagelist">
  <ul>
    <li>
      <div class="darinama">Ahmad</div>
    </li>
    <li>
      <div class="darinama">Galih</div>
    </li>
    <li>
      <div class="darinama">String name</div>
    </li>
  </ul>
</div>
<div id=message>
  <?php
    php ob_start();
  ?>
  <div class="from"></div>
  <?php
    $nm = ob_get_contents();
    $strnm = substr($nm, 20);
    ?>
</div>
</code>```

result $nm is

Galih

want result just Galih

result $strnm is

ma">

substr not working
i want to process the data in php

答:
You could use a regular expression to parse the value.

```<code>$input_line1 = '<div class="drnama">Galih</div>';
$input_line2 = '<li>list item</li>';

// works for any HTML tag
$regex = "/<([\w]+)[^>]*>(.*?)<\/([\w]+)>/";

$nm = preg_match($regex, $input_line2, $output_array);
print_r($output_array);

/*
Array
(
    [0] => <li>list item</li>
    [1] => li
    [2] => list item
    [3] => li
)
*/

$nm = preg_match($regex, $input_line1, $output_array);
print_r($output_array);

/*
Array
(
    [0] => <div class="drnama">Galih</div>
    [1] => div
    [2] => Galih
    [3] => div
)
*/
</code>```

Demo

Body:
I have the code tag "div" its value will change cause i use jquery on click.
i using code ob_get_contents() for passing to php variable, but tag "div" also join.
how can i get value only?

Example :
inbox.js

jQuery(document).ready(function($) {
var cols = {}, messageIsOpen = false;
cols.showMessage = function() {
    $('body').addClass('show-message');
    messageIsOpen = true;
};
cols.hideMessage = function() {
    $('body').removeClass('show-message');
    $('.message-list li').removeClass('active');
messageIsOpen = false;
};
$('.messagelist .li')on('click', function(e){
  var item = $(this);
  if(messageIsOpen && item.is('.active')) {
    cols.hideMessage();
  }else{
    item.addClass('active');
    cols.showMessage();
    var drnm = $(".active .darinama").text();
    $(".from").text(drnm);
  }
});
});

inbox.php

Ahmad

Galih

String name

  <?php
    php ob_start();
  ?>

  <?php
    $nm = ob_get_contents();
    $strnm = substr($nm, 20);
    ?>

result $nm is

Galih

want result just Galih

result $strnm is

ma">

substr not working
i want to process the data in php

Body:
You could use a regular expression to parse the value.

$input_line1 = '<div class="drnama">Galih</div>';
$input_line2 = '<li>list item</li>';

// works for any HTML tag
$regex = "/<([\w]+)[^>]*>(.*?)<\/([\w]+)>/";

$nm = preg_match($regex, $input_line2, $output_array);
print_r($output_array);

/*
Array
(
    [0] => <li>list item</li>
    [1] => li
    [2] => list item
    [3] => li
)
*/

$nm = preg_match($regex, $input_line1, $output_array);
print_r($output_array);

/*
Array
(
    [0] => <div class="drnama">Galih</div>
    [1] => div
    [2] => Galih
    [3] => div
)
*/

Demo


问:
Why do I get 'No -renderInContext: method found' warning?
I get a compiler warning at the -renderInContext:

```<code>- (UIImage *) imageFromView:(UIView *)view {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}
</code>```

I have QuartzCore in the project frameworks, and the code works.
How do I fix the code so it stops giving me the warning?

The exact warning I get is

```<code>warning: no '-renderInContext:' method found
warning: (Messages without a matching method signature
warning: will be assumed to return 'id' and accept
warning: '...' as arguments.)
</code>```

答:
I suppose it's due to the fact that the CALayer class header is in the QuartzCore framework.

In Xcode, in the Frameworks group, add the QuartzCore framework and it should be all fine.

Then, see my post here on SO for how to include the header files in every source file. Now it's not for Core Data, but for QuartzCore (in the exact same way)

Body:
I get a compiler warning at the -renderInContext:

- (UIImage *) imageFromView:(UIView *)view {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

I have QuartzCore in the project frameworks, and the code works.
How do I fix the code so it stops giving me the warning?

The exact warning I get is

warning: no '-renderInContext:' method found
warning: (Messages without a matching method signature
warning: will be assumed to return 'id' and accept
warning: '...' as arguments.)


问:
Filter all files recursively in a directory and then move them to a new set of folders each with a limit of files per directory
Sorry for the long title, just trying to be specific.

Here's my scenario today (as the title alludes):

Root Dir has x amount of folders, say 20.  Each folder has files and possible sub-folders.  I know that I only care about the files in any folder with "Hold" in the folder name.

I need to target all files, no matter the type, in the folders and subs.  I then need to move the target files to new folders in the root dir.  Each folder must only house 50,000 files and then roll over to the next folder for the next 50k.  That process will repeat until all the targets have been moved to their new dir.

Here's the PS code I have so far:

```<code>#SETUP
$FileDir = GCI -Path C:\TEST -Filter 'Hold*' -Directory -Recurse
$FilesinHOLD = GCI -File -Path $FileDir.FullName -Recurse
$NewDir = 'C:\TEST\Limited'
$Limit = '50000'

#Execution
$FilesinHOLD | Select-Object -First $Limit | Move-Item -Destination $NewDir
</code>```

Where I'm left is looking for the mechanism to auto-create a new "Limited" folder and put 50k in there and then repeat the process.  I was wondering if it would be possible to just render the same name simply followed by (2) and then (3) and so on automatically as the default behavior in Windows Explorer..? It would look like this:

C:\TEST\Limited

C:\TEST\Limited(2)

C:\TEST\Limited(3)

I would finish up by running back through and deleting the now empty "HOLD" directories from which I pulled the files from after verifying they are empty via GCI or Measure-Object.

Thanks in advance for your input.

-CE

答:
Rather than grabbing all the files then removing them from the array, I would move them as I recurse the directories, then loop on that:</p>

```<code>$rootDir = 'C:\TEST\Limited'
$NewDir = $rootDir
$Limit = '50000'
$filesMoved = $Limit
$folderCnt = 1
while($filesMoved -ge $limit)
{
    $filesMoved = GCI -Path C:\TEST -Filter 'Hold*' -Directory -Recurse | GCI -File -Recurse | Select-Object -First $Limit | Move-Item -Destination $NewDir -passthru | measure | select -expand count
    $folderCnt += 1
    $newDir = $rootDir +"($folderCnt)"
}
</code>```

Body:
Sorry for the long title, just trying to be specific.

Here's my scenario today (as the title alludes):

Root Dir has x amount of folders, say 20.  Each folder has files and possible sub-folders.  I know that I only care about the files in any folder with "Hold" in the folder name.

I need to target all files, no matter the type, in the folders and subs.  I then need to move the target files to new folders in the root dir.  Each folder must only house 50,000 files and then roll over to the next folder for the next 50k.  That process will repeat until all the targets have been moved to their new dir.

Here's the PS code I have so far:

#SETUP
$FileDir = GCI -Path C:\TEST -Filter 'Hold*' -Directory -Recurse
$FilesinHOLD = GCI -File -Path $FileDir.FullName -Recurse
$NewDir = 'C:\TEST\Limited'
$Limit = '50000'

#Execution
$FilesinHOLD | Select-Object -First $Limit | Move-Item -Destination $NewDir

Where I'm left is looking for the mechanism to auto-create a new "Limited" folder and put 50k in there and then repeat the process.  I was wondering if it would be possible to just render the same name simply followed by (2) and then (3) and so on automatically as the default behavior in Windows Explorer..? It would look like this:

C:\TEST\Limited

C:\TEST\Limited(2)

C:\TEST\Limited(3)

I would finish up by running back through and deleting the now empty "HOLD" directories from which I pulled the files from after verifying they are empty via GCI or Measure-Object.

Thanks in advance for your input.

-CE

Body:
Rather than grabbing all the files then removing them from the array, I would move them as I recurse the directories, then loop on that:

$rootDir = 'C:\TEST\Limited'
$NewDir = $rootDir
$Limit = '50000'
$filesMoved = $Limit
$folderCnt = 1
while($filesMoved -ge $limit)
{
    $filesMoved = GCI -Path C:\TEST -Filter 'Hold*' -Directory -Recurse | GCI -File -Recurse | Select-Object -First $Limit | Move-Item -Destination $NewDir -passthru | measure | select -expand count
    $folderCnt += 1
    $newDir = $rootDir +"($folderCnt)"
}


问:
Generate range between two strings [AA] -> [CD] or [CCC] -> [DMK]
I want to generate a sequence of strings between two groups that can be either 1 letter [A] -> [F] , 2 letters such as [AA] -> [CD] or any other length like 3 or 4 letters using c#.

For example I can specify the start and end values, and it will generate the sequence.

From [AA] to [CD] should generate

```<code>AA
AB
AC
AD

BA
BB
BC
BD

CA
CB
CC
CD
</code>```

I tried to utilize base-26 algorithm to generate the required sequence but failed to get the required output.

```<code>string from ="AA";
string to = "CD";
IEnumerable<string> mysequence = Enumerable.Range(ConvertNumber(from), ConvertNumber(to) - ConvertNumber(from)).Select(ConvertAlpha).ToList();

public static string ConvertAlpha(int value)
{
    const int a = (int)'A';
    value = value - 1;
    var returnValue = new StringBuilder();
    while (value > -1)
    {
        var remainder = value % 26;
        returnValue.Insert(0, (char)(a + remainder));
        value = value / 26 - 1;
    }
    return returnValue.ToString();
}

public static int ConvertNumber(string value)
{
    const int a = (int)'A' - 1;
    int returnValue = 0;
    foreach (var character in value.ToUpper())
    {
        returnValue *= 26;
        returnValue += (int)character - a;
    }
    return returnValue;
}
</code>```

答:
The problem you describe is harder than just converting a base-26 representation to an integer, doing some calculation, and then converting back. Your alpha strings aren't necessarily base-26. For example, you say that given AA and CD, you want to generate

```<code>AA, AB, AC, AD
BA, BB, BC, BD
CA, CB, CC, CD
</code>```

What you really have is a base-4 system that uses the characters A, B, C, and D to represent the numbers 0, 1, 2, and 3. What you're saying here is that you want to generate all the 2-digit, base-4 numbers from 00 through 33.

Given CCC => DMK, it's a base-11 system using digits C through M. It's unclear from your description whether you want:

```<code>CCC, CCD, CCE ... CCK
CDC, CDD, CDE ... CDK
...
</code>```

Or if you want

```<code>CCC, CCD, CCE ... CCM
CDC, CDD, CDE ... CDM
...
</code>```

If you want the former, then each digit position is a different base, and things get even more complicated.

How you define things changes how you would write the code to generate the values.

Regardless or how you want to interpret your alpha values, it's clear that your base-26 conversion functions are incorrect.

Your conversion from int to string has a few errors. In particular, subtracting 1 from the value is going to give you trouble. You can see that if you were to pass 0 to the function. The result would be an empty string.

Here's a correct function:

```<code>static string ConvertToBase26(int value)
{
    const int a = (int)'A';
    var result = new StringBuilder();
    do
    {
        var remainder = value % 26;
        value /= 26;
        result.Insert(0, (char)(a + remainder);
    } while (value > 0);
    return result.ToString();
}
</code>```

Your conversion from base26 to integer has similar errors, due to subtracting 1 from things. Remember, A acts like 0. The corrected function:

```<code>static int ConvertFromBase26(string value)
{
    const int a = (int)'A';
    int result = 0;
    foreach (var c in value.ToUpper())
    {
        result = (result * 26) + (c - a);
    }
    return result;
}
</code>```

I recommend renaming your base conversion functions. Your ConvertAlpha function converts an integer to a base-26 string. That's not at all clear in the name, as one could misconstrue "ConvertAlpha" to mean "ConvertFromAlpha". I would recommend ConvertToBase26 and ConvertFromBase26, which are much more explicit and unambiguous.

Body:
I want to generate a sequence of strings between two groups that can be either 1 letter [A] -> [F] , 2 letters such as [AA] -> [CD] or any other length like 3 or 4 letters using c#.

For example I can specify the start and end values, and it will generate the sequence.

From [AA] to [CD] should generate

AA
AB
AC
AD

BA
BB
BC
BD

CA
CB
CC
CD

I tried to utilize base-26 algorithm to generate the required sequence but failed to get the required output.

string from ="AA";
string to = "CD";
IEnumerable<string> mysequence = Enumerable.Range(ConvertNumber(from), ConvertNumber(to) - ConvertNumber(from)).Select(ConvertAlpha).ToList();

public static string ConvertAlpha(int value)
{
    const int a = (int)'A';
    value = value - 1;
    var returnValue = new StringBuilder();
    while (value > -1)
    {
        var remainder = value % 26;
        returnValue.Insert(0, (char)(a + remainder));
        value = value / 26 - 1;
    }
    return returnValue.ToString();
}

public static int ConvertNumber(string value)
{
    const int a = (int)'A' - 1;
    int returnValue = 0;
    foreach (var character in value.ToUpper())
    {
        returnValue *= 26;
        returnValue += (int)character - a;
    }
    return returnValue;
}

Body:
The problem you describe is harder than just converting a base-26 representation to an integer, doing some calculation, and then converting back. Your alpha strings aren't necessarily base-26. For example, you say that given AA and CD, you want to generate

AA, AB, AC, AD
BA, BB, BC, BD
CA, CB, CC, CD

What you really have is a base-4 system that uses the characters A, B, C, and D to represent the numbers 0, 1, 2, and 3. What you're saying here is that you want to generate all the 2-digit, base-4 numbers from 00 through 33.

Given CCC => DMK, it's a base-11 system using digits C through M. It's unclear from your description whether you want:

CCC, CCD, CCE ... CCK
CDC, CDD, CDE ... CDK
...

Or if you want

CCC, CCD, CCE ... CCM
CDC, CDD, CDE ... CDM
...

If you want the former, then each digit position is a different base, and things get even more complicated.

How you define things changes how you would write the code to generate the values.

Regardless or how you want to interpret your alpha values, it's clear that your base-26 conversion functions are incorrect.

Your conversion from int to string has a few errors. In particular, subtracting 1 from the value is going to give you trouble. You can see that if you were to pass 0 to the function. The result would be an empty string.

Here's a correct function:

static string ConvertToBase26(int value)
{
    const int a = (int)'A';
    var result = new StringBuilder();
    do
    {
        var remainder = value % 26;
        value /= 26;
        result.Insert(0, (char)(a + remainder);
    } while (value > 0);
    return result.ToString();
}

Your conversion from base26 to integer has similar errors, due to subtracting 1 from things. Remember, A acts like 0. The corrected function:

static int ConvertFromBase26(string value)
{
    const int a = (int)'A';
    int result = 0;
    foreach (var c in value.ToUpper())
    {
        result = (result * 26) + (c - a);
    }
    return result;
}

I recommend renaming your base conversion functions. Your ConvertAlpha function converts an integer to a base-26 string. That's not at all clear in the name, as one could misconstrue "ConvertAlpha" to mean "ConvertFromAlpha". I would recommend ConvertToBase26 and ConvertFromBase26, which are much more explicit and unambiguous.


问:
How can I get only 1 result to be printed to the console and not both of them?

My code here has a problem but I know what the problem is. There are 2 characters in grade, so 2 results are shown, each result is added by 0.3. That is a problem because only one result is supposed to be printed to the console.

```<code>keydict = {'A': 4.0,'B': 3.0,'C': 2.0,'D': 1.0,'F': 0, '+': 0.3, '-': -0.3}
grade = input('Grade:')

def letter2number(letter):
    if len(grade) > 2:
        print('Too many characters')
        letter2number(grade)
    for char in grade:
        if char in keydict:
            if '+' in grade:
                print(keydict[char] + keydict['+'])
            elif '-' in grade:
                print(keydict[char] + keydict['-'])
            else:
                print(keydict[char])
        else:
            print(grade,'is an invalid input')
    return

letter2number(grade)
</code>```

This is what gets printed to the screen after the user inputs "A+"(or any grade with a '+' or '-') I realize the for loop is causing this problem because there are 2 characters in the input. But I don't think there is another way to do it without using a for loop. The 4.3 is expected, the 0.6 is not what I want.

```<code>Grade: A+ # <<< Thats a user input
4.3       # <<< YES
0.6       # <<< How can I get this to NOT print
</code>```

Other than the 0.6 being printed, I have no other issue with the code. In other words, I don't want the 0.6 there, but the 4.3 should stay.

答:
You need to add break at the end of the block if char in keydict:

```<code>keydict = {'A': 4.0,'B': 3.0,'C': 2.0,'D': 1.0,'F': 0, '+': 0.3, '-': -0.3}
grade = input('Grade:')

def letter2number(letter):
    if len(grade) > 2:
        print('Too many characters')
        letter2number(grade)
    for char in grade:
        if char in keydict:
            if '+' in grade:
                print(keydict[char] + keydict['+'])
            elif '-' in grade:
                print(keydict[char] + keydict['-'])
            else:
                print(keydict[char])

            break  # <<---

        else:
            print(grade,'is an invalid input')
    return

letter2number(grade)
</code>```

break stops the loop

Body:
My code here has a problem but I know what the problem is. There are 2 characters in grade, so 2 results are shown, each result is added by 0.3. That is a problem because only one result is supposed to be printed to the console.

keydict = {'A': 4.0,'B': 3.0,'C': 2.0,'D': 1.0,'F': 0, '+': 0.3, '-': -0.3}
grade = input('Grade:')

def letter2number(letter):
    if len(grade) > 2:
        print('Too many characters')
        letter2number(grade)
    for char in grade:
        if char in keydict:
            if '+' in grade:
                print(keydict[char] + keydict['+'])
            elif '-' in grade:
                print(keydict[char] + keydict['-'])
            else:
                print(keydict[char])
        else:
            print(grade,'is an invalid input')
    return

letter2number(grade)

This is what gets printed to the screen after the user inputs "A+"(or any grade with a '+' or '-') I realize the for loop is causing this problem because there are 2 characters in the input. But I don't think there is another way to do it without using a for loop. The 4.3 is expected, the 0.6 is not what I want.

Grade: A+ # <<< Thats a user input
4.3       # <<< YES
0.6       # <<< How can I get this to NOT print

Other than the 0.6 being printed, I have no other issue with the code. In other words, I don't want the 0.6 there, but the 4.3 should stay.

Body:
You need to add break at the end of the block if char in keydict:

keydict = {'A': 4.0,'B': 3.0,'C': 2.0,'D': 1.0,'F': 0, '+': 0.3, '-': -0.3}
grade = input('Grade:')

def letter2number(letter):
    if len(grade) > 2:
        print('Too many characters')
        letter2number(grade)
    for char in grade:
        if char in keydict:
            if '+' in grade:
                print(keydict[char] + keydict['+'])
            elif '-' in grade:
                print(keydict[char] + keydict['-'])
            else:
                print(keydict[char])

            break  # <<---

        else:
            print(grade,'is an invalid input')
    return

letter2number(grade)

break stops the loop


问:
Difficulties coding variables for the choices in a dictionary guessing game
I'm trying to create a guessing game where the user chooses a key within the dictionary and guesses the value of it.
I'm having a hard time trying to code the variables for the choice in order to have to guess the value.

Here is what I have so far:

```<code>def main():
    capitals = {'AL' : 'Montgomery', 'AK' : 'Juneau', 'AZ' : 'Phoenix',
                'AR' : 'Little Rock', 'CA' : 'Sacramento', 'CO' : 'Denver',
                'CT' : 'Hartford', 'FL' : 'Tallahassee', 'GA' : 'Atlanta',
                'HI' : 'Honolulu', 'ID' : 'Boise', 'IL' : 'Springfield',
                'IN' : 'Indianapolis', 'IA' : 'Des Moines', 'KS' : 'Topeka'}
    print("Choose a state from the list", capitals.keys())
    choice = input('Which state would you like to guess? : ')
    choice == capitals.keys()
    guess = input('Guess the capital of the state chosen : ')
    answer = capitals.values()
    if guess == answer:
        print("Yay! You're CORRECT!")
    else:
        print("Sorry, You're INCORRECT!")

main()
</code>```

It seems that my if statement isn't being read by the program. How can I fix this?

答:
There are a few things wrong with the code provided. Here's a working version with inline comments to explain what's going on. While loops allow you to check the input data before moving on.</p>

```<code>def main():

    capitals = {'AL': 'Montgomery', 'AK': 'Juneau', 'AZ': 'Phoenix',
                'AR': 'Little Rock', 'CA': 'Sacramento', 'CO': 'Denver',
                'CT': 'Hartford', 'FL': 'Tallahassee', 'GA': 'Atlanta',
                'HI': 'Honolulu', 'ID': 'Boise', 'IL': 'Springfield',
                'IN': 'Indianapolis', 'IA': 'Des Moines', 'KS': 'Topeka'}

    # initialize variables used in while loops
    choice = ''
    guess = ''

    print("Choose a state from the list: {0}".format(' '.join(capitals.keys())))

    # as long as choice is not in the list of capitals, keep asking
    while choice not in capitals.keys():
        choice = input('Which state would you like to guess? : ')

    # get the correct answer for the chosen state
    answer = capitals[choice]

    # as long as the guess doesn't contain any non-whitespace characters, keep asking
    while guess.strip() == '':
        guess = input('Guess the capital of the state chosen : ')

    # if the cleaned up, case-insensitive guess matches the answer, you win
    if guess.strip().lower() == answer.lower():
        print("Yay! You're CORRECT!")

    # otherwise, you lose
    else:
        print("Sorry, You're INCORRECT!")

main()
</code>```

Body:
I'm trying to create a guessing game where the user chooses a key within the dictionary and guesses the value of it.
I'm having a hard time trying to code the variables for the choice in order to have to guess the value.

Here is what I have so far:

def main():
    capitals = {'AL' : 'Montgomery', 'AK' : 'Juneau', 'AZ' : 'Phoenix',
                'AR' : 'Little Rock', 'CA' : 'Sacramento', 'CO' : 'Denver',
                'CT' : 'Hartford', 'FL' : 'Tallahassee', 'GA' : 'Atlanta',
                'HI' : 'Honolulu', 'ID' : 'Boise', 'IL' : 'Springfield',
                'IN' : 'Indianapolis', 'IA' : 'Des Moines', 'KS' : 'Topeka'}
    print("Choose a state from the list", capitals.keys())
    choice = input('Which state would you like to guess? : ')
    choice == capitals.keys()
    guess = input('Guess the capital of the state chosen : ')
    answer = capitals.values()
    if guess == answer:
        print("Yay! You're CORRECT!")
    else:
        print("Sorry, You're INCORRECT!")

main()

It seems that my if statement isn't being read by the program. How can I fix this?

Body:
There are a few things wrong with the code provided. Here's a working version with inline comments to explain what's going on. While loops allow you to check the input data before moving on.

def main():

    capitals = {'AL': 'Montgomery', 'AK': 'Juneau', 'AZ': 'Phoenix',
                'AR': 'Little Rock', 'CA': 'Sacramento', 'CO': 'Denver',
                'CT': 'Hartford', 'FL': 'Tallahassee', 'GA': 'Atlanta',
                'HI': 'Honolulu', 'ID': 'Boise', 'IL': 'Springfield',
                'IN': 'Indianapolis', 'IA': 'Des Moines', 'KS': 'Topeka'}

    # initialize variables used in while loops
    choice = ''
    guess = ''

    print("Choose a state from the list: {0}".format(' '.join(capitals.keys())))

    # as long as choice is not in the list of capitals, keep asking
    while choice not in capitals.keys():
        choice = input('Which state would you like to guess? : ')

    # get the correct answer for the chosen state
    answer = capitals[choice]

    # as long as the guess doesn't contain any non-whitespace characters, keep asking
    while guess.strip() == '':
        guess = input('Guess the capital of the state chosen : ')

    # if the cleaned up, case-insensitive guess matches the answer, you win
    if guess.strip().lower() == answer.lower():
        print("Yay! You're CORRECT!")

    # otherwise, you lose
    else:
        print("Sorry, You're INCORRECT!")

main()


问:
How to change the background color of navigation bar in a modal view?
I present a modal view when I click a cell in my custom tableview. How to change the background color of navigation bar in a modal view?
For example. I want to change it to black color.The following code do not work in the prepare segue method.

```<code>[destinationNavController.navigationBar setBackgroundColor:[UIColor blackColor]];
</code>```

or

```<code> [[UINavigationBar appearance]setBackgroundColor:[UIColor blackColor]];
</code>```

or

```<code> [destinationNavController.navigationBar setTintColor:[UIColor blackColor]];
</code>```

in the viewDidLoad method of the destination Controller view I write

```<code>[self.navigationController.navigationBar setBackgroundColor:[UIColor blackColor]];
</code>```

or

```<code> [[UINavigationBar appearance]setBackgroundColor:[UIColor blackColor]];
</code>```

or

```<code> [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];// only change the navigation item text color....
</code>```

Any other ideas?

答:
I only tested this in iOS 11 so far and in my case our app is white but I want to present a fullscreen slide show with black color, but I still wanted a status bar, with white letters and the same black background as my main view

Step 1: make your view background color black.
 XCode in your .xib or storyboard the parents view's background color black (very important step)

Step 2:
in your view controller that is in charge of this view, add this:

```<code>override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent }
</code>```

This makes the color of the status text to be white. This also works on iPhone X.

Body:
I present a modal view when I click a cell in my custom tableview. How to change the background color of navigation bar in a modal view?
For example. I want to change it to black color.The following code do not work in the prepare segue method.

[destinationNavController.navigationBar setBackgroundColor:[UIColor blackColor]];

or

 [[UINavigationBar appearance]setBackgroundColor:[UIColor blackColor]];

or

 [destinationNavController.navigationBar setTintColor:[UIColor blackColor]];

in the viewDidLoad method of the destination Controller view I write

[self.navigationController.navigationBar setBackgroundColor:[UIColor blackColor]];

or

 [[UINavigationBar appearance]setBackgroundColor:[UIColor blackColor]];

or

 [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];// only change the navigation item text color....

Any other ideas?

Body:
I only tested this in iOS 11 so far and in my case our app is white but I want to present a fullscreen slide show with black color, but I still wanted a status bar, with white letters and the same black background as my main view

Step 1: make your view background color black.
 XCode in your .xib or storyboard the parents view's background color black (very important step)

Step 2:
in your view controller that is in charge of this view, add this:

override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent }

This makes the color of the status text to be white. This also works on iPhone X.


问:
Doctrine ORM default value with quotes
how can i set a default value with different quotes?

```<code>     /**
     * @ORM\Column(type="string", options={"default" = "<link href="https://fonts.googleapis.com/css?family=Nunito+Sans" rel="stylesheet">"})
     */
</code>```

THX for help

答:
```<code> /**
   * @ORM\Column(type="string")
   */
  protected $field = '<link href="https://fonts.googleapis.com/css?family=Nunito+Sans" rel="stylesheet">';
</code>```

Title: Doctrine ORM default value with quotes

Body:
how can i set a default value with different quotes?

     /**
     * @ORM\Column(type="string", options={"default" = "<link href="https://fonts.googleapis.com/css?family=Nunito+Sans" rel="stylesheet">"})
     */

THX for help


问:
where will be stored our AWS Custom AMI?
we can take the back up of server which is running in AWS. that is called AMI.
How AWS handles our custom AMI ? where it will be stored ? can we access the Custom AMI Location ? I searched lot but could not get the answer. please let me know if there is any documentation about Custom AMI location. if it stored in S3 buckets can we see it ? or otherwise how can we know about out custom AMI.</p>

答:
An Amazon Machine Image (AMI) is stored in Amazon S3, but it is not directly accessible. Instead, you must use API calls or the Management Console to use an AMI.

The reality is that an AMI might actually contain content from other AMIs -- for example, if you launch an instance from a standard AWS-provided AMI, then add one file and create a new AMI, only the blocks that your instance changed would be stored -- the remaining (unchanged) blocks simply point to the original AMI content. This means that AMIs can often be quite small and you will not pay the cost of storing the complete disk. All of this is invisible to users.

You can see your 'custom' AMI in the AMIs section of the management console, or via the describe_images API call.


问:
Can we have two separate bin folders within a single Function App?
We have two different azure function app projects, each with a single function. We would like to host them all under a single Function App in Azure and each with it's own bin. I would like to be able for each function to deal with their own versions of external references, i.e. function1 might use json.net 10.0, while function2 stay on json.net 9.0.

Creating an Azure Function App host for each function can become very unmanageable, specially if we have to multiply x3 for each environment: dev, staging, prod.

We tried by doing a normal deployment of the two projects, but they both share the same bin (which resulted in a reference issue):

```<code>wwwroot
- bin
- function1
--- function.json (pointing to ../bin/function1.dll)
- function2
--- function.json (pointing to ../bin/function2.dll)
- host.json
</code>```

We also tried creating virtual application directories and deploy to those, but the portal doesn't find the functions. The end structure is:

```<code>wwwroot
- function1
--- bin
--- function1
------ function.json
--- host.json
- function2
--- bin
--- function2
------ function.json
--- host.json
</code>```

moving the function.json file of each function to the root of the virtual directory and fixing the reference to the dll fixes the issue.

It sounds like Virtual Directories would cater to this need, but the portal doesn't seem to support finding function.json two levels deep.

Is what we are wanting to do possible?

答:
This documentation seems to imply that you can define custom assemblies on a per function basis, though I do not know how the versioning would work.

Private assemblies are part of a given function's context, and support side-loading of different versions. Private assemblies should be uploaded in a bin folder in the function directory. Reference using the file name, such as #r "MyAssembly.dll".

Body:
We have two different azure function app projects, each with a single function. We would like to host them all under a single Function App in Azure and each with it's own bin. I would like to be able for each function to deal with their own versions of external references, i.e. function1 might use json.net 10.0, while function2 stay on json.net 9.0.

Creating an Azure Function App host for each function can become very unmanageable, specially if we have to multiply x3 for each environment: dev, staging, prod.

We tried by doing a normal deployment of the two projects, but they both share the same bin (which resulted in a reference issue):

wwwroot
- bin
- function1
--- function.json (pointing to ../bin/function1.dll)
- function2
--- function.json (pointing to ../bin/function2.dll)
- host.json

We also tried creating virtual application directories and deploy to those, but the portal doesn't find the functions. The end structure is:

wwwroot
- function1
--- bin
--- function1
------ function.json
--- host.json
- function2
--- bin
--- function2
------ function.json
--- host.json

moving the function.json file of each function to the root of the virtual directory and fixing the reference to the dll fixes the issue.

It sounds like Virtual Directories would cater to this need, but the portal doesn't seem to support finding function.json two levels deep.

Is what we are wanting to do possible?


问:
How do I get the row count of a Pandas DataFrame?
How do I get the number of rows of a pandas dataframe df?

答:
...building on Jan-Philip Gehrcke's answer.

The reason why len(df) or len(df.index) is faster than df.shape[0]:

Look at the code. df.shape is a @property that runs a DataFrame method calling len twice.

```<code>df.shape??
Type:        property
String form: <property object at 0x1127b33c0>
Source:
# df.shape.fget
@property
def shape(self):
    """
    Return a tuple representing the dimensionality of the DataFrame.
    """
    return len(self.index), len(self.columns)
</code>```

And beneath the hood of len(df)

```<code>df.__len__??
Signature: df.__len__()
Source:
    def __len__(self):
        """Returns length of info axis, but here we use the index """
        return len(self.index)
File:      ~/miniconda2/lib/python2.7/site-packages/pandas/core/frame.py
Type:      instancemethod
</code>```

len(df.index) will be slightly faster than len(df) since it has one less function call, but this is always faster than df.shape[0]

Body:
...building on Jan-Philip Gehrcke's answer.

The reason why len(df) or len(df.index) is faster than df.shape[0]:

Look at the code. df.shape is a @property that runs a DataFrame method calling len twice.

df.shape??
Type:        property
String form: <property object at 0x1127b33c0>
Source:
# df.shape.fget
@property
def shape(self):
    """
    Return a tuple representing the dimensionality of the DataFrame.
    """
    return len(self.index), len(self.columns)

And beneath the hood of len(df)

df.__len__??
Signature: df.__len__()
Source:
    def __len__(self):
        """Returns length of info axis, but here we use the index """
        return len(self.index)
File:      ~/miniconda2/lib/python2.7/site-packages/pandas/core/frame.py
Type:      instancemethod

len(df.index) will be slightly faster than len(df) since it has one less function call, but this is always faster than df.shape[0]


问:
Make Lambda function execute now, and/or in an hour
I'm trying to implement an AWS Lambda function that should send an HTTP request. If that request fails (response is anything but status 200) I should wait another hour before retrying (longer that the Lambda stays hot). What the best way to implement this?

What comes to mind is to persist my HTTP request in some way and being able to trigger the Lambda function again in a specified amount of time in case of a persisted HTTP request. But I'm not completely sure which AWS service that would provide that functionality for me. Is SQS an option that can help here?

Or, can I dynamically schedule Lambda execution for this? Note that the request to be retried should be identical to the first one.

Any other suggestions? What's the best practice for this?

(Lambda function is my option. No EC2 or such things are possible)

答:
You can't directly trigger Lambda functions from SQS (at the time of writing, anyhow).

You could potentially handle the non-200 errors by writing the request data (with appropriate timestamp) to a DynamoDB table that's configured for TTL. You can use DynamoDB Streams to detect when DynamoDB deletes a record and that can trigger a Lambda function from the stream.

This is obviously a roundabout way to achieve what you want but it should be simple to test.


问:
Golang map containing both string and integer
I am trying to create a JSON string from a map using JSON.Marshal() in golang. However, the int values are being displayed as strings surrounded by double quotes.

My code is outputting:

```<code>{ "age":
    {
        "$gt":"22",
        "$lt":"20"
    },
  "location":
    {
        "$eq":"london"
    },
  "name":{
        "$eq":"fred"
    }
}
</code>```

instead of

```<code>{ "age":
    {
        "$gt":22,
        "$lt":20
    },
  "location":
    {
        "$eq":"london"
    },
  "name":{
        "$eq":"fred"
    }
}
</code>```

I am using:

```<code>var output_map = map[string]map[string]string{}

//Populate map here

output_json, err := json.Marshal(output_map)

if err!= nil {
    fmt.Println("Error encoding JSON")
}

fmt.Println(output_json)
</code>```

My understanding is that JSON.Marshal() will print the integers correctly if they are supplied but my map won't contain integers. I could change my map to map[string]map[string]int{} but then it wouldn't contain the string values for 'name' and 'location'.

The ultimate problem is that I need the map to contain both int and string values. Some sort of map[string]map[string]{}.

How can I achieve this? Thank you in advance.

Harry

答:
I agree with maerics,

map[string]interface{} would be the way to go, if you have to avoid structs.

From your content I assume, that you are dealing with mongodb-queries.

So maybe the following code helps.

If you are going to query mongodb from go I would recommend the mgo-driver mgo.v2.

It implements a custom type bson.M which is the same as mentioned above, but works also for querying the db.

Beside this, it makes the code more readable.

Sample:

```<code>package main

import (
    "fmt"
    "gopkg.in/mgo.v2/bson"
    "encoding/json"
)

func main() {

    bsonMap := bson.M{
        "age": bson.M{
            "$gt": 22,
            "$lt": 20,
        },
        "location": bson.M{"$eq": "london",},
        "name":     bson.M{"$eq": "fred"},
    }

    bytes, err := json.Marshal(bsonMap)

    if err != nil {
        panic(err)
    }

    fmt.Println(string(bytes))
}
</code>```

Body:
I am trying to create a JSON string from a map using JSON.Marshal() in golang. However, the int values are being displayed as strings surrounded by double quotes.

My code is outputting:

{ "age":
    {
        "$gt":"22",
        "$lt":"20"
    },
  "location":
    {
        "$eq":"london"
    },
  "name":{
        "$eq":"fred"
    }
}

instead of

{ "age":
    {
        "$gt":22,
        "$lt":20
    },
  "location":
    {
        "$eq":"london"
    },
  "name":{
        "$eq":"fred"
    }
}

I am using:

var output_map = map[string]map[string]string{}

//Populate map here

output_json, err := json.Marshal(output_map)

if err!= nil {
    fmt.Println("Error encoding JSON")
}

fmt.Println(output_json)

My understanding is that JSON.Marshal() will print the integers correctly if they are supplied but my map won't contain integers. I could change my map to map[string]map[string]int{} but then it wouldn't contain the string values for 'name' and 'location'.

The ultimate problem is that I need the map to contain both int and string values. Some sort of map[string]map[string]{}.

How can I achieve this? Thank you in advance.

Harry

Body:
I agree with maerics,

map[string]interface{} would be the way to go, if you have to avoid structs.

From your content I assume, that you are dealing with mongodb-queries.

So maybe the following code helps.

If you are going to query mongodb from go I would recommend the mgo-driver mgo.v2.

It implements a custom type bson.M which is the same as mentioned above, but works also for querying the db.

Beside this, it makes the code more readable.

Sample:

package main

import (
    "fmt"
    "gopkg.in/mgo.v2/bson"
    "encoding/json"
)

func main() {

    bsonMap := bson.M{
        "age": bson.M{
            "$gt": 22,
            "$lt": 20,
        },
        "location": bson.M{"$eq": "london",},
        "name":     bson.M{"$eq": "fred"},
    }

    bytes, err := json.Marshal(bsonMap)

    if err != nil {
        panic(err)
    }

    fmt.Println(string(bytes))
}