问:
how to count multiple columns using countifs
I am putting in a formula  to count the number of times a quote is required Indicated by the letter Q in a given column, when I put the formula in for one column I get the correct answer, but when I want to do it for multiple columns I get zero, can anyone help please?
the formula is

```<code>=COUNTIFS(D10:D29,"=Q",G10:G29,"=Q")
</code>```

答:
Actually, what I've found is that there is a way better way instead of the sumproduct, which can result in a overly-long formula if you have 5 columns. Instead, I found that using the SUM+IF function as we use the SUMPRODUCT, will achieve the result faster and better.

=SUM(IF((E:I="ABC")*(B:B="DEF"); 1; 0))

This function returns the number of rows that contain both "ABC" and "DEF" in the defined columns.

Spread the word!

Body:
I am putting in a formula  to count the number of times a quote is required Indicated by the letter Q in a given column, when I put the formula in for one column I get the correct answer, but when I want to do it for multiple columns I get zero, can anyone help please?
the formula is

=COUNTIFS(D10:D29,"=Q",G10:G29,"=Q")


来源: stackexchange

问:
How do I clone a Django model instance object and save it to the database?
```<code>Foo.objects.get(pk="foo")
<Foo: test>
</code>```

In the database, I want to add another object which is a copy of the object above.

Suppose my table has one row. I want to insert the first row object into another row with a different primary key. How can I do that?

答:
There's a clone snippet here, which you can add to your model which does this:</p>

```<code>def clone(self):
  new_kwargs = dict([(fld.name, getattr(old, fld.name)) for fld in old._meta.fields if fld.name != old._meta.pk]);
  return self.__class__.objects.create(**new_kwargs)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Foo.objects.get(pk="foo")
<Foo: test>

In the database, I want to add another object which is a copy of the object above.

Suppose my table has one row. I want to insert the first row object into another row with a different primary key. How can I do that?

Body:
There's a clone snippet here, which you can add to your model which does this:

def clone(self):
  new_kwargs = dict([(fld.name, getattr(old, fld.name)) for fld in old._meta.fields if fld.name != old._meta.pk]);
  return self.__class__.objects.create(**new_kwargs)


问:
Java libraries in machine learning
I'm doing a big machine learning project in Java.

I tried some libraries but they were uncomfortable. Not many algorithms, few examples, unclear function parameters.

So, I wanted to ask if anyone knew a convenient library in Java for machine learning. (In terms of: easy to import, easy to use, lots of samples, etc.)

In addition, I have already read the csv file to a matrix. So if the library uses it, it will be better. Thank you.

答:
Here are a few links

ApacheSAMOA: https://samoa.incubator.apache.org/

Weka: http://www.cs.waikato.ac.nz/ml/weka/

Rapid Miner: https://rapidminer.com/

ContentLicense: CC BY-SA 3.0

Title: Java libraries in machine learning

ContentLicense: CC BY-SA 4.0


问:
I want to pass a list of SqlParameter to a function which executes stored procedure in C#
I want to save two values say @name and @pwd to a table, for this I can use following code in aspx page.

```<code>public void save1()
{
    try
    {
        using (SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["myCon"].ConnectionString))
        {
            using(SqlCommand cmd = new SqlCommand("SP_TEST",con))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@name", txtUname.Text);
                cmd.Parameters.Add("@pwd", txtPwd.Text);

                cmd.ExecuteNonQuery();
            }
        }
    }
    catch (Exception ex)
    { }
}
</code>```

But I want to pass these two variable as a single List<SqlParameter> variable as

```<code>List<SqlParameter> param = new List<SqlParameter>();
param.Add(new SqlParameter("@name", uname));
param.Add(new SqlParameter("@pwd", pwd));
</code>```

Thus the declaration of above function changes from

```<code>public void save1()
</code>```

to

```<code>public void save1(List<SqlParameter> param)
</code>```

But my problem is I don't know how to extract those two variables from this param and then add them to the cmd variable. I need your help.

答:
Have your Save function look like so:

```<code>public void Save1(List<SqlParameter> param)
{
    try
    {
        using (SqlConnection con = new SqlConnection(ConfigurationManager
            .ConnectionStrings["myCon"].ConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand("SP_TEST", con))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                foreach (var item in param)
                    cmd.Parameters.Add(item);
                cmd.ExecuteNonQuery();
            }
        }
    }
    catch (Exception ex)
    {
        /*...*/
    }
}
</code>```

Then have param be accessible to the calling routine as well as the Save1(..) function, like so:

```<code>public/*private*/ List<SqlParameter> param = new List<SqlParameter>();
</code>```

Lastly, your calling routine will call Save1(..) as following:

```<code>string uname = "...";
string pwd = "...";
param.Add(new SqlParameter("@name", uname));
param.Add(new SqlParameter("@pwd", pwd));
Save1(param);
</code>```

Body:
I want to save two values say @name and @pwd to a table, for this I can use following code in aspx page.

public void save1()
{
    try
    {
        using (SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["myCon"].ConnectionString))
        {
            using(SqlCommand cmd = new SqlCommand("SP_TEST",con))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@name", txtUname.Text);
                cmd.Parameters.Add("@pwd", txtPwd.Text);

                cmd.ExecuteNonQuery();
            }
        }
    }
    catch (Exception ex)
    { }
}

But I want to pass these two variable as a single List<SqlParameter> variable as

List<SqlParameter> param = new List<SqlParameter>();
param.Add(new SqlParameter("@name", uname));
param.Add(new SqlParameter("@pwd", pwd));

Thus the declaration of above function changes from

public void save1()

to

public void save1(List<SqlParameter> param)

But my problem is I don't know how to extract those two variables from this param and then add them to the cmd variable. I need your help.

Body:
Have your Save function look like so:

public void Save1(List<SqlParameter> param)
{
    try
    {
        using (SqlConnection con = new SqlConnection(ConfigurationManager
            .ConnectionStrings["myCon"].ConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand("SP_TEST", con))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                foreach (var item in param)
                    cmd.Parameters.Add(item);
                cmd.ExecuteNonQuery();
            }
        }
    }
    catch (Exception ex)
    {
        /*...*/
    }
}

Then have param be accessible to the calling routine as well as the Save1(..) function, like so:

public/*private*/ List<SqlParameter> param = new List<SqlParameter>();

Lastly, your calling routine will call Save1(..) as following:

string uname = "...";
string pwd = "...";
param.Add(new SqlParameter("@name", uname));
param.Add(new SqlParameter("@pwd", pwd));
Save1(param);


问:
GLSL precision qualifiers ignored
We have OpenGLES2.0 shaders that work fine on IOS and most Android devices but on the Amazon Kindle Fire 7 it seems that one of our varying components is losing precision

its defined in the vertex shader and pixel shader as

```<code>varying highp vec4 v_worldposition;
</code>```

and we also have

```<code>precision highp float;
</code>```

at the top of each file.

Yet, on this one device, the precision gets worse and worse the higher the numbers are. There's lots of accuracy around 0, but as the position gets to 200+ the precision drops to about 0.1 units - so it seems that the shader is using 16 bit floating point. In my mind, not highp at all, but maybe that's all it can do?

It's possible that it's using 16 bit floating point for all varying components but it shows up really badly in our case as we are texturing in the pixel shader based on world coordinates.

Does anyone know if there is a way to force 32 bit floating point in the shader or other code, or if the Amazon Fire 7 can even support it. Could it be a setting in the manifest? This is the only Android device we've seen this problem on.

答:
The OpenGLES 2 spec allows devices to only support mediump precision in the fragment shader.

Presumably the Amazon Kindle Fire 7's Mali-450MP4 GPU is one such device. It is possible to query at runtime with glGetShaderPrecisionFormat.

You either have to drop support for such devices (easier said than done because there's no simple manifest option) or you have to refactor your shader so that you don't rely on high precision, or detect at runtime and use a lower detail shader for this sort of device. I tend to do the latter.

Title: GLSL precision qualifiers ignored

Body:
We have OpenGLES2.0 shaders that work fine on IOS and most Android devices but on the Amazon Kindle Fire 7 it seems that one of our varying components is losing precision

its defined in the vertex shader and pixel shader as

varying highp vec4 v_worldposition;

and we also have

precision highp float;

at the top of each file.

Yet, on this one device, the precision gets worse and worse the higher the numbers are. There's lots of accuracy around 0, but as the position gets to 200+ the precision drops to about 0.1 units - so it seems that the shader is using 16 bit floating point. In my mind, not highp at all, but maybe that's all it can do?

It's possible that it's using 16 bit floating point for all varying components but it shows up really badly in our case as we are texturing in the pixel shader based on world coordinates.

Does anyone know if there is a way to force 32 bit floating point in the shader or other code, or if the Amazon Fire 7 can even support it. Could it be a setting in the manifest? This is the only Android device we've seen this problem on.


问:
Why does the NVL2 function don't accept LONG values in its second and third parameters?
The official Oracle database documentation says that the NVL2 function doesn't allow values of type LONG in its second and third parameters though it doesn't explain why. </p>

<p>Why do we have this restriction? Is there any specific reason for this restriction? </p>

答:
Because LONG columns are long, loooong (pun intended :)) deprecated and shouldn't be used anymore: Oracle 9.0.1 -
 Deprecated and Desupported Features

Body:
The official Oracle database documentation says that the NVL2 function doesn't allow values of type LONG in its second and third parameters though it doesn't explain why.

Why do we have this restriction? Is there any specific reason for this restriction?


问:
how to avoid "Not Responding"

Possible Duplicate:

  Keep app responsive during long task

how to avoid "Not Responding", when processing large query or long process looping?

thx

答:
From my perspective you have two choices(depending on HOW LONG the task(or loop) will take):

use a thread as Alexander Malakhov mentioned;

add Application.ProcessMessages(forces the application to draw UI and to respond to events, but it's not as good when the loop takes a lot of time -- use thread..) after each loop completion if you would like the application to respond, however I would recommend it only for -small amount of time- loops, for long intensive loops use threads.

Title: how to avoid "Not Responding"


问:
Twitter share image with text, toast "Image Could Not Be Loaded"
I am getting the toast Image Could Not Be Loaded when I trying and attach an image URL to a tweet. I have changed type but still not working.

My intent code:

```<code>String imageUrl="http://www.cyclesoon.com/admin/assets/img/rideimages/1499161893615.jpg";
Intent tweetIntent = new Intent(Intent.ACTION_SEND);
tweetIntent.putExtra(Intent.EXTRA_TEXT, "Join ride");
tweetIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(imageUrl));
tweetIntent.setType("image/png");

PackageManager packManager = context.getPackageManager();
List<ResolveInfo> resolvedInfoList = packManager.queryIntentActivities(tweetIntent, PackageManager.MATCH_DEFAULT_ONLY);

boolean resolved = false;
for (ResolveInfo resolveInfo : resolvedInfoList) {
    if (resolveInfo.activityInfo.packageName.startsWith("com.twitter.android")) {
        tweetIntent.setClassName(resolveInfo.activityInfo.packageName,resolveInfo.activityInfo.name);
        resolved = true;
        break;
    }
}
if (resolved) {
    startActivity(tweetIntent);
} else {
    Intent i = new Intent();
    i.putExtra(Intent.EXTRA_TEXT, "");
    i.setAction(Intent.ACTION_VIEW);
    i.setData(Uri.parse("https://twitter.com/intent/tweet?text=" + urlEncode("")));
    startActivity(i);
}
</code>```

Any solution appreciates.

答: If you see the documentation, there is a line which says The image Uri should be a file Uri (i.e. file://absolute_path scheme) to a local file. So yes, Image should be on your device. – by  Mohammed Atif

Body:
I am getting the toast Image Could Not Be Loaded when I trying and attach an image URL to a tweet. I have changed type but still not working.

My intent code:

String imageUrl="http://www.cyclesoon.com/admin/assets/img/rideimages/1499161893615.jpg";
Intent tweetIntent = new Intent(Intent.ACTION_SEND);
tweetIntent.putExtra(Intent.EXTRA_TEXT, "Join ride");
tweetIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(imageUrl));
tweetIntent.setType("image/png");

PackageManager packManager = context.getPackageManager();
List<ResolveInfo> resolvedInfoList = packManager.queryIntentActivities(tweetIntent, PackageManager.MATCH_DEFAULT_ONLY);

boolean resolved = false;
for (ResolveInfo resolveInfo : resolvedInfoList) {
    if (resolveInfo.activityInfo.packageName.startsWith("com.twitter.android")) {
        tweetIntent.setClassName(resolveInfo.activityInfo.packageName,resolveInfo.activityInfo.name);
        resolved = true;
        break;
    }
}
if (resolved) {
    startActivity(tweetIntent);
} else {
    Intent i = new Intent();
    i.putExtra(Intent.EXTRA_TEXT, "");
    i.setAction(Intent.ACTION_VIEW);
    i.setData(Uri.parse("https://twitter.com/intent/tweet?text=" + urlEncode("")));
    startActivity(i);
}

Any solution appreciates.


问:
MySQL DB is ignoring foreign key constraints
I've got a really strange (and scary) issue: My mySQL DB is generally ignoring foreign key constraints!

All my tables are InnoDB and I'm creating them with liquibase like this:

```<code><addForeignKeyConstraint baseColumnNames="user_account_id"
    baseTableName="account_transaction"
    constraintName="fk_account_transaction_user_account_id"
    referencedColumnNames="id"
    referencedTableName="user_account"/>
</code>```

The foreign keys are created fine. In HeidiSQL I see them like this:

I also checked for FOREIGN_KEY_CHECKS and I've set it to 1 (SET FOREIGN_KEY_CHECKS=1;)

All my ID columns have the data type BIGINT (dunno if that matters).

What is also worth to mention: The following statement

```<code>  SELECT * FROM information_schema.TABLE_CONSTRAINTS
WHERE CONSTRAINT_SCHEMA = DATABASE();
</code>```

returns a bunch of constraints, but no foreign key constraints... When I execute the same statement on my local mySQL DB, it returns all the constraints INCLUDING foreign key constraints. I can't figure out what's the difference between them though...

Any help is very much appreciated :)

@Update:
So the hint with MyISAM and InnoDB did the trick. I did investigate that before. However, for some reason my tables are InnoDB, but my DB is MyISAM. I'm gonna make further investigations on that :)

答:
As Bill Karwin notes in his comment, FOREIGN KEY constraints are ignored if the table is not InnoDB.

Demonstration:

```<code>CREATE TABLE foo_p
( id BIGINT UNSIGNED PRIMARY KEY
) ENGINE=MYISAM
;

CREATE TABLE foo_c
( id   BIGINT UNSIGNED PRIMARY KEY
, p_id BIGINT UNSIGNED
) ENGINE=MYISAM
;
</code>```

Add a foreign key constraint:

```<code>ALTER TABLE foo_c
  ADD CONSTRAINT fk_foo_c_foo_p
  FOREIGN KEY (id) REFERENCES foo_p (id)
  ON DELETE NO ACTION ON UPDATE NO ACTION
;
</code>```

MySQL creates an index but not a foreign key.

Change storage engine to InnoDB does not create foreign keys:

```<code>ALTER TABLE foo_p ENGINE=INNODB ;

ALTER TABLE foo_c ENGINE=INNODB ;
</code>```

Use SHOW CREATE TABLE foo_c to see table definition:

```<code>CREATE TABLE `foo_c` (
  `id` BIGINT(20) UNSIGNED NOT NULL,
  `p_id` BIGINT(20) UNSIGNED DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_foo_c_foo_p` (`id`)
) ENGINE=INNODB
</code>```

There's an index (converted from the MyISAM definition) but no foreign key.

To add a foreign key:

```<code>ALTER TABLE foo_c
  DROP KEY fk_foo_c_foo_p
, ADD CONSTRAINT fk_foo_c_foo_p
  FOREIGN KEY (p_id) REFERENCES foo_p (id)
  ON DELETE NO ACTION ON UPDATE NO ACTION
;
</code>```

A SHOW CREATE TABLE shows the FOREIGN KEY constraint, as well as the index that was automatically created:

```<code>CREATE TABLE `foo_c` (
  `id` BIGINT(20) UNSIGNED NOT NULL,
  `p_id` BIGINT(20) UNSIGNED DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_foo_c_foo_p` (`p_id`),
  CONSTRAINT `fk_foo_c_foo_p` FOREIGN KEY (`p_id`) REFERENCES `foo_p` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=INNODB
</code>```

Body:
I've got a really strange (and scary) issue: My mySQL DB is generally ignoring foreign key constraints!

All my tables are InnoDB and I'm creating them with liquibase like this:

<addForeignKeyConstraint baseColumnNames="user_account_id"
    baseTableName="account_transaction"
    constraintName="fk_account_transaction_user_account_id"
    referencedColumnNames="id"
    referencedTableName="user_account"/>

The foreign keys are created fine. In HeidiSQL I see them like this:

I also checked for FOREIGN_KEY_CHECKS and I've set it to 1 (SET FOREIGN_KEY_CHECKS=1;)

All my ID columns have the data type BIGINT (dunno if that matters).

What is also worth to mention: The following statement

  SELECT * FROM information_schema.TABLE_CONSTRAINTS
WHERE CONSTRAINT_SCHEMA = DATABASE();

returns a bunch of constraints, but no foreign key constraints... When I execute the same statement on my local mySQL DB, it returns all the constraints INCLUDING foreign key constraints. I can't figure out what's the difference between them though...

Any help is very much appreciated :)

@Update:
So the hint with MyISAM and InnoDB did the trick. I did investigate that before. However, for some reason my tables are InnoDB, but my DB is MyISAM. I'm gonna make further investigations on that :)

Body:
As Bill Karwin notes in his comment, FOREIGN KEY constraints are ignored if the table is not InnoDB.

Demonstration:

CREATE TABLE foo_p
( id BIGINT UNSIGNED PRIMARY KEY
) ENGINE=MYISAM
;

CREATE TABLE foo_c
( id   BIGINT UNSIGNED PRIMARY KEY
, p_id BIGINT UNSIGNED
) ENGINE=MYISAM
;

Add a foreign key constraint:

ALTER TABLE foo_c
  ADD CONSTRAINT fk_foo_c_foo_p
  FOREIGN KEY (id) REFERENCES foo_p (id)
  ON DELETE NO ACTION ON UPDATE NO ACTION
;

MySQL creates an index but not a foreign key.

Change storage engine to InnoDB does not create foreign keys:

ALTER TABLE foo_p ENGINE=INNODB ;

ALTER TABLE foo_c ENGINE=INNODB ;

Use SHOW CREATE TABLE foo_c to see table definition:

CREATE TABLE `foo_c` (
  `id` BIGINT(20) UNSIGNED NOT NULL,
  `p_id` BIGINT(20) UNSIGNED DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_foo_c_foo_p` (`id`)
) ENGINE=INNODB

There's an index (converted from the MyISAM definition) but no foreign key.

To add a foreign key:

ALTER TABLE foo_c
  DROP KEY fk_foo_c_foo_p
, ADD CONSTRAINT fk_foo_c_foo_p
  FOREIGN KEY (p_id) REFERENCES foo_p (id)
  ON DELETE NO ACTION ON UPDATE NO ACTION
;

A SHOW CREATE TABLE shows the FOREIGN KEY constraint, as well as the index that was automatically created:

CREATE TABLE `foo_c` (
  `id` BIGINT(20) UNSIGNED NOT NULL,
  `p_id` BIGINT(20) UNSIGNED DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_foo_c_foo_p` (`p_id`),
  CONSTRAINT `fk_foo_c_foo_p` FOREIGN KEY (`p_id`) REFERENCES `foo_p` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=INNODB


问:
Detect if the incoming call is roaming
Are there any ways to determine if the incoming call is roaming whether regional, national, or international? I'm using libphonenumber to handle some of my call cases but I don't know if it can solve my problem as there is no documentation too.

答:
Use the method isNetworkRoaming():</p>

```<code>private final TelephonyManagertelephonyManager = (TelephonyManager) yourContext.getSystemService(Context.TELEPHONY_SERVICE);

telephonyManager.isNetworkRoaming()
</code>```

Title: Detect if the incoming call is roaming

Body:
Use the method isNetworkRoaming():

private final TelephonyManagertelephonyManager = (TelephonyManager) yourContext.getSystemService(Context.TELEPHONY_SERVICE);

telephonyManager.isNetworkRoaming()


问:
why copy constructor is called when passing temporary by const reference?
I am passing an unnamed temporary object to a function defined with const ref parameter. The copy ctor of the class is private, and I get a compilation error. I don't understand why a copy constructor is called in this situation.

```<code>class A {
public:
  A(int i) {}
private:
  A(const A&) {}
};

void f(const A& a)
{
}

int main()
{
  f(A(1)); // <-- error here: 'A::A(const A&)' is private
}
</code>```

As expected, when I change the main to:

```<code>A a(1);
f(a);
</code>```

it works.

EDIT: the compiler is gcc 4.1.2

答:
You can find the answer to your question in Copy Constructor Needed with temp object or go directly to http://gcc.gnu.org/bugs/#cxx%5Frvalbind

The C++ Standard says that a temporary
  object should be created in this
  context and its contents filled with a
  copy of the object we are trying to
  bind to the reference; it also says
  that the temporary copy can be elided,
  but the semantic constraints (eg.
  accessibility) of the copy constructor
  still have to be checked.

For further information, you can
  consult the following paragraphs of
  the C++ standard: [dcl.init.ref]/5,
  bullet 2, sub-bullet 1, and
  [class.temporary]/2.

Starting with GCC 4.3.0, GCC no longer
  gives an error for this case. This
  change is based on the intent of the
  C++ language committee. As of
  2010-05-28, the final proposed draft
  of the C++0x standard permits this
  code without error.

Body:
I am passing an unnamed temporary object to a function defined with const ref parameter. The copy ctor of the class is private, and I get a compilation error. I don't understand why a copy constructor is called in this situation.

class A {
public:
  A(int i) {}
private:
  A(const A&) {}
};

void f(const A& a)
{
}

int main()
{
  f(A(1)); // <-- error here: 'A::A(const A&)' is private
}

As expected, when I change the main to:

A a(1);
f(a);

it works.

EDIT: the compiler is gcc 4.1.2


问:
F# List.exists on two lists
I have two lists listA and listB where I want to return true if listB contains any element also in listA.

```<code>let listA = ["A";"B";"C"]
let listB = ["D";"E";"A"]
</code>```

Should return true in this case. I feel like this should be easy to solve and I'm missing something fundamental somewhere.

For example, why can't I do like this?

```<code>let testIntersect = for elem in listA do List.exists (fun x -> x = elem) listB
</code>```

答:
One function that you could use is List.except, which is not yet documented (!) but can be seen in this pull request that was merged a couple of years ago. You'd probably use it like this:

```<code>let testIntersect a b =
    let b' = b |> List.except a
    // If b' is shorter than b, then b contained at least one element of a
    List.length b' < List.length b
</code>```

However, this runs through list B about three times, once to do the except algorithm and once each to do both the length calls. So another approach might be to do what you did, but turn list A into a set so that the exists call won't be O(N):

```<code>let testIntersect a b =
    let setA = a |> Set.ofList
    match b |> List.tryFind (fun x -> setA |> Set.contains x) with
    | Some _ -> true
    | None   -> false
</code>```

The reason I used tryFind is because List.find would throw an exception if the predicate didn't match any items of the list.

Edit: An even better approach is to use List.exists, which I temporarily forgot about (thanks to Honza Brestan for reminding me about it):

```<code>let testIntersect a b =
    let setA = a |> Set.ofList
    b |> List.exists (fun x -> setA |> Set.contains x)
</code>```

Which, of course, is pretty much what you were originally wanting to do in your testIntersect code sample. The only difference is that you were using the for ... in syntax in your code sample, which wouldn't work. In F#, the for loop is exclusively for expressions that return unit (and thus, probably have side effects). If you want to return a value, the for loop won't do that. So using the functions that do return value, like List.exists, is the approach you want to take.

Title: F# List.exists on two lists

Body:
I have two lists listA and listB where I want to return true if listB contains any element also in listA.

let listA = ["A";"B";"C"]
let listB = ["D";"E";"A"]

Should return true in this case. I feel like this should be easy to solve and I'm missing something fundamental somewhere.

For example, why can't I do like this?

let testIntersect = for elem in listA do List.exists (fun x -> x = elem) listB

Body:
One function that you could use is List.except, which is not yet documented (!) but can be seen in this pull request that was merged a couple of years ago. You'd probably use it like this:

let testIntersect a b =
    let b' = b |> List.except a
    // If b' is shorter than b, then b contained at least one element of a
    List.length b' < List.length b

However, this runs through list B about three times, once to do the except algorithm and once each to do both the length calls. So another approach might be to do what you did, but turn list A into a set so that the exists call won't be O(N):

let testIntersect a b =
    let setA = a |> Set.ofList
    match b |> List.tryFind (fun x -> setA |> Set.contains x) with
    | Some _ -> true
    | None   -> false

The reason I used tryFind is because List.find would throw an exception if the predicate didn't match any items of the list.

Edit: An even better approach is to use List.exists, which I temporarily forgot about (thanks to Honza Brestan for reminding me about it):

let testIntersect a b =
    let setA = a |> Set.ofList
    b |> List.exists (fun x -> setA |> Set.contains x)

Which, of course, is pretty much what you were originally wanting to do in your testIntersect code sample. The only difference is that you were using the for ... in syntax in your code sample, which wouldn't work. In F#, the for loop is exclusively for expressions that return unit (and thus, probably have side effects). If you want to return a value, the for loop won't do that. So using the functions that do return value, like List.exists, is the approach you want to take.


问:
How to display 3 different Lists next to each other in SAP UI 5?
I've 3 different  Lists that I want to display next to each other, however for some reason they are being displayed under each other.

I am using JSViews.

Here is the relevant parts of my code and screenshot ;

in my JSView ;

```<code>    var keysList = new sap.m.List(this.createId("keysList"), {

    });
    var valList1 = new sap.m.List(this.createId("valList1"), {

    });
    var valList2 = new sap.m.List(this.createId("valList2"), {

    });
    var vBox2 = new sap.m.VBox({
        alignItems: "Start",
        justifyContent: "Start",
        items: [
            keysList,
            valList1,
            valList2
        ]
    }).addStyleClass("vbox2");

    var oPageMerkliste2 = new sap.m.Page({
        showHeader: false,
        content: [
            toolbar,
            vBox1,
            vBox2
        ]
    });

    return oPageMerkliste2;
</code>```

my Controller ;

```<code>        var keysList = this.byId("keysList");
        var keysModel = new sap.ui.model.json.JSONModel();
        keysModel.setData(keysObj);
        console.log("keysList", keysList);
        keysList.setModel(keysModel);
        var template0 = new sap.m.CustomListItem({
            content: [
                new sap.m.VBox({
                    items: [
                        new sap.m.Text({
                            text : "{}"
                        })
                    ]
                }).addStyleClass("listSize")
            ]
        }).addStyleClass("");
        keysList.bindAggregation("items", "/", template0);
        //val list 1
        var valList1 = this.byId("valList1");
        var valList1Model = new sap.ui.model.json.JSONModel();
        valList1Model.setData(valsObj1);
        console.log("valList1", valList1);
        valList1.setModel(valList1Model);
        var template1 = new sap.m.CustomListItem({
            content: [
                new sap.m.VBox({
                    items: [
                        new sap.m.Text({
                            text : "{}"
                        })
                    ]
                }).addStyleClass("listSize")
            ]
        }).addStyleClass("");
        valList1.bindAggregation("items", "/", template1);
            //val2 list
        var valList2 = this.byId("valList2");
        var valList2Model = new sap.ui.model.json.JSONModel();
        valList2Model.setData(valsObj2);
        console.log("valList2", valList2);
        valList2.setModel(valList2Model);
        var template2 = new sap.m.CustomListItem({
            content: [
                new sap.m.VBox({
                    items: [
                        new sap.m.Text({
                            text : "{}"
                        })
                    ]
                }).addStyleClass("listSize")
            ]
        }).addStyleClass("");
        valList2.bindAggregation("items", "/", template2);
</code>```

I thought VBox was actually for displaying the items next to each other but apparently in my case it doesn't behave in the way it actually should.

I tried to play with it on Chrome Dev. Tools and edited styles with changing width s but it didn't help either.

How can I display them next to each other ?   ( Like 0. index of the first  List is next to 0. index of the second List etc.)

And here is a screenshot how my "List" looks so far  ( sorry about bad paint skills)

答:
Try changing VBox with HBox.

```<code>sap.m.HBox
</code>```

In your code, your using VBox, so it is  doing the expected.

Body:
I've 3 different  Lists that I want to display next to each other, however for some reason they are being displayed under each other.

I am using JSViews.

Here is the relevant parts of my code and screenshot ;

in my JSView ;

    var keysList = new sap.m.List(this.createId("keysList"), {

    });
    var valList1 = new sap.m.List(this.createId("valList1"), {

    });
    var valList2 = new sap.m.List(this.createId("valList2"), {

    });
    var vBox2 = new sap.m.VBox({
        alignItems: "Start",
        justifyContent: "Start",
        items: [
            keysList,
            valList1,
            valList2
        ]
    }).addStyleClass("vbox2");

    var oPageMerkliste2 = new sap.m.Page({
        showHeader: false,
        content: [
            toolbar,
            vBox1,
            vBox2
        ]
    });

    return oPageMerkliste2;

my Controller ;

        var keysList = this.byId("keysList");
        var keysModel = new sap.ui.model.json.JSONModel();
        keysModel.setData(keysObj);
        console.log("keysList", keysList);
        keysList.setModel(keysModel);
        var template0 = new sap.m.CustomListItem({
            content: [
                new sap.m.VBox({
                    items: [
                        new sap.m.Text({
                            text : "{}"
                        })
                    ]
                }).addStyleClass("listSize")
            ]
        }).addStyleClass("");
        keysList.bindAggregation("items", "/", template0);
        //val list 1
        var valList1 = this.byId("valList1");
        var valList1Model = new sap.ui.model.json.JSONModel();
        valList1Model.setData(valsObj1);
        console.log("valList1", valList1);
        valList1.setModel(valList1Model);
        var template1 = new sap.m.CustomListItem({
            content: [
                new sap.m.VBox({
                    items: [
                        new sap.m.Text({
                            text : "{}"
                        })
                    ]
                }).addStyleClass("listSize")
            ]
        }).addStyleClass("");
        valList1.bindAggregation("items", "/", template1);
            //val2 list
        var valList2 = this.byId("valList2");
        var valList2Model = new sap.ui.model.json.JSONModel();
        valList2Model.setData(valsObj2);
        console.log("valList2", valList2);
        valList2.setModel(valList2Model);
        var template2 = new sap.m.CustomListItem({
            content: [
                new sap.m.VBox({
                    items: [
                        new sap.m.Text({
                            text : "{}"
                        })
                    ]
                }).addStyleClass("listSize")
            ]
        }).addStyleClass("");
        valList2.bindAggregation("items", "/", template2);

I thought VBox was actually for displaying the items next to each other but apparently in my case it doesn't behave in the way it actually should.

I tried to play with it on Chrome Dev. Tools and edited styles with changing width s but it didn't help either.

How can I display them next to each other ?   ( Like 0. index of the first  List is next to 0. index of the second List etc.)

And here is a screenshot how my "List" looks so far  ( sorry about bad paint skills)

Body:
Try changing VBox with HBox.

sap.m.HBox

In your code, your using VBox, so it is  doing the expected.


问:
Error illegal start of simple expression
I am having this error :

error: illegal start of simple expression
  def process_alcs(lines: List[String]) : List[(String, Double)] = for (line <- lines) yield (val a = line.split(",")) (a[0],a[4].toDouble)

for this line of code :

```<code>def process_alcs(lines: List[String]) : List[(String, Double)] =
  for (line <- lines) yield (val a = line.split(",")) (a[0],a[4].toDouble)
</code>```

I first thought it was a parenthese mismatch but I checked 100 times

答:
Try

```<code> def process_alcs(lines: List[String]) : List[(String, Double)] = for (line <- lines) yield {
   val a = line.split(",")
   (a(0),a(4).toDouble)
 }
</code>```

Basically, you are performing a multi line evaluation in your yield. As such, you must encapsulate the code in it with { instead of (. Also, both statements should be encapsulated in a single {} pair since they build up to what you want to yield.

Additionally, array members in scala are accessed using () and not []. So, you want to use a(0) instead of a[0]

On a separate note, this seems related to another question someone else asked today in which case he wanted to convert to double the value in the 4th column. To access the 4th column, you would want to use a(3).

In that case, the code becomes,

```<code>def process_alcs(lines: List[String]) : List[(String, Double)] = for (line <- lines) yield {
  val a = line.split(",")
  (a(0), a(3).toDouble)
}
</code>```

Hope this helps. Let me know if you have any further questions :)

Edit: To convert to map, try,

```<code>def process_as_map(lines: List[String]) : Map[String, Double] = {
  val results: List[(String, Double)] = for (line <- lines) yield {
    val a = line.split(",")
    (a(0), a(3).toDouble)
  }
  results.toMap
}
</code>```

Refer comments for explanation, on why I tweaked as such based on your code

Body:
I am having this error :

error: illegal start of simple expression
  def process_alcs(lines: List[String]) : List[(String, Double)] = for (line <- lines) yield (val a = line.split(",")) (a[0],a[4].toDouble)

for this line of code :

def process_alcs(lines: List[String]) : List[(String, Double)] =
  for (line <- lines) yield (val a = line.split(",")) (a[0],a[4].toDouble)

I first thought it was a parenthese mismatch but I checked 100 times

Body:
Try

 def process_alcs(lines: List[String]) : List[(String, Double)] = for (line <- lines) yield {
   val a = line.split(",")
   (a(0),a(4).toDouble)
 }

Basically, you are performing a multi line evaluation in your yield. As such, you must encapsulate the code in it with { instead of (. Also, both statements should be encapsulated in a single {} pair since they build up to what you want to yield.

Additionally, array members in scala are accessed using () and not []. So, you want to use a(0) instead of a[0]

On a separate note, this seems related to another question someone else asked today in which case he wanted to convert to double the value in the 4th column. To access the 4th column, you would want to use a(3).

In that case, the code becomes,

def process_alcs(lines: List[String]) : List[(String, Double)] = for (line <- lines) yield {
  val a = line.split(",")
  (a(0), a(3).toDouble)
}

Hope this helps. Let me know if you have any further questions :)

Edit: To convert to map, try,

def process_as_map(lines: List[String]) : Map[String, Double] = {
  val results: List[(String, Double)] = for (line <- lines) yield {
    val a = line.split(",")
    (a(0), a(3).toDouble)
  }
  results.toMap
}

Refer comments for explanation, on why I tweaked as such based on your code


问:
Spicing C with classes
Disclaimer: I am a complete newbie with C, but I've been playing with it trying to mimic some features of classes. Ok, I know that if I want to go that way I should learn C++, but consider the following a little experiment.

Schreiner, in the book Object-oriented programming with ANSI-C suggests a way to use pointers to get object orientation features in C. I must admit I have only skimmed through the book, but I don't like his approach too much. Basically, he uses pointers to functions in order to arrange that

```<code>func(foo);
</code>```

actually results in calling

```<code>foo.methods->func();
</code>```

where foo.methods is a struct containing pointers to functions. The thing I do not like in this approach is that one has to have the global function foo anyway; that is, methods are not namespaced by the class they live in. My feeling is that this will soon lead to clutter: think two objects foo and bar, both having a method func but with a different number of parameters.

So I have tried to get something more fit to my taste. A first attempt is the following (I omit the declarations for sake of brevity)

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

//Instances of this struct will be my objects
struct foo {
    //Properties
    int bar;

    //Methods
    void (* print)(struct foo self);
    void (* printSum)(struct foo self, int delta);
};

//Here is the actual implementation of the methods
static void printFoo(struct foo self) {
    printf("This is bar: %d\n", self.bar);
}

static void printSumFoo(struct foo self, int delta) {
    printf("This is bar plus delta: %d\n", self.bar + delta);
}

//This is a sort of constructor
struct foo Foo(int bar) {
    struct foo foo = {
        .bar = bar,
        .print = &printFoo,
        .printSum = &printSumFoo
    };
    return foo;
}

//Finally, this is how one calls the methods
void
main(void) {
    struct foo foo = Foo(14);
    foo.print(foo); // This is bar: 14
    foo.printSum(foo, 2); // This is bar plus delta: 16
}
</code>```

This is unconvenient but sort of works. What I do not like, though, is that you have to explicitly add the object itself as the first argument. With some preprocessor work I can do a little better:

```<code>#include <stdio.h>
#define __(stuff)     stuff.method(* stuff.object)

//Instances of this struct will be my objects
struct foo {
    //Properties
    int bar;

    //Methods
    //Note: these are now struct themselves
    //and they contain a pointer the object...
    struct {
        void (* method)(struct foo self);
        struct foo * object;
    } print;
};

//Here is the actual implementation of the methods
static void printFoo(struct foo self) {
    printf("This is bar: %d\n", self.bar);
}

//This is a sort of constructor
struct foo Foo(int bar) {
    struct foo foo = {
        .bar = bar,
        //...hence initialization is a little bit different
        .print = {
            .method = &printFoo,
            .object = &foo
        }
    };
    return foo;
}

//Finally, this is how one calls the methods
void
main(void) {
    struct foo foo = Foo(14);
    //This is long and unconvenient...
    foo.print.method(* foo.print.object); // This is bar: 14
    //...but it can be shortened by the preprocessor
    __(foo.print); // This is bar: 14
}
</code>```

This is as far as I can get. The problem here is that it will not work for methods with arguments, as preprocessor macros cannot take a variable number of arguments. Of course one can define macros _0, _1 and so on according to the number of arguments (until one gets tired), but this is hardly a good approach.

Is there any way to improve on this and let C use a more object-oriented syntax?

I should add that actually Schreiner does much more than what I said in his book, but I think the basic construction does not change.

答:
A book (in PDF form) that explains how to do it, is object oriented programming in ANSI C
It's old (1993) but still contains some valid ideas and tips, IMHO.</p>

Title: Spicing C with classes

Body:
Disclaimer: I am a complete newbie with C, but I've been playing with it trying to mimic some features of classes. Ok, I know that if I want to go that way I should learn C++, but consider the following a little experiment.

Schreiner, in the book Object-oriented programming with ANSI-C suggests a way to use pointers to get object orientation features in C. I must admit I have only skimmed through the book, but I don't like his approach too much. Basically, he uses pointers to functions in order to arrange that

func(foo);

actually results in calling

foo.methods->func();

where foo.methods is a struct containing pointers to functions. The thing I do not like in this approach is that one has to have the global function foo anyway; that is, methods are not namespaced by the class they live in. My feeling is that this will soon lead to clutter: think two objects foo and bar, both having a method func but with a different number of parameters.

So I have tried to get something more fit to my taste. A first attempt is the following (I omit the declarations for sake of brevity)

#include <stdio.h>

//Instances of this struct will be my objects
struct foo {
    //Properties
    int bar;

    //Methods
    void (* print)(struct foo self);
    void (* printSum)(struct foo self, int delta);
};

//Here is the actual implementation of the methods
static void printFoo(struct foo self) {
    printf("This is bar: %d\n", self.bar);
}

static void printSumFoo(struct foo self, int delta) {
    printf("This is bar plus delta: %d\n", self.bar + delta);
}

//This is a sort of constructor
struct foo Foo(int bar) {
    struct foo foo = {
        .bar = bar,
        .print = &printFoo,
        .printSum = &printSumFoo
    };
    return foo;
}

//Finally, this is how one calls the methods
void
main(void) {
    struct foo foo = Foo(14);
    foo.print(foo); // This is bar: 14
    foo.printSum(foo, 2); // This is bar plus delta: 16
}

This is unconvenient but sort of works. What I do not like, though, is that you have to explicitly add the object itself as the first argument. With some preprocessor work I can do a little better:

#include <stdio.h>
#define __(stuff)     stuff.method(* stuff.object)

//Instances of this struct will be my objects
struct foo {
    //Properties
    int bar;

    //Methods
    //Note: these are now struct themselves
    //and they contain a pointer the object...
    struct {
        void (* method)(struct foo self);
        struct foo * object;
    } print;
};

//Here is the actual implementation of the methods
static void printFoo(struct foo self) {
    printf("This is bar: %d\n", self.bar);
}

//This is a sort of constructor
struct foo Foo(int bar) {
    struct foo foo = {
        .bar = bar,
        //...hence initialization is a little bit different
        .print = {
            .method = &printFoo,
            .object = &foo
        }
    };
    return foo;
}

//Finally, this is how one calls the methods
void
main(void) {
    struct foo foo = Foo(14);
    //This is long and unconvenient...
    foo.print.method(* foo.print.object); // This is bar: 14
    //...but it can be shortened by the preprocessor
    __(foo.print); // This is bar: 14
}

This is as far as I can get. The problem here is that it will not work for methods with arguments, as preprocessor macros cannot take a variable number of arguments. Of course one can define macros _0, _1 and so on according to the number of arguments (until one gets tired), but this is hardly a good approach.

Is there any way to improve on this and let C use a more object-oriented syntax?

I should add that actually Schreiner does much more than what I said in his book, but I think the basic construction does not change.


问:
How can I return a value from the main function when using a nested forEach loop without a temporary variable?
I would like to return primaryNumber without having to use a an extra variable for it.

I would like an arrow statement function that just returns element.number without needing primaryNumber. As it stands the inner forEach is in a different scope so I can't just return element.number from findPrimaryNumber(). Is there a good solution?

```<code>function findPrimaryNumber(gender, naturalExpressionYearOfBirth) {
    let primaryNumber, primaryNumberGenderObject;
    if (gender === "f") {
        primaryNumberGenderObject = primaryNumberFemales;
    } else if (gender === "m") {
        primaryNumberGenderObject = primaryNumberMales;
    }

    primaryNumberGenderObject.forEach(element => {
        element.year.forEach(yearWeAreLookingFor => {
            if (yearWeAreLookingFor === naturalExpressionYearOfBirth) {
                primaryNumber = element.number;
            }
        });
    });
    return primaryNumber;
}
</code>```

Here is an example of the object it is searching:

```<code>const primaryNumberMales = [{
    name: "Fire Yin",
    number: 9,
    year: [1910,
      1919,
      1928,
      1937,
      1946,
      1955,
      1964,
      1973,
      1982,
      1991,
      2000,
      2009,
      2018
    ]
  },
  {
    name: "Mountain Yang",
    number: 8,
    year: [1911,
      1920,
      1929,
      1938,
      1947,
      1956,
      1965,
      1974,
      1983,
      1992,
      2001,
      2010,
      2019,
    ]
  },
  {
    name: "Lake Yin",
    number: 7,
    year: [1912,
      1921,
      1930,
      1939,
      1948,
      1957,
      1966,
      1975,
      1984,
      1993,
      2002,
      2011,
      2020,
    ]
  },
  {
    name: "Sky Yang",
    number: 6,
    year: [1913,
      1922,
      1931,
      1940,
      1949,
      1958,
      1967,
      1976,
      1985,
      1994,
      2003,
      2012,
      2021,
    ]
  },
  {
    name: "Earth Core Yang",
    number: 5,
    year: [1914,
      1923,
      1932,
      1941,
      1950,
      1959,
      1968,
      1977,
      1986,
      1995,
      2004,
      2013,
      2022,
    ]
  },
  {
    name: "Wind Yin",
    number: 4,
    year: [1915,
      1924,
      1933,
      1942,
      1951,
      1960,
      1969,
      1978,
      1987,
      1996,
      2005,
      2014,
      2023,
    ]
  },
  {
    name: "Thunder Yang",
    number: 3,
    year: [1916,
      1925,
      1934,
      1943,
      1952,
      1961,
      1970,
      1979,
      1988,
      1997,
      2006,
      2015,
      2024,
    ]
  },
  {
    name: "Earth Yin",
    number: 2,
    year: [1917,
      1926,
      1935,
      1944,
      1953,
      1962,
      1971,
      1980,
      1989,
      1998,
      2007,
      2016,
      2025,
    ]
  },
  {
    name: "Sea Yang",
    number: 1,
    year: [1918,
      1927,
      1936,
      1945,
      1954,
      1963,
      1972,
      1981,
      1990,
      1999,
      2008,
      2017,
      2026,
    ]
  }
];
</code>```

答:
You can try this by using .find

```<code>function findPrimaryNumber(gender, naturalExpressionYearOfBirth) {
    let primaryNumberGenderObject;

    if (gender === "f") {
      primaryNumberGenderObject = primaryNumberFemales;
    } else if (gender === "m") {
      primaryNumberGenderObject = primaryNumberMales;
    }

    return (primaryNumberGenderObject.find(element =>
      element.year.includes(naturalExpressionYearOfBirth)
    ) || {}).number

    // OR AN INNER FIND, NOT SO ADVISABLE
    // return (primaryNumberGenderObject.find(element =>
    //   element.year.find(yearWeAreLookingFor =>
    //     yearWeAreLookingFor === naturalExpressionYearOfBirth
    //   )
    // ) || {}).number
}
</code>```

Body:
I would like to return primaryNumber without having to use a an extra variable for it.

I would like an arrow statement function that just returns element.number without needing primaryNumber. As it stands the inner forEach is in a different scope so I can't just return element.number from findPrimaryNumber(). Is there a good solution?

function findPrimaryNumber(gender, naturalExpressionYearOfBirth) {
    let primaryNumber, primaryNumberGenderObject;
    if (gender === "f") {
        primaryNumberGenderObject = primaryNumberFemales;
    } else if (gender === "m") {
        primaryNumberGenderObject = primaryNumberMales;
    }

    primaryNumberGenderObject.forEach(element => {
        element.year.forEach(yearWeAreLookingFor => {
            if (yearWeAreLookingFor === naturalExpressionYearOfBirth) {
                primaryNumber = element.number;
            }
        });
    });
    return primaryNumber;
}

Here is an example of the object it is searching:

const primaryNumberMales = [{
    name: "Fire Yin",
    number: 9,
    year: [1910,
      1919,
      1928,
      1937,
      1946,
      1955,
      1964,
      1973,
      1982,
      1991,
      2000,
      2009,
      2018
    ]
  },
  {
    name: "Mountain Yang",
    number: 8,
    year: [1911,
      1920,
      1929,
      1938,
      1947,
      1956,
      1965,
      1974,
      1983,
      1992,
      2001,
      2010,
      2019,
    ]
  },
  {
    name: "Lake Yin",
    number: 7,
    year: [1912,
      1921,
      1930,
      1939,
      1948,
      1957,
      1966,
      1975,
      1984,
      1993,
      2002,
      2011,
      2020,
    ]
  },
  {
    name: "Sky Yang",
    number: 6,
    year: [1913,
      1922,
      1931,
      1940,
      1949,
      1958,
      1967,
      1976,
      1985,
      1994,
      2003,
      2012,
      2021,
    ]
  },
  {
    name: "Earth Core Yang",
    number: 5,
    year: [1914,
      1923,
      1932,
      1941,
      1950,
      1959,
      1968,
      1977,
      1986,
      1995,
      2004,
      2013,
      2022,
    ]
  },
  {
    name: "Wind Yin",
    number: 4,
    year: [1915,
      1924,
      1933,
      1942,
      1951,
      1960,
      1969,
      1978,
      1987,
      1996,
      2005,
      2014,
      2023,
    ]
  },
  {
    name: "Thunder Yang",
    number: 3,
    year: [1916,
      1925,
      1934,
      1943,
      1952,
      1961,
      1970,
      1979,
      1988,
      1997,
      2006,
      2015,
      2024,
    ]
  },
  {
    name: "Earth Yin",
    number: 2,
    year: [1917,
      1926,
      1935,
      1944,
      1953,
      1962,
      1971,
      1980,
      1989,
      1998,
      2007,
      2016,
      2025,
    ]
  },
  {
    name: "Sea Yang",
    number: 1,
    year: [1918,
      1927,
      1936,
      1945,
      1954,
      1963,
      1972,
      1981,
      1990,
      1999,
      2008,
      2017,
      2026,
    ]
  }
];

Body:
You can try this by using .find

function findPrimaryNumber(gender, naturalExpressionYearOfBirth) {
    let primaryNumberGenderObject;

    if (gender === "f") {
      primaryNumberGenderObject = primaryNumberFemales;
    } else if (gender === "m") {
      primaryNumberGenderObject = primaryNumberMales;
    }

    return (primaryNumberGenderObject.find(element =>
      element.year.includes(naturalExpressionYearOfBirth)
    ) || {}).number

    // OR AN INNER FIND, NOT SO ADVISABLE
    // return (primaryNumberGenderObject.find(element =>
    //   element.year.find(yearWeAreLookingFor =>
    //     yearWeAreLookingFor === naturalExpressionYearOfBirth
    //   )
    // ) || {}).number
}


问:
Beautifulsoup code no longer working in python script
I have a python script that I am having trouble with and I think I have narrowed the issue down to this line:

```<code>formkey = soup.find_all("script")[9].string[153:][:-141]
</code>```

I believe that this line is supposed to return the value of "form_key" on this page https://shop.adidas.ae/en/forum-mis-wrap-shoes/BY4412.html

Is there something I'm missing? Thanks

答:
if you want the value of input with name="form_key"

do:

```<code>form_key_value = soup.find('input', {'name':'form_key'})['value']
</code>```

Looking at the source of the page, this value is what you want and it is easier to get it this way and also more Pythonic than to parse the JavaScript

Body:
I have a python script that I am having trouble with and I think I have narrowed the issue down to this line:

formkey = soup.find_all("script")[9].string[153:][:-141]

I believe that this line is supposed to return the value of "form_key" on this page https://shop.adidas.ae/en/forum-mis-wrap-shoes/BY4412.html

Is there something I'm missing? Thanks

Body:
if you want the value of input with name="form_key"

do:

form_key_value = soup.find('input', {'name':'form_key'})['value']

Looking at the source of the page, this value is what you want and it is easier to get it this way and also more Pythonic than to parse the JavaScript


问:
htaccess redirect for Angular routes
I have an angular application with several routes, such as:

```<code>site.com/
site.com/page
site.com/page/4
</code>```

Using angular's html5 routing mode, these resolve correctly when you click links to them from within the application, but of course are 404 errors when you do a hard refresh. To fix this, I've tried implementing a basic htaccess rewrite.

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_METHOD} !OPTIONS
RewriteRule ^(.*)$ index.html [L]
</code>```

This works for the angular requests, however when I try to load scripts or make ajax calls within my domain, such as:

```<code><script src="/app/programs/script.js"></script>
</code>```

This script doesn't load - it's request is redirected and it tries to load the index.html page as the .htaccess thinks it should reroute the request - not knowing that this file does exist and it should load the file instead of redirect.

Is there any way I can have the htaccess redirect the request to index.html (with the view parameters) only if there is not an actual file that it should resolve to?

答:
I will provide another detailed htaccess file in case you need to :

Considerate the baseUrl and default index file

Remove the leading slash to manage :params

Here is my htaccess, very close, but more specific :

```<code>DirectoryIndex index.html
RewriteEngine on
RewriteBase /subDir
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^(.*) index.html [NC,L]
</code>```

Title: htaccess redirect for Angular routes

Body:
I have an angular application with several routes, such as:

site.com/
site.com/page
site.com/page/4

Using angular's html5 routing mode, these resolve correctly when you click links to them from within the application, but of course are 404 errors when you do a hard refresh. To fix this, I've tried implementing a basic htaccess rewrite.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_METHOD} !OPTIONS
RewriteRule ^(.*)$ index.html [L]

This works for the angular requests, however when I try to load scripts or make ajax calls within my domain, such as:

This script doesn't load - it's request is redirected and it tries to load the index.html page as the .htaccess thinks it should reroute the request - not knowing that this file does exist and it should load the file instead of redirect.

Is there any way I can have the htaccess redirect the request to index.html (with the view parameters) only if there is not an actual file that it should resolve to?

Body:
I will provide another detailed htaccess file in case you need to :

Considerate the baseUrl and default index file

Remove the leading slash to manage :params

Here is my htaccess, very close, but more specific :

DirectoryIndex index.html
RewriteEngine on
RewriteBase /subDir
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^(.*) index.html [NC,L]


问:
Javascript image refresh with preload, loading issues
I have a small *.html file showing and regularly updating a *.png file.
To prevent flashing during the reload, I preload the image within the code.

Although I observe, that during some refereshs (seems random), the image is only displayed partially (1/2 to 1/3 in lower part is blank white) and takes a delay to finish loading.

How can I prevent this?

index.html

```<code><html>
<body onload="update();">
    <script src="update.js"></script>
    <div id="container">
       <img id="img_display" src="my_image.png"/>
    </div>
</html>
</code>```

update.js

```<code>function update() {
    update_image();
    setTimeout(update, 1000);
}

function update_image() {
    //timestamp as random identifier
    var timestamp = new Date().getTime();
    //create image path, appending timestamp to force reload of image instead of using chached version
    var s_src = "my_image.png?random=" + timestamp;
    // preload image to prevent flashing
    var img = new Image();
    img.src = s_src;
    // get img container ID
    var s_id = "img_display";
    // refresh source parameter
    document.getElementById(s_id).src = s_src;
}
</code>```

答:
In update.js

/*Instead of */

function update() {
    update_image();
    setTimeout("update();", 1000);
}

/*Use */

function update() {
    setTimeout(function(){ update_image(); }, 1000);
}

Body:
I have a small *.html file showing and regularly updating a *.png file.
To prevent flashing during the reload, I preload the image within the code.

Although I observe, that during some refereshs (seems random), the image is only displayed partially (1/2 to 1/3 in lower part is blank white) and takes a delay to finish loading.

How can I prevent this?

index.html

update.js

function update() {
    update_image();
    setTimeout(update, 1000);
}

function update_image() {
    //timestamp as random identifier
    var timestamp = new Date().getTime();
    //create image path, appending timestamp to force reload of image instead of using chached version
    var s_src = "my_image.png?random=" + timestamp;
    // preload image to prevent flashing
    var img = new Image();
    img.src = s_src;
    // get img container ID
    var s_id = "img_display";
    // refresh source parameter
    document.getElementById(s_id).src = s_src;
}


问:
Testing a function that may produce different outputs every time it is called
Given the function:

```<code>static boolean chance(int percentage) {
    return percentage != 0 && random.nextInt(101) <= percentage;
}
</code>```

and a test for that function:

```<code>@Test
public void chance_AlwaysFalse_Percentage0() {
    assertFalse(chance(0));
}
</code>```

The test does not provide with certainty that chance will always return true. I could change the change function to the following:

```<code>static boolean chance(int percentage) {
    return random.nextInt(101) <= percentage;
}
</code>```

and the test would still pass. However, there is a very small chance that random.nextInt(100) will return 0, which would make the function return true, making the test fail.

I could execute this test a billion times as well, but given the nature of random numbers, there is still a minimal chance of failure.

How should I go about testing a function like this? Should it be tested at all? What is a better approach to this problem?

答:
Automated tests can't catch everything.  In fact, the first example of your function might also have a bug, in that chance(1) will have a 2% chance instead of a 1% chance of returning true (since it would return true if the random number was either 0 or 1).  But if you only test 0 and 100, it would pass those tests 100% of the time.  (In fact, 0 and 100 are the only values that will return true the correct percentage of the time; everything else will be off by 1%.  The effects of that bug are subtle enough that you may or may not ever notice it, depending on how the function is used.)

You could put your tests in a loop, if you really wanted to.  If you ran the chance_AlwaysFalse_Percentage0 test 10,000 times, the odds would be very much in favor of any particular random number being hit.  (No, it's not technically guaranteed, but if you calculate the odds, I think you'd be satisfied.)  I'm not sure if that's worth doing.

Body:
Given the function:

static boolean chance(int percentage) {
    return percentage != 0 && random.nextInt(101) <= percentage;
}

and a test for that function:

@Test
public void chance_AlwaysFalse_Percentage0() {
    assertFalse(chance(0));
}

The test does not provide with certainty that chance will always return true. I could change the change function to the following:

static boolean chance(int percentage) {
    return random.nextInt(101) <= percentage;
}

and the test would still pass. However, there is a very small chance that random.nextInt(100) will return 0, which would make the function return true, making the test fail.

I could execute this test a billion times as well, but given the nature of random numbers, there is still a minimal chance of failure.

How should I go about testing a function like this? Should it be tested at all? What is a better approach to this problem?


问:
Given action, reducer returned undefined
I'm doing my first react.js app. Because of some issues with the react & redux template project in Visual Studio 2017 I ended up with a Web API in Visual Studio 2017 and a whole different react project in Visual Studio Code (I don't know if that is relevant). I'm trying to consume my Web API but my action.payload.data is always undefined. Also I get a cross-origin error. I don't get what am I doing wrong.

src/actions/index.js

```<code>import axios from 'axios';

export const FETCH_HOME = 'fetch_home';

const R00T_URL = 'http://localhost:52988/api';

export function fetchHome() {
    const request = axios.get(`${R00T_URL}/home`, { crossdomain: true });

    console.log(`request: ${request}`);
    return {
        type: FETCH_HOME,
        payload: request
    };
}
</code>```

src/reducers/reducer_home.js

```<code>import { FETCH_HOME } from '../actions';

export default function(state = {}, action) {
    if (typeof action.payload === 'undefined') {
        console.log('action undefined');
        return state;
    }

    switch (action.type) {
        case FETCH_HOME:
            console.log(`action: ${action}`);
            return action.payload.data;
        default:
            return state;
    }
}
</code>```

src/components/home_index.js

```<code>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchHome } from '../actions';

class HomeIndex extends Component {
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        this.props.fetchHome();
    }

    render() {
        console.log(`props: ${this.props}`);
        return (
            <div>
                <h1>Home Index</h1>
            </div>
        );
    }
}

function mapStateToProps(state) {
    return { props: state.props };
}

export default connect(mapStateToProps, { fetchHome })(HomeIndex);
</code>```

src/index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { BrowserRouter, Route } from 'react-router-dom';
import reducers from './reducers';
import HomeIndex from './components/home_index';
import promise from 'redux-promise';

const createStoreWithMiddleware = applyMiddleware(promise)(createStore);

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <BrowserRouter>
      <div>
        <Route path="/" component={HomeIndex} />
      </div>
    </BrowserRouter>
  </Provider>
  , document.querySelector('.container'));
</code>```

答:
Your call to axios.get() is asynchronous.

You likely want your action creator to return the action object, like this:

src/actions/index.js

```<code>...

export function fetchHome(result) {
  return {
    type: FETCH_HOME,
    payload: result
  }
}
</code>```

...and then perform the async request in your component and call the action creator with the results:

src/components/home_index.js

```<code>...

componentDidMount() {
  axios.get(`${R00T_URL}/home`, { crossdomain: true })
    .then(result => {
      console.log(`result: ${result}`);
      this.props.fetchHome(result)
    })
    .catch(err => {
      // Handle error
    })
}

...
</code>```

If you want to keep the async part in your action creator then look at using redux-thunk:
https://www.npmjs.com/package/redux-thunk

Body:
I'm doing my first react.js app. Because of some issues with the react & redux template project in Visual Studio 2017 I ended up with a Web API in Visual Studio 2017 and a whole different react project in Visual Studio Code (I don't know if that is relevant). I'm trying to consume my Web API but my action.payload.data is always undefined. Also I get a cross-origin error. I don't get what am I doing wrong.

src/actions/index.js

import axios from 'axios';

export const FETCH_HOME = 'fetch_home';

const R00T_URL = 'http://localhost:52988/api';

export function fetchHome() {
    const request = axios.get(`${R00T_URL}/home`, { crossdomain: true });

    console.log(`request: ${request}`);
    return {
        type: FETCH_HOME,
        payload: request
    };
}

src/reducers/reducer_home.js

import { FETCH_HOME } from '../actions';

export default function(state = {}, action) {
    if (typeof action.payload === 'undefined') {
        console.log('action undefined');
        return state;
    }

    switch (action.type) {
        case FETCH_HOME:
            console.log(`action: ${action}`);
            return action.payload.data;
        default:
            return state;
    }
}

src/components/home_index.js

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchHome } from '../actions';

class HomeIndex extends Component {
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        this.props.fetchHome();
    }

    render() {
        console.log(`props: ${this.props}`);
        return (

Home Index

        );
    }
}

function mapStateToProps(state) {
    return { props: state.props };
}

export default connect(mapStateToProps, { fetchHome })(HomeIndex);

src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { BrowserRouter, Route } from 'react-router-dom';
import reducers from './reducers';
import HomeIndex from './components/home_index';
import promise from 'redux-promise';

const createStoreWithMiddleware = applyMiddleware(promise)(createStore);

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <BrowserRouter>

        <Route path="/" component={HomeIndex} />

    </BrowserRouter>
  </Provider>
  , document.querySelector('.container'));

Body:
Your call to axios.get() is asynchronous.

You likely want your action creator to return the action object, like this:

src/actions/index.js

...

export function fetchHome(result) {
  return {
    type: FETCH_HOME,
    payload: result
  }
}

...and then perform the async request in your component and call the action creator with the results:

src/components/home_index.js

...

componentDidMount() {
  axios.get(`${R00T_URL}/home`, { crossdomain: true })
    .then(result => {
      console.log(`result: ${result}`);
      this.props.fetchHome(result)
    })
    .catch(err => {
      // Handle error
    })
}

...

If you want to keep the async part in your action creator then look at using redux-thunk:
https://www.npmjs.com/package/redux-thunk


问:
(iphone) how to set 'atomic' @property for a variable?
I want to use an integer variable from multiple threads.

Hence I want to make getter/setter atomic operation.

at header file

```<code>@property (retain) NSNumber* myNumber;
</code>```

at implementation file

```<code>@synthesize myNumber;
</code>```

won't compile, what am i missing?

(type of property ‘myNumber’ does not match type of ivar ‘myNumber’)

- edit, I declared it as int myNumber; compilation problem solved

Also, can I use plain int for this? (not NSNumber* )

答:
In general, you may use int instead of NSNumber. Type choice depends on the problem you are trying to solve.

The particular error message you get says that your instance variable has a different type than the property with the same name. Do you clare your ivar as int myNumber? In this case you should write

```<code>@property int myNumber;
</code>```

Update

Since properties are atomic by default, you do not need to explicitly write:

```<code>@property (atomic) int myNumber;
</code>```

Body:
I want to use an integer variable from multiple threads.

Hence I want to make getter/setter atomic operation.

at header file

@property (retain) NSNumber* myNumber;

at implementation file

@synthesize myNumber;

won't compile, what am i missing?

(type of property ‘myNumber’ does not match type of ivar ‘myNumber’)

- edit, I declared it as int myNumber; compilation problem solved

Also, can I use plain int for this? (not NSNumber* )

Body:
In general, you may use int instead of NSNumber. Type choice depends on the problem you are trying to solve.

The particular error message you get says that your instance variable has a different type than the property with the same name. Do you clare your ivar as int myNumber? In this case you should write

@property int myNumber;

Update

Since properties are atomic by default, you do not need to explicitly write:

@property (atomic) int myNumber;


问:
Specify an optional pathname with React router v4
So I have this route declared in my index.js for the React FE:

```<code><Route exact path='/documents/:survey_id' component={protectedRoute(Documents)} />
</code>```

I want to return the same component even if the route is /documents. In that case, the component would just render with the first :survey_id in the users list. I guess I could just add another route like:

```<code><Route exact path='/documents/:survey_id' component={protectedRoute(Documents)} />
<Route exact path='/documents' component={protectedRoute(Documents)} />
</code>```

Kind of repetitive so wonder if there is a better way.

答:
Instead of having an additional Route, what you could do is have an optional path in your Route path like

```<code><Route exact path='/documents(/:survey_id)?' component={protectedRoute(Documents)} />
</code>```

NOTE: React path parameters are provided in a way which
  path-to-regexp understands.  So to define a parameter as
  optional you add a trailing question-mark ?.

Body:
So I have this route declared in my index.js for the React FE:

<Route exact path='/documents/:survey_id' component={protectedRoute(Documents)} />

I want to return the same component even if the route is /documents. In that case, the component would just render with the first :survey_id in the users list. I guess I could just add another route like:

<Route exact path='/documents/:survey_id' component={protectedRoute(Documents)} />
<Route exact path='/documents' component={protectedRoute(Documents)} />

Kind of repetitive so wonder if there is a better way.

Body:
Instead of having an additional Route, what you could do is have an optional path in your Route path like

<Route exact path='/documents(/:survey_id)?' component={protectedRoute(Documents)} />

NOTE: React path parameters are provided in a way which
  path-to-regexp understands.  So to define a parameter as
  optional you add a trailing question-mark ?.


问:
Rails datetime_select month names not showing internationalization
I am having a problem with datetime_select month rails view control.

After integrating new localization to my website (bs_BA) Bosnian, I have a problem where names of months not showing correctly.

This is my view control with slim syntax:

```<code>= f.datetime_select :event_date, :order => [:day,:month,:year], class:'form-control'
</code>```

Also I have a gem 'rails-i18n' installed.

All other label translations are okay, just having issue with 'month' drop-down content.

答:
This is fix in my case filling bs_BA.yml with:

```<code>  date:
    order: [ !ruby/symbol day, !ruby/symbol month, !ruby/symbol year ]
    formats:
      default: "%Y-%m-%d"
      short: "%b %d"
      long: "%B %d, %Y"
    day_names: [Ponedjeljak, Utorak, Srijeda, Cetvrtak, Petak, Subota, Nedjelja]
    #abbr_day_names: [P, U, S, C, Pt, S, N]
    month_names: [~, Januar, Februar, Mart, April, Maj, Juni, Juli, August, Septembar, Oktobar, Novembar, Decembar]
    #abbr_month_names: [~, Jan, Feb, Mar, Apr, Maj, Jun, Jul, Aug, Sep, Okt, Nov, Dec]
</code>```

Body:
I am having a problem with datetime_select month rails view control.

After integrating new localization to my website (bs_BA) Bosnian, I have a problem where names of months not showing correctly.

This is my view control with slim syntax:

= f.datetime_select :event_date, :order => [:day,:month,:year], class:'form-control'

Also I have a gem 'rails-i18n' installed.

All other label translations are okay, just having issue with 'month' drop-down content.

Body:
This is fix in my case filling bs_BA.yml with:

  date:
    order: [ !ruby/symbol day, !ruby/symbol month, !ruby/symbol year ]
    formats:
      default: "%Y-%m-%d"
      short: "%b %d"
      long: "%B %d, %Y"
    day_names: [Ponedjeljak, Utorak, Srijeda, Cetvrtak, Petak, Subota, Nedjelja]
    #abbr_day_names: [P, U, S, C, Pt, S, N]
    month_names: [~, Januar, Februar, Mart, April, Maj, Juni, Juli, August, Septembar, Oktobar, Novembar, Decembar]
    #abbr_month_names: [~, Jan, Feb, Mar, Apr, Maj, Jun, Jul, Aug, Sep, Okt, Nov, Dec]


问:
Stop .py files from terminating after script execution
I wrote a script that works, but when I open it as a .py file email attachment, after I finish answer the inputs and it runs, it closes. What can I do to stop this. Here is the code if it helps:</p>

```<code># Write a program to solve an ancient Chinese puzzle: We count 35 heads
# and 94 legs among the chickens and rabbits on a farm. How many rabbits
# and how many chickens are there?

# Inputs the number of heads and legs, respectively.
# Makes sure it is read as an integer.

h=input('Enter the number of heads:')
heads=int(h)
le=input('Enter the number of legs:')
legs=int(le)

# Executes a while loop while the total number of rabbits is less
# than or equal to 35.

rabbits=0
while rabbits <= heads:
    chickens = heads - rabbits

# Prints the result if there are 35 heads and 94 legs found.

    if 2 * chickens + 4 * rabbits == legs and chickens + rabbits == heads:
        print('There are', rabbits, 'rabbits and',  chickens, 'chickens.')
        break
    rabbits+=1

if 2 * chickens + 4 * rabbits != legs or chickens + rabbits != heads:
    print('No answer.')
</code>```

答:
You could easily just put input() at the end of your script to keep it from terminating.

As you may know, input() takes in a string from the standard input and then you can do with it whatever you want which in this situation isn't necessary.

Body:
I wrote a script that works, but when I open it as a .py file email attachment, after I finish answer the inputs and it runs, it closes. What can I do to stop this. Here is the code if it helps:

# Write a program to solve an ancient Chinese puzzle: We count 35 heads
# and 94 legs among the chickens and rabbits on a farm. How many rabbits
# and how many chickens are there?

# Inputs the number of heads and legs, respectively.
# Makes sure it is read as an integer.

h=input('Enter the number of heads:')
heads=int(h)
le=input('Enter the number of legs:')
legs=int(le)

# Executes a while loop while the total number of rabbits is less
# than or equal to 35.

rabbits=0
while rabbits <= heads:
    chickens = heads - rabbits

# Prints the result if there are 35 heads and 94 legs found.

    if 2 * chickens + 4 * rabbits == legs and chickens + rabbits == heads:
        print('There are', rabbits, 'rabbits and',  chickens, 'chickens.')
        break
    rabbits+=1

if 2 * chickens + 4 * rabbits != legs or chickens + rabbits != heads:
    print('No answer.')


问:
Load module to invoke its decorators
I have a program consistring of several modules specifying the respective web application handlers and one, specifying the respective router.

The library I use can be found here.

Excerpt from webapp.service (there are more such modules):

```<code>from webapp.router import ROUTER

@ROUTER.route('/service/[id:int]')
class ServicePermissions(AuthenticatedService):
    """Handles service permissions."""

    NODE = 'services'
    NAME = 'services manager'
    DESCRIPTION = 'Manages services permissions'
    PROMOTE = False
</code>```

webapp.router:

```<code>ROUTER = Router()
</code>```

When I import the webapp.router module, the webapp.service module does obviously not run. Hence, the @ROUTER.route('/service/[id:int]') decorator is not run and my web aplication will fail with the message, that the respective route is not available.

What is the best practice in that case to run the code in webapp.service to "run" the decorators? I do not really need to import the module itself or any of its members.

答:
As stated in the comments fot the question,
you simply have to import the modules. As for linter complaints, those are the lesser of your problems. Linters are there to help - if they get into the way, just don't listen to them.

So, the simple way just to get your things working is, at the end of your __main__.py or __init__.py, depending on your app structure, to import explicitly all the modules that make use of the view decorator.

If you have a linter, check how to silence it on the import lines - that is usually accomplished with a special comment on the import line.

Python's introspection is fantastic, but it can't find instances of a class, or subclasses, if those are defined in modules that are not imported: such a module is just a text file sitting on the disk, like any data file.

What some frameworks offer as an approach is to have a "discovery" utility that will silently import all "py" files in the project folders. That way your views can "come into existence" without explicit imports.

You could use a function like:

```<code>import os

def discover(caller_file):
    caller_folder = os.path.dirname(caller_file)
    for current, folders, files in os.walk(caller_folder):
        if current == "__pycache__":
            continue
        for file in files:
            if file.endswith(".py"):
                __import__(os.path.join(current, file))
</code>```

And call it on your main module with discover(__file__)

Title: Load module to invoke its decorators

Body:
I have a program consistring of several modules specifying the respective web application handlers and one, specifying the respective router.

The library I use can be found here.

Excerpt from webapp.service (there are more such modules):

from webapp.router import ROUTER

@ROUTER.route('/service/[id:int]')
class ServicePermissions(AuthenticatedService):
    """Handles service permissions."""

    NODE = 'services'
    NAME = 'services manager'
    DESCRIPTION = 'Manages services permissions'
    PROMOTE = False

webapp.router:

ROUTER = Router()

When I import the webapp.router module, the webapp.service module does obviously not run. Hence, the @ROUTER.route('/service/[id:int]') decorator is not run and my web aplication will fail with the message, that the respective route is not available.

What is the best practice in that case to run the code in webapp.service to "run" the decorators? I do not really need to import the module itself or any of its members.

Body:
As stated in the comments fot the question,
you simply have to import the modules. As for linter complaints, those are the lesser of your problems. Linters are there to help - if they get into the way, just don't listen to them.

So, the simple way just to get your things working is, at the end of your __main__.py or __init__.py, depending on your app structure, to import explicitly all the modules that make use of the view decorator.

If you have a linter, check how to silence it on the import lines - that is usually accomplished with a special comment on the import line.

Python's introspection is fantastic, but it can't find instances of a class, or subclasses, if those are defined in modules that are not imported: such a module is just a text file sitting on the disk, like any data file.

What some frameworks offer as an approach is to have a "discovery" utility that will silently import all "py" files in the project folders. That way your views can "come into existence" without explicit imports.

You could use a function like:

import os

def discover(caller_file):
    caller_folder = os.path.dirname(caller_file)
    for current, folders, files in os.walk(caller_folder):
        if current == "__pycache__":
            continue
        for file in files:
            if file.endswith(".py"):
                __import__(os.path.join(current, file))

And call it on your main module with discover(__file__)


问:
Updateing mysql json field in array
Having this json:

```<code>{
    f1: "abc",
    f2: [
        {id: 1, val:"a"},
        {id: 2, val:"b"},
        {id: 3, val:"c"}
    ],
    f3: [
        "a",
        "b",
        "c"
    ]
}
</code>```

Update:
As an example:

```<code>SELECT JSON_SEARCH(
'{"f1": "abc", "f2": [{"id": "1", "val":"a"},{"id": "2", "2":"b"},{"id": 3, "val":"2"}], "f3": ["a","b","c"]}',
'all', '1', null, '$.f2[*].id');
</code>```

returns the needed path for f2->id==1
I can then use

```<code>select json_set(
'{"f1": "abc", "f2": [{"id": "1", "val":"a"},{"id": "2", "2":"b"},{"id": 3, "val":"2"}], "f3": ["a","b","c"]}',
'$.f2[0].val', 'd');
</code>```

to update the data.

but

```<code>SELECT JSON_SEARCH(
'{"f1": "abc", "f2": [{"id": 1, "val":"a"},{"id": "2", "2":"b"},{"id": 3, "val":"2"}], "f3": ["a","b","c"]}',
'all', '1', null, '$.f2[*].id');
</code>```

won't find f2->id==1 . Neither does

```<code>SELECT JSON_SEARCH(
'{"f1": "abc", "f2": [{"id": 1, "val":"a"},{"id": "2", "2":"b"},{"id": 3, "val":"2"}], "f3": ["a","b","c"]}',
'all', 1, null, '$.f2[*].id');
</code>```

=========

update 2:
I will just save the IDs as string... But right now i have onother problem:

```<code>SELECT JSON_SEARCH(
'{"mm": [{"id":"1","field":"test","value":33}]}',
'one', '1', null, '$.mm[*].id') as path;
</code>```

is working

```<code>SELECT *  FROM document_data where document_id=5;
update document_data set data=JSON_SET(data, '$.mm', json_array()) where document_id=5;
update document_data set data=JSON_ARRAY_APPEND(data, '$.mm', '{"id":"1","field":"test","value":33}') where document_id=5;
SELECT JSON_SEARCH(data, 'one', '1', null, '$.mm[*].id') as path from document_data where id='5';
</code>```

is not working. Seems to be the quoting.
Can someone help?

==========

how can i update f2 where id==2 using JSON_SET?

Tried everything but i can't seem to figure out how to do it.

Many thanks
Rene

Title: Updateing mysql json field in array

Body:
Having this json:

{
    f1: "abc",
    f2: [
        {id: 1, val:"a"},
        {id: 2, val:"b"},
        {id: 3, val:"c"}
    ],
    f3: [
        "a",
        "b",
        "c"
    ]
}

Update:
As an example:

SELECT JSON_SEARCH(
'{"f1": "abc", "f2": [{"id": "1", "val":"a"},{"id": "2", "2":"b"},{"id": 3, "val":"2"}], "f3": ["a","b","c"]}',
'all', '1', null, '$.f2[*].id');

returns the needed path for f2->id==1
I can then use

select json_set(
'{"f1": "abc", "f2": [{"id": "1", "val":"a"},{"id": "2", "2":"b"},{"id": 3, "val":"2"}], "f3": ["a","b","c"]}',
'$.f2[0].val', 'd');

to update the data.

but

SELECT JSON_SEARCH(
'{"f1": "abc", "f2": [{"id": 1, "val":"a"},{"id": "2", "2":"b"},{"id": 3, "val":"2"}], "f3": ["a","b","c"]}',
'all', '1', null, '$.f2[*].id');

won't find f2->id==1 . Neither does

SELECT JSON_SEARCH(
'{"f1": "abc", "f2": [{"id": 1, "val":"a"},{"id": "2", "2":"b"},{"id": 3, "val":"2"}], "f3": ["a","b","c"]}',
'all', 1, null, '$.f2[*].id');

=========

update 2:
I will just save the IDs as string... But right now i have onother problem:

SELECT JSON_SEARCH(
'{"mm": [{"id":"1","field":"test","value":33}]}',
'one', '1', null, '$.mm[*].id') as path;

is working

SELECT *  FROM document_data where document_id=5;
update document_data set data=JSON_SET(data, '$.mm', json_array()) where document_id=5;
update document_data set data=JSON_ARRAY_APPEND(data, '$.mm', '{"id":"1","field":"test","value":33}') where document_id=5;
SELECT JSON_SEARCH(data, 'one', '1', null, '$.mm[*].id') as path from document_data where id='5';

is not working. Seems to be the quoting.
Can someone help?

==========

how can i update f2 where id==2 using JSON_SET?

Tried everything but i can't seem to figure out how to do it.

Many thanks
Rene

Body:
JSON_SEARCH, by design, seems to search only strings, see WL#7909: Server side JSON functions :: JSON_SEARCH.

One option, very unintuitive is to use something like (be careful with performance problems):

mysql> SELECT VERSION();
+-----------+
| VERSION() |
+-----------+
| 5.7.20    |
+-----------+
1 row in set (0.00 sec)

mysql> SET @`json` := '{
    '>   "f1": "abc",
    '>   "f2": [
    '>           {"id": 1, "val": "a"},
    '>           {"id": 2, "val": "b"},
    '>           {"id": 3, "val": "c"}
    '>         ],
    '>   "f3": ["a", "b", "c"]
    '> }',
    ->     @`value` := 2,
    ->     @`base_path` := '$.f2';
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT JSON_SEARCH(
    ->   REPLACE(
    ->     REPLACE(
    ->       REPLACE(
    ->         JSON_EXTRACT(@`json`, CONCAT(@`base_path`, '[*].id')),
    ->       ', ', '","'),
    ->     '[', '["'),
    ->   ']', '"]'),
    -> 'one', @`value`) INTO @`path`;
Query OK, 1 row affected (0.00 sec)

mysql> SELECT @`path`;
+---------+
| @`path` |
+---------+
| "$[1]"  |
+---------+
1 row in set (0.00 sec)

mysql> SELECT
    ->   CONCAT(
    ->     REPLACE(
    ->       JSON_UNQUOTE(@`path`),
    ->       '$',
    ->       @`base_path`
    ->     ),
    ->   '.val') INTO @`path`;
Query OK, 1 row affected (0.00 sec)

mysql> SELECT @`path`;
+-------------+
| @`path`     |
+-------------+
| $.f2[1].val |
+-------------+
1 row in set (0.00 sec)

mysql> SELECT JSON_SET(@`json`, @`path`, 'd');
+-------------------------------------------------------------------------------------------------------------------+
| JSON_SET(@`json`, @`path`, 'd')                                                                                |
+-------------------------------------------------------------------------------------------------------------------+
| {"f1": "abc", "f2": [{"id": 1, "val": "a"}, {"id": 2, "val": "d"}, {"id": 3, "val": "c"}], "f3": ["a", "b", "c"]} |
+-------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

See db-fiddle.


问:
How can I update table cells to an editable field on a selection?
I have a Table and I want some table-cells to change to a selection, where the user can change the values.

So far it works, but if I click on the -cell, the text value changes to my selection. But when I try to click on the selection to chose a new value, my option-list just shows for a second.

I figured out, that if I click on my selection, the function runs again and changes the value of the td-cell to my selection, so I am not able to change it.

Here is my code:

jQuery(".editTable.tdInactive").on("click", function(event) {
  event.preventDefault();
  console.log("WOAS?");
  var $ = jQuery;
  var this_object = $(this);

  this_object.removeClass('tdInactive');
  this_object.addClass('tdActive');

  var current_content = $(this).html();

  var new_content = $(this).attr('data-select');

  this_object.empty();
  this_object.append(new_content);

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td data-select="MY SELECTION CODE" class="editTable tdInactive">VALUE AS TEXT TO CHANGE</td>
  </tr>
</table></code>```

答:
$( ".editTable.tdInactive" ).on( "click", function( event ){
event.preventDefault();
alert("WOAS?");

var this_object = $( this );

this_object.removeClass('tdInactive');
this_object.addClass('tdActive');

var current_content = $(this).html();

var new_content = $(this).data('select');

this_object.empty();
this_object.html( new_content );

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
<tr>
<td data-select="MY SELECTION CODE" class="editTable tdInactive">VALUE AS TEXT TO CHANGE</td>
</tr>
</table>

<style>
table, th, td {
   border: 1px solid black;
}
</style></code>```

Here you go.You need to take the data value like this.

Body:
I have a Table and I want some table-cells to change to a selection, where the user can change the values.

So far it works, but if I click on the -cell, the text value changes to my selection. But when I try to click on the selection to chose a new value, my option-list just shows for a second.

I figured out, that if I click on my selection, the function runs again and changes the value of the td-cell to my selection, so I am not able to change it.

Here is my code:

jQuery(".editTable.tdInactive").on("click", function(event) {
  event.preventDefault();
  console.log("WOAS?");
  var $ = jQuery;
  var this_object = $(this);

  this_object.removeClass('tdInactive');
  this_object.addClass('tdActive');

  var current_content = $(this).html();

  var new_content = $(this).attr('data-select');

  this_object.empty();
  this_object.append(new_content);

});

    VALUE AS TEXT TO CHANGE

Body:
$( ".editTable.tdInactive" ).on( "click", function( event ){
event.preventDefault();
alert("WOAS?");

var this_object = $( this );

this_object.removeClass('tdInactive');
this_object.addClass('tdActive');

var current_content = $(this).html();

var new_content = $(this).data('select');

this_object.empty();
this_object.html( new_content );

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
<tr>
<td data-select="MY SELECTION CODE" class="editTable tdInactive">VALUE AS TEXT TO CHANGE</td>
</tr>
</table>

<style>
table, th, td {
   border: 1px solid black;
}
</style>

Here you go.You need to take the data value like this.


问:
Pointers sent to function
I have following code in main():

```<code>msgs, err := ch.Consume(
        q.Name, // queue
        //..
    )

    cache := ttlru.New(100, ttlru.WithTTL(5 * time.Minute)) //Cache type

    //log.Println(reflect.TypeOf(msgs)) 'chan amqp.Delivery'

    go func() {
       //here I use `cache` and `msgs` as closures. And it works fine.
    }
</code>```

I decided to create separate function for instead of anonymous.

I declared it as func hitCache(cache *ttlru.Cache, msgs *chan amqp.Delivery) {

I get compile exception:

```<code>./go_server.go:61: cannot use cache (type ttlru.Cache) as type *ttlru.Cache in argument to hitCache:
    *ttlru.Cache is pointer to interface, not interface
./go_server.go:61: cannot use msgs (type <-chan amqp.Delivery) as type *chan amqp.Delivery in argument to hitCache
</code>```

Question: How should I pass msg and cache into the new function?

答: Pointers to interfaces are nearly never used. You may simplify things and use interfaces of pass by value. </p>

Title: Pointers sent to function

Body:
I have following code in main():

msgs, err := ch.Consume(
        q.Name, // queue
        //..
    )

    cache := ttlru.New(100, ttlru.WithTTL(5 * time.Minute)) //Cache type

    //log.Println(reflect.TypeOf(msgs)) 'chan amqp.Delivery'

    go func() {
       //here I use `cache` and `msgs` as closures. And it works fine.
    }

I decided to create separate function for instead of anonymous.

I declared it as func hitCache(cache *ttlru.Cache, msgs *chan amqp.Delivery) {

I get compile exception:

./go_server.go:61: cannot use cache (type ttlru.Cache) as type *ttlru.Cache in argument to hitCache:
    *ttlru.Cache is pointer to interface, not interface
./go_server.go:61: cannot use msgs (type <-chan amqp.Delivery) as type *chan amqp.Delivery in argument to hitCache

Question: How should I pass msg and cache into the new function?


问:
Change text color of a specific column for QTreeView
I have widget that inherits from QTreeView, and I want to change the text color, but only for a specific column. Currently I set the stylesheet, so the entire row changes the text color to red when the item is selected.

```<code>QTreeView::item:selected {color: red}
</code>```

I want to change only the color of the first column when the item is selected. I know how to change the colour for specific columns (using ForegroundRole on the model and checking the index column), but I don't know how to do check if the index is selected in the model.

答:
So this is how I solved it.    </p>

```<code>class MyDelegate : public QStyledItemDelegate {
public:
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
        QString text_highlight;
        if (index.column() == 0)){
            text_highlight = BLUE;
        } else{
            text_highlight = RED;
        }
        QStyleOptionViewItem s = *qstyleoption_cast<const QStyleOptionViewItem*>(&option);
        s.palette.setColor(QPalette::HighlightedText, QColor(text_highlight));
        QStyledItemDelegate::paint(painter, s, index);
    }
}
</code>```

Body:
I have widget that inherits from QTreeView, and I want to change the text color, but only for a specific column. Currently I set the stylesheet, so the entire row changes the text color to red when the item is selected.

QTreeView::item:selected {color: red}

I want to change only the color of the first column when the item is selected. I know how to change the colour for specific columns (using ForegroundRole on the model and checking the index column), but I don't know how to do check if the index is selected in the model.

Body:
So this is how I solved it.

class MyDelegate : public QStyledItemDelegate {
public:
    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
        QString text_highlight;
        if (index.column() == 0)){
            text_highlight = BLUE;
        } else{
            text_highlight = RED;
        }
        QStyleOptionViewItem s = *qstyleoption_cast<const QStyleOptionViewItem*>(&option);
        s.palette.setColor(QPalette::HighlightedText, QColor(text_highlight));
        QStyledItemDelegate::paint(painter, s, index);
    }
}


问:
Reading parent document from iFrame and changing parent
I'm trying to write a JavaScript application that will load a button up in an iFrame on a page.  This application will read the parent document and strip out all images, apply minimal styling and reload the parent with this newly marked up page.

The problem I am having is reading and writing the parent document from the iFrame.  Does anyone know of a way to achieve this?  I've read up a little on cross-domain messaging but am unsure of the alternatives and which would be best.

Thanks in advance.

答:
You can reference the parent either by using parent or using the top variable that always points to the outer most document.

parent == parent window

top == out most window

So for accesing the first div in the parent window

```<code>var d = parent.document.getElementsByTagName("div")[0];
</code>```

But as noted already in the comment, both the outer document and the document in the iframe need to be from the same domain or you will be blocked for security reasons.

Body:
You can reference the parent either by using parent or using the top variable that always points to the outer most document.

parent == parent window

top == out most window

So for accesing the first div in the parent window

var d = parent.document.getElementsByTagName("div")[0];

But as noted already in the comment, both the outer document and the document in the iframe need to be from the same domain or you will be blocked for security reasons.