问:
How to add behaviour to standard dictionary?
I want to make a simple wrapper to the standard python dictionary, or maybe the defaultdict class where there is a default value.

The change I want to make is very simple: I would like to store in the dictionary data-structures that are not hashable due to the possibility of mutation, but I have guarantee in my code that I won't ever mutate them anyways.

My approach is detect if the key to the dictionary is hashable, if so proceed as usual. However if the key is not hashable, turn it into a string first then proceed as usual.

答:
You can inherit from dict and override __setitem__ method:

```<code>class CustomDict(dict):
    def __setitem__(self, key, value):
        try:
            hash(key)
        except TypeError:
            key = str(key)

        super(CustomDict, self).__setitem__(key, value)

    def __getitem__(self, key):
        try:
            hash(key)
        except TypeError:
            key = str(key)

        return super(CustomDict, self).__getitem__(key)

data = CustomDict()

data["x"] = True
data[dict(foo='bar')] = False
print(data)
>>> {'x': True, "{'foo': 'bar'}": False}
assert data[dict(foo='bar')] == False
</code>```

Or you can create custom dict-like object as described here.

Body:
You can inherit from dict and override __setitem__ method:

class CustomDict(dict):
    def __setitem__(self, key, value):
        try:
            hash(key)
        except TypeError:
            key = str(key)

        super(CustomDict, self).__setitem__(key, value)

    def __getitem__(self, key):
        try:
            hash(key)
        except TypeError:
            key = str(key)

        return super(CustomDict, self).__getitem__(key)

data = CustomDict()

data["x"] = True
data[dict(foo='bar')] = False
print(data)
>>> {'x': True, "{'foo': 'bar'}": False}
assert data[dict(foo='bar')] == False

Or you can create custom dict-like object as described here.


来源: stackexchange

问:
How to deprecate an Array type declaration in Delphi?
I need to mark as deprecated an array type declaration (well, actually more than just one), in order to help migrate our code to the more advanced and flexible TArray<T> generic type.

I've tried this:

```<code>type
  TArrayChars = array of Char deprecated;
</code>```

but I got a compilation error: E2029 ';' expected but identifier 'deprecated' found

The same works if the declared type isn't an array, for example:

```<code>type
  TFieldChars = set of Char deprecated;
</code>```

Note that this should be feasible by design.

What am I missing?

This seems to be a bug in Delphi (at least 10.1 Berlin and 10.2 Tokyo).

My accepted answer proposes a neat workaround, that is:

```<code>type
  TArrayCharsOld = array of Char;
  TArrayChars    = TArrayCharsOld deprecated;
</code>```

I'll file a bug report to Embarcadero.

This is the Embarcadero QC issue I've submitted:
https://quality.embarcadero.com/browse/RSP-18316

答:
There is a way around it (at least in 10.1 Berlin).

```<code>type
  TArrayCharsOld = array of Char;
  TArrayChars = TArrayCharsOld deprecated;
</code>```

compiles.

ContentLicense: CC BY-SA 3.0

Body:
I need to mark as deprecated an array type declaration (well, actually more than just one), in order to help migrate our code to the more advanced and flexible TArray<T> generic type.

I've tried this:

type
  TArrayChars = array of Char deprecated;

but I got a compilation error: E2029 ';' expected but identifier 'deprecated' found

The same works if the declared type isn't an array, for example:

type
  TFieldChars = set of Char deprecated;

Note that this should be feasible by design.

What am I missing?

This seems to be a bug in Delphi (at least 10.1 Berlin and 10.2 Tokyo).

My accepted answer proposes a neat workaround, that is:

type
  TArrayCharsOld = array of Char;
  TArrayChars    = TArrayCharsOld deprecated;

I'll file a bug report to Embarcadero.

This is the Embarcadero QC issue I've submitted:
https://quality.embarcadero.com/browse/RSP-18316

Body:
There is a way around it (at least in 10.1 Berlin).

type
  TArrayCharsOld = array of Char;
  TArrayChars = TArrayCharsOld deprecated;

compiles.


问:
Trying to get user id and user meta data from WordPress database
I am trying to get a list of all users in WordPress getting the user ID from the user table and some additional meta information from the usermeta table for the corresponding user. I am trying the below code but it's not working. I think I am going wrong in the INNER JOIN part of the statement but I don't know how to correct it.

```<code>$sql = "
SELECT {$wpdb->users}.ID,{$wpdb->usermeta}.meta_value
FROM {$wpdb->users},{$wpdb->usermeta}
INNER JOIN {$wpdb->usermeta} ON ({$wpdb->users}.ID = {$wpdb->usermeta}.user_id)
WHERE 1=1 AND {$wpdb->usermeta}.meta_key = 'first_name' OR {$wpdb->usermeta}.meta_key = 'last_name' OR {$wpdb->usermeta}.meta_key = 'dev_capabilities'
";

$users = $wpdb->get_results($sql);
</code>```

p.s. I realise there's easier ways to get this information in WordPress by using the get_users() function but because this is in a particular action I can't use this method.

答:
You are close. You are actually, accidentally, joining in your usermeta data in twice. Once as as an implicit cross join with the , and once again as an explicit INNER JOIN. Instead:

```<code>$sql = "
SELECT {$wpdb->users}.ID,{$wpdb->usermeta}.meta_value
FROM {$wpdb->users} INNER JOIN {$wpdb->usermeta} ON ({$wpdb->users}.ID = {$wpdb->usermeta}.user_id)
WHERE 1=1 AND {$wpdb->usermeta}.meta_key = 'first_name' OR {$wpdb->usermeta}.meta_key = 'last_name' OR {$wpdb->usermeta}.meta_key = 'dev_capabilities'
";

$users = $wpdb->get_results($sql);
</code>```

To get first and last name as well as dev capabilities in the same record (and, I assume, in the same array that $wpdb outputs) you can inner join to that meta table three times. Sticking each one of those into a subquery makes it easy to parse what's happening:

```<code>$sql = "
SELECT {$wpdb->users}.ID, firstname.meta_value as first_name, lastname.meta_value as last_name, devcapabilities.meta_value as dev_capabilities
FROM {$wpdb->users}
    INNER JOIN (SELECT user_id, meta_value FROM {$wpdb->usermeta} WHERE meta_key = 'first_name') as firstname ON {$wpdb->users}.ID = firstname.user_id
    INNER JOIN (SELECT user_id, meta_value FROM {$wpdb->usermeta} WHERE meta_key = 'last_name') as lastname ON {$wpdb->users}.ID = lastname.user_id
    INNER JOIN (SELECT user_id, meta_value FROM {$wpdb->usermeta} WHERE meta_key = 'dev_capabilities') as devcapabilities ON {$wpdb->users}.ID = devcapabilities.user_id
";

$users = $wpdb->get_results($sql);
</code>```

Body:
I am trying to get a list of all users in WordPress getting the user ID from the user table and some additional meta information from the usermeta table for the corresponding user. I am trying the below code but it's not working. I think I am going wrong in the INNER JOIN part of the statement but I don't know how to correct it.

$sql = "
SELECT {$wpdb->users}.ID,{$wpdb->usermeta}.meta_value
FROM {$wpdb->users},{$wpdb->usermeta}
INNER JOIN {$wpdb->usermeta} ON ({$wpdb->users}.ID = {$wpdb->usermeta}.user_id)
WHERE 1=1 AND {$wpdb->usermeta}.meta_key = 'first_name' OR {$wpdb->usermeta}.meta_key = 'last_name' OR {$wpdb->usermeta}.meta_key = 'dev_capabilities'
";

$users = $wpdb->get_results($sql);

p.s. I realise there's easier ways to get this information in WordPress by using the get_users() function but because this is in a particular action I can't use this method.

Body:
You are close. You are actually, accidentally, joining in your usermeta data in twice. Once as as an implicit cross join with the , and once again as an explicit INNER JOIN. Instead:

$sql = "
SELECT {$wpdb->users}.ID,{$wpdb->usermeta}.meta_value
FROM {$wpdb->users} INNER JOIN {$wpdb->usermeta} ON ({$wpdb->users}.ID = {$wpdb->usermeta}.user_id)
WHERE 1=1 AND {$wpdb->usermeta}.meta_key = 'first_name' OR {$wpdb->usermeta}.meta_key = 'last_name' OR {$wpdb->usermeta}.meta_key = 'dev_capabilities'
";

$users = $wpdb->get_results($sql);

To get first and last name as well as dev capabilities in the same record (and, I assume, in the same array that $wpdb outputs) you can inner join to that meta table three times. Sticking each one of those into a subquery makes it easy to parse what's happening:

$sql = "
SELECT {$wpdb->users}.ID, firstname.meta_value as first_name, lastname.meta_value as last_name, devcapabilities.meta_value as dev_capabilities
FROM {$wpdb->users}
    INNER JOIN (SELECT user_id, meta_value FROM {$wpdb->usermeta} WHERE meta_key = 'first_name') as firstname ON {$wpdb->users}.ID = firstname.user_id
    INNER JOIN (SELECT user_id, meta_value FROM {$wpdb->usermeta} WHERE meta_key = 'last_name') as lastname ON {$wpdb->users}.ID = lastname.user_id
    INNER JOIN (SELECT user_id, meta_value FROM {$wpdb->usermeta} WHERE meta_key = 'dev_capabilities') as devcapabilities ON {$wpdb->users}.ID = devcapabilities.user_id
";

$users = $wpdb->get_results($sql);


问:
What would be the fastest way to concatenate three files in C#?
I need to concatenate 3 files using C#. A header file, content, and a footer file, but I want to do this as cool as it can be done.

Cool = really small code or really fast (non-assembly code).

答: If you are in a Win32 environment, the most efficient solution could be to use the Win32 API function "WriteFile". There is an example in VB 6, but rewriting it in C# is not difficult.</p>

OwnerDisplayName: Bobby Bruckovnic

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: bdukes

OwnerDisplayName: TcKs


问:
What does the error: "Module 'myApp' has verification error 2733 at offset 1646" mean
I get the following error:

Module 'myApp' has verification error
  2733 at offset 1646

and this is my code:

```<code>public class Midlet extends net.rim.device.api.ui.UiApplication{

public static void main(String[] argv) {
     new Midlet().startApp();
}

public void startApp() {
    System.out.println("tada!");
}

public void pauseApp() {
    System.out.println("PauseApp ...zzzz...");
}

public void destroyApp(boolean unconditional) {
    System.out.println("destroyed: " + unconditional);
}

public void notifyDestroyed() {
    System.exit(0);
}

public void platformRequest(String s) {
    net.rim.blackberry.api.browser.Browser.getDefaultSession().displayPage(s);
}
</code>```

}

My Imports "LWUIT", "BlackberryPort" and "LWUIT4IO".

It builds without errors, I get the error when I try to start up the app.

What does this error mean?

答:
Have you signed your app? Browser integration requires app signing.

Also take a look at the LWUIT blog explains the verification errors.

Body:
I get the following error:

Module 'myApp' has verification error
  2733 at offset 1646

and this is my code:

public class Midlet extends net.rim.device.api.ui.UiApplication{

public static void main(String[] argv) {
     new Midlet().startApp();
}

public void startApp() {
    System.out.println("tada!");
}

public void pauseApp() {
    System.out.println("PauseApp ...zzzz...");
}

public void destroyApp(boolean unconditional) {
    System.out.println("destroyed: " + unconditional);
}

public void notifyDestroyed() {
    System.exit(0);
}

public void platformRequest(String s) {
    net.rim.blackberry.api.browser.Browser.getDefaultSession().displayPage(s);
}

}

My Imports "LWUIT", "BlackberryPort" and "LWUIT4IO".

It builds without errors, I get the error when I try to start up the app.

What does this error mean?


问:
wso2is/lib/endorsed/._* not letting java load
Downloaded from wso2 site the Identity server to my mac.
made copy and executed :
/bin/wso2server.sh -Dstartup
and I get :
JAVA_HOME environment variable is set to /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.131-3.b12.el7_3.x86_64
CARBON_HOME environment variable is set to /home/bpatton/wso2is-5.3.0
Using Java memory options: -Xms256m -Xmx1024m
Error occurred during initialization of VM
java/lang/ClassNotFoundException: error in opening JAR file /home/bpatton/wso2is-5.3.0/lib/endorsed/._geronimo-jaxws_2.2_spec-1.0.jar

It's not a permissions issue chmod -R 0755
so when I do a strings /lib/endorsed ._geronimo-jaxws_2.2_spec-1.0.jar
I get :
Mac OS X
ATTR
com.apple.quarantine

All the .files in lib/endorsed have the same thing in them, all the same size
I tried deleting them and get :
[bpatton@wso2-dev] wso2is-5.3.0 # bin/wso2server.sh -Dstartup
JAVA_HOME environment variable is set to /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.131-3.b12.el7_3.x86_64
CARBON_HOME environment variable is set to /home/bpatton/wso2is-5.3.0
Using Java memory options: -Xms256m -Xmx1024m
[2017-06-08 08:47:22,134] ERROR {org.wso2.carbon.server.extensions.DropinsBundleDeployer} -  Error occured while deploying bundles in the dropins directory
...  This question widget thins the output from the execution is code.
log4j:WARN No appenders could be found for logger (org.apache.openjpa.osgi.PersistenceActivator).
log4j:WARN Please initialize the log4j system properly.

Does the site see that I'm downloading from a mac an give me a mac version?
This is driving me nuts.

答:
SOLVED
The entire problem was in creating my tarball.
I have used
tar -cvf .tar
for over 35 years and have never had a problem.
from the man pages
man tar
the -f adds an archive.
So every directory has a . file for each file.
These . files were causing the problem.
when I used rsync to transfer between my mac and the Linux VM the problem went away.</p>


问:
race condition by using __block
I have a list of PHAsset that I need to get their associated URL and do something with each URL. After all the assets are processed I need to perform another task. I try to use __block to count the assets that are processed, but it is not reliable due to race condition. Is there a better way of knowing when all the assets are processed?</p>

```<code>    PHFetchResult* photosAsset = [PHAsset fetchAssetsInAssetCollection:collection options:fetchOptions2];
    __block int count = 0;

    for (int i = 0; i < photosAsset.count; ++i) {
        [[PHImageManager defaultManager] requestAVAssetForVideo:[photosAsset objectAtIndex:i] options:nil resultHandler:
         ^(AVAsset *avAsset, AVAudioMix *audioMix, NSDictionary *info) {
             NSURL *url = [(AVURLAsset *)avAsset URL];
             // then do something with the url here...

             ++count;
             NSLog(@"%d", count);
             if (count == photosAsset.count) {
                 NSLog(@"FINISHED!");
             }
        }];
    }
</code>```

答:
So here is the solution based on @Larme's suggestion: </p>

```<code>    dispatch_group_t group = dispatch_group_create();

    for (int i = 0; i < photosAsset.count; ++i) {
        dispatch_group_enter(group);
        [[PHImageManager defaultManager] requestAVAssetForVideo:[photosAsset objectAtIndex:i] options:nil resultHandler:
         ^(AVAsset *avAsset, AVAudioMix *audioMix, NSDictionary *info) {
             dispatch_group_leave(group);
         }];
    }

    dispatch_group_notify(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
        NSLog(@"FINISHED!");
    });

    dispatch_release(group);
</code>```

Title: race condition by using __block

Body:
I have a list of PHAsset that I need to get their associated URL and do something with each URL. After all the assets are processed I need to perform another task. I try to use __block to count the assets that are processed, but it is not reliable due to race condition. Is there a better way of knowing when all the assets are processed?

    PHFetchResult* photosAsset = [PHAsset fetchAssetsInAssetCollection:collection options:fetchOptions2];
    __block int count = 0;

    for (int i = 0; i < photosAsset.count; ++i) {
        [[PHImageManager defaultManager] requestAVAssetForVideo:[photosAsset objectAtIndex:i] options:nil resultHandler:
         ^(AVAsset *avAsset, AVAudioMix *audioMix, NSDictionary *info) {
             NSURL *url = [(AVURLAsset *)avAsset URL];
             // then do something with the url here...

             ++count;
             NSLog(@"%d", count);
             if (count == photosAsset.count) {
                 NSLog(@"FINISHED!");
             }
        }];
    }

Body:
So here is the solution based on @Larme's suggestion:

    dispatch_group_t group = dispatch_group_create();

    for (int i = 0; i < photosAsset.count; ++i) {
        dispatch_group_enter(group);
        [[PHImageManager defaultManager] requestAVAssetForVideo:[photosAsset objectAtIndex:i] options:nil resultHandler:
         ^(AVAsset *avAsset, AVAudioMix *audioMix, NSDictionary *info) {
             dispatch_group_leave(group);
         }];
    }

    dispatch_group_notify(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
        NSLog(@"FINISHED!");
    });

    dispatch_release(group);


问:
Create RegExps on the fly using string variables
Say I wanted to make the following re-usable:

```<code>function replace_foo(target, replacement) {
   return target.replace("string_to_replace",replacement);
}
</code>```

I might do something like this:

```<code>function replace_foo(target, string_to_replace, replacement) {
   return target.replace(string_to_replace,replacement);
}
</code>```

With string literals this is easy enough. But what if I want to get a little more tricky with the regex? For example, say I want to replace everything but string_to_replace. Instinctually I would try to extend the above by doing something like:

```<code>function replace_foo(target, string_to_replace, replacement) {
   return target.replace(/^string_to_replace/,replacement);
}
</code>```

This doesn't seem to work. My guess is that it thinks string_to_replace is a string literal, rather than a variable representing a string. Is it possible to create JavaScript regexes on the fly using string variables? Something like this would be great if at all possible:

```<code>function replace_foo(target, string_to_replace, replacement) {
   var regex = "/^" + string_to_replace + "/";
   return target.replace(regex,replacement);
}
</code>```

答:
I think I have very good example for highlight text in string (it finds not looking at register but highlighted using register)

```<code>function getHighlightedText(basicString, filterString) {

    if ((basicString === "") || (basicString === null) || (filterString === "") || (filterString === null)) return basicString;

    return basicString.replace(new RegExp(filterString.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\\\$&'), 'gi'),
        function(match)
            {return "<mark>"+match+"</mark>"});

}
</code>```

http://jsfiddle.net/cdbzL/1258/

ContentLicense: CC BY-SA 4.0

Body:
Say I wanted to make the following re-usable:

function replace_foo(target, replacement) {
   return target.replace("string_to_replace",replacement);
}

I might do something like this:

function replace_foo(target, string_to_replace, replacement) {
   return target.replace(string_to_replace,replacement);
}

With string literals this is easy enough. But what if I want to get a little more tricky with the regex? For example, say I want to replace everything but string_to_replace. Instinctually I would try to extend the above by doing something like:

function replace_foo(target, string_to_replace, replacement) {
   return target.replace(/^string_to_replace/,replacement);
}

This doesn't seem to work. My guess is that it thinks string_to_replace is a string literal, rather than a variable representing a string. Is it possible to create JavaScript regexes on the fly using string variables? Something like this would be great if at all possible:

function replace_foo(target, string_to_replace, replacement) {
   var regex = "/^" + string_to_replace + "/";
   return target.replace(regex,replacement);
}

Body:
I think I have very good example for highlight text in string (it finds not looking at register but highlighted using register)

function getHighlightedText(basicString, filterString) {

    if ((basicString === "") || (basicString === null) || (filterString === "") || (filterString === null)) return basicString;

    return basicString.replace(new RegExp(filterString.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\\\$&'), 'gi'),
        function(match)
            {return "<mark>"+match+"</mark>"});

}

http://jsfiddle.net/cdbzL/1258/


问:
Regex to find last token on a string
I was wondering if there is a way having this

```<code>var string = "foo::bar"
</code>```

To get the last part of the string: "bar" using just regex.

I was trying to do look-aheads but couldn't master them enough to do this.

--

UPDATE

Perhaps some examples will make the question clearer.

```<code>var st1 = "foo::bar::0"
match should be 0

var st2 = "foo::bar::0-3aab"
match should be 0-3aab

var st3 = "foo"
no match should be found
</code>```

答:
```<code>var string2 = string.replace(/.*::/, "");
</code>```

though perhaps string isn't the best choice of name for your string?

Title: Regex to find last token on a string

Body:
I was wondering if there is a way having this

var string = "foo::bar"

To get the last part of the string: "bar" using just regex.

I was trying to do look-aheads but couldn't master them enough to do this.

--

UPDATE

Perhaps some examples will make the question clearer.

var st1 = "foo::bar::0"
match should be 0

var st2 = "foo::bar::0-3aab"
match should be 0-3aab

var st3 = "foo"
no match should be found

Body:
var string2 = string.replace(/.*::/, "");

though perhaps string isn't the best choice of name for your string?


问:
What is the quota limit of invitations for a google classroom domain acount?
i will appriciate any help with my problem, I created a script that basically takes a students list and starts to send invitations to different courses, at some point i am getting this error "Error: @UserInvitationQuotaExhausted The user does not have enough quota to invite users to this course."
I am using a domain account not a personal account, i have read that the invitations quota for personal accounts is 100 per day, but i can not find any information about domain accounts. Is there any form to increase the quota of invitations for my domain account?

Thank you.

答:
Here's the Usage Limits

To view or change usage limits for your project, or to request an increase to your quota, do the following:

If you don't already have a billing account for your project, then create one.

Visit the Enabled APIs page of the API library in the API Console, and select an API from the list.

To view and change quota-related settings, select Quotas. To view usage statistics, select Usage


问:
Multiple MAX values in a single query
I'm taking this data and inserting it into another table as part of a conversion process. Unfortunately I'm not able to modify the table schema in either my source or target location.

Schema is as follows (super simplified but the data types can't be modified, just obviously cast)

```<code>CREATE TABLE [dbo].[TestScores](
    [id] [INT] NOT NULL,
    [EXAMNE_ID] [VARCHAR](40) NULL,
    [TestName] VARCHAR(30) NULL,
    [PASS_STA] [VARCHAR](5) NULL,
    [TST_DTE] [VARCHAR](8) NULL,
    [STD_SCOR] [VARCHAR](3) NULL,
) ON [PRIMARY]
</code>```

I have the following source data: (Obviously just a snapshot of the data but for a single person)

```<code>+----+-----------+-----------------+----------+----------+----------+
| id | EXAMNE_ID |    TestName     | PASS_STA | TST_DTE  | STD_SCOR |
+----+-----------+-----------------+----------+----------+----------+
|  1 |     00001 | Social Studies  | Fail     | 20160608 |        7 |
|  2 |     00001 | Science         | Fail     | 20160608 |        8 |
|  3 |     00001 | Reading         | Fail     | 20160608 |        2 |
|  4 |     00001 | Math            | Fail     | 20160608 |        8 |
|  5 |     00001 | Writing         | Fail     | 20160608 |        7 |
|  6 |     00001 | Social Studies  | Fail     | 20160608 |        7 |
|  7 |     00001 | Science         | Fail     | 20160608 |        8 |
|  8 |     00001 | Reading         | Fail     | 20160608 |        2 |
|  9 |     00001 | Math            | Fail     | 20160608 |        8 |
| 10 |     00001 | Writing         | Fail     | 20160608 |        7 |
| 11 |     00001 | Social Studies  | Fail     | 20160608 |        7 |
| 12 |     00001 | Science         | Fail     | 20160608 |        8 |
| 13 |     00001 | Reading         | Fail     | 20160608 |        2 |
| 14 |     00001 | Math            | Fail     | 20160608 |        8 |
| 15 |     00001 | Writing         | Fail     | 20160608 |        7 |
| 16 |     00001 | Social Studies  | Fail     | 20160608 |        7 |
| 17 |     00001 | Social Studies  | Fail     | 20160930 |       10 |
| 18 |     00001 | Science         | Fail     | 20160608 |        8 |
| 19 |     00001 | Reading         | Fail     | 20160608 |        2 |
| 20 |     00001 | Reading         | Fail     | 20160930 |        5 |
| 21 |     00001 | Math            | Fail     | 20160608 |        8 |
| 22 |     00001 | Writing         | Fail     | 20160608 |        7 |
| 23 |     00001 | Writing         | Fail     | 20160930 |       10 |
| 24 |     00001 | Social Studies  | Fail     | 20160608 |        7 |
| 25 |     00001 | Social Studies  | Fail     | 20160930 |       10 |
| 26 |     00001 | Science         | Fail     | 20160608 |        8 |
| 27 |     00001 | Reading         | Fail     | 20160608 |        2 |
| 28 |     00001 | Reading         | Fail     | 20160930 |        5 |
| 29 |     00001 | Math            | Fail     | 20160608 |        8 |
| 30 |     00001 | Writing         | Fail     | 20160608 |        7 |
| 31 |     00001 | Writing         | Fail     | 20160930 |       10 |
| 32 |     00001 | Social Studies  | Fail     | 20160608 |        7 |
| 33 |     00001 | Social Studies  | Fail     | 20160930 |       10 |
| 34 |     00001 | Science         | Fail     | 20160608 |        8 |
| 35 |     00001 | Reading         | Fail     | 20160608 |        2 |
| 36 |     00001 | Reading         | Fail     | 20160930 |        5 |
| 37 |     00001 | Math            | Fail     | 20160608 |        8 |
| 38 |     00001 | Writing         | Pass     | 20160608 |        7 |
| 39 |     00001 | Writing         | Pass     | 20160930 |       10 |
| 40 |     00001 | Social Studies  | Pass     | 20160608 |        7 |
| 41 |     00001 | Social Studies  | Pass     | 20160930 |       10 |
| 42 |     00001 | Science         | Pass     | 20160608 |        8 |
| 43 |     00001 | Reading         | Pass     | 20160608 |        2 |
| 44 |     00001 | Reading         | Pass     | 20160930 |        5 |
| 45 |     00001 | Reading         | Pass     | 20161202 |        9 |
| 46 |     00001 | Math            | Pass     | 20160608 |        8 |
+----+-----------+-----------------+----------+----------+----------+
</code>```

My end result target data should look like this:

```<code>+----+-----------+-----------------+----------+----------+----------+
| id | EXAMNE_ID |    TestName     | PASS_STA | TST_DTE  | STD_SCOR |
+----+-----------+-----------------+----------+----------+----------+
| 39 |     00001 | Writing         | Pass     | 20160930 |       10 |
| 41 |     00001 | Social Studies  | Pass     | 20160930 |       10 |
| 42 |     00001 | Science         | Pass     | 20160608 |        8 |
| 45 |     00001 | Reading         | Pass     | 20161202 |        9 |
| 46 |     00001 | Math            | Pass     | 20160608 |        8 |
+----+-----------+-----------------+----------+----------+----------+
</code>```

I know I gave a ton of extra data since I'm really only looking for results that have a PASS_STA of 'Pass', but I wanted to give more of a complete picture.

Essentially the logic that occurs is that for a given person, when the exam is passed, pull out the greatest value of the TST_DTE and STD_SCOR columns. I'm trying this with what seems like multiple variants of max but it's heading in the wrong direction.

Currently this query isn't giving me what I'm looking for.

```<code>SELECT DISTINCT
EXAMNE_ID, PASS_STA, TestName, MAX(TST_DTE) AS 'TST_DTE', MAX(STD_SCOR) AS 'STD_SCOR'
FROM dbo.TestScores
GROUP BY EXAMNE_ID, PASS_STA, TestName, STD_SCOR
HAVING PASS_STA = 'Pass'
</code>```

Part of me is thinking I need to nest the query since I'm looking for two max values (plus one is a date - well, a date-ish, since it's in a varchar) and the other is a number (but again, stored in a varchar) or maybe somehow the RANK functionality?

I'd rather not have to do aggregate CASE statements for each of the five subject areas. There are actually a few dozen subject areas total, it's just this one test type that I'm showing here has five. So while I think aggregate case statements may work, it may be too cumbersome.

Any ideas?

Thanks in advance

答:
Other than the datatype issue, you need to remove std_scor from your group by, and move your having to where:

Converting the tst_dte to date or int is not necessary given your date format, but I included the conversion anyway.

```<code>select
   examne_id
 , pass_sta
 , TestName
 , max(convert(date,tst_dte)) as tst_dte
 , max(convert(int,std_scor)) as std_scor
from dbo.TestScores
group by
   examne_id
 , pass_sta
 , TestName
having pass_sta = 'Pass'
</code>```

rextester demo: http://rextester.com/BDI16678

returns:

```<code>+-----------+----------+----------------+------------+----------+
| examne_id | pass_sta |    TestName    |  tst_dte   | std_scor |
+-----------+----------+----------------+------------+----------+
|         1 | Pass     | Math           | 2016-06-08 |        8 |
|         1 | Pass     | Reading        | 2016-12-02 |        9 |
|         1 | Pass     | Science        | 2016-06-08 |        8 |
|         1 | Pass     | Social Studies | 2016-09-30 |       10 |
|         1 | Pass     | Writing        | 2016-09-30 |       10 |
+-----------+----------+----------------+------------+----------+
</code>```

Title: Multiple MAX values in a single query

Body:
I'm taking this data and inserting it into another table as part of a conversion process. Unfortunately I'm not able to modify the table schema in either my source or target location.

Schema is as follows (super simplified but the data types can't be modified, just obviously cast)

CREATE TABLE [dbo].[TestScores](
    [id] [INT] NOT NULL,
    [EXAMNE_ID] [VARCHAR](40) NULL,
    [TestName] VARCHAR(30) NULL,
    [PASS_STA] [VARCHAR](5) NULL,
    [TST_DTE] [VARCHAR](8) NULL,
    [STD_SCOR] [VARCHAR](3) NULL,
) ON [PRIMARY]

I have the following source data: (Obviously just a snapshot of the data but for a single person)

+----+-----------+-----------------+----------+----------+----------+
| id | EXAMNE_ID |    TestName     | PASS_STA | TST_DTE  | STD_SCOR |
+----+-----------+-----------------+----------+----------+----------+
|  1 |     00001 | Social Studies  | Fail     | 20160608 |        7 |
|  2 |     00001 | Science         | Fail     | 20160608 |        8 |
|  3 |     00001 | Reading         | Fail     | 20160608 |        2 |
|  4 |     00001 | Math            | Fail     | 20160608 |        8 |
|  5 |     00001 | Writing         | Fail     | 20160608 |        7 |
|  6 |     00001 | Social Studies  | Fail     | 20160608 |        7 |
|  7 |     00001 | Science         | Fail     | 20160608 |        8 |
|  8 |     00001 | Reading         | Fail     | 20160608 |        2 |
|  9 |     00001 | Math            | Fail     | 20160608 |        8 |
| 10 |     00001 | Writing         | Fail     | 20160608 |        7 |
| 11 |     00001 | Social Studies  | Fail     | 20160608 |        7 |
| 12 |     00001 | Science         | Fail     | 20160608 |        8 |
| 13 |     00001 | Reading         | Fail     | 20160608 |        2 |
| 14 |     00001 | Math            | Fail     | 20160608 |        8 |
| 15 |     00001 | Writing         | Fail     | 20160608 |        7 |
| 16 |     00001 | Social Studies  | Fail     | 20160608 |        7 |
| 17 |     00001 | Social Studies  | Fail     | 20160930 |       10 |
| 18 |     00001 | Science         | Fail     | 20160608 |        8 |
| 19 |     00001 | Reading         | Fail     | 20160608 |        2 |
| 20 |     00001 | Reading         | Fail     | 20160930 |        5 |
| 21 |     00001 | Math            | Fail     | 20160608 |        8 |
| 22 |     00001 | Writing         | Fail     | 20160608 |        7 |
| 23 |     00001 | Writing         | Fail     | 20160930 |       10 |
| 24 |     00001 | Social Studies  | Fail     | 20160608 |        7 |
| 25 |     00001 | Social Studies  | Fail     | 20160930 |       10 |
| 26 |     00001 | Science         | Fail     | 20160608 |        8 |
| 27 |     00001 | Reading         | Fail     | 20160608 |        2 |
| 28 |     00001 | Reading         | Fail     | 20160930 |        5 |
| 29 |     00001 | Math            | Fail     | 20160608 |        8 |
| 30 |     00001 | Writing         | Fail     | 20160608 |        7 |
| 31 |     00001 | Writing         | Fail     | 20160930 |       10 |
| 32 |     00001 | Social Studies  | Fail     | 20160608 |        7 |
| 33 |     00001 | Social Studies  | Fail     | 20160930 |       10 |
| 34 |     00001 | Science         | Fail     | 20160608 |        8 |
| 35 |     00001 | Reading         | Fail     | 20160608 |        2 |
| 36 |     00001 | Reading         | Fail     | 20160930 |        5 |
| 37 |     00001 | Math            | Fail     | 20160608 |        8 |
| 38 |     00001 | Writing         | Pass     | 20160608 |        7 |
| 39 |     00001 | Writing         | Pass     | 20160930 |       10 |
| 40 |     00001 | Social Studies  | Pass     | 20160608 |        7 |
| 41 |     00001 | Social Studies  | Pass     | 20160930 |       10 |
| 42 |     00001 | Science         | Pass     | 20160608 |        8 |
| 43 |     00001 | Reading         | Pass     | 20160608 |        2 |
| 44 |     00001 | Reading         | Pass     | 20160930 |        5 |
| 45 |     00001 | Reading         | Pass     | 20161202 |        9 |
| 46 |     00001 | Math            | Pass     | 20160608 |        8 |
+----+-----------+-----------------+----------+----------+----------+

My end result target data should look like this:

+----+-----------+-----------------+----------+----------+----------+
| id | EXAMNE_ID |    TestName     | PASS_STA | TST_DTE  | STD_SCOR |
+----+-----------+-----------------+----------+----------+----------+
| 39 |     00001 | Writing         | Pass     | 20160930 |       10 |
| 41 |     00001 | Social Studies  | Pass     | 20160930 |       10 |
| 42 |     00001 | Science         | Pass     | 20160608 |        8 |
| 45 |     00001 | Reading         | Pass     | 20161202 |        9 |
| 46 |     00001 | Math            | Pass     | 20160608 |        8 |
+----+-----------+-----------------+----------+----------+----------+

I know I gave a ton of extra data since I'm really only looking for results that have a PASS_STA of 'Pass', but I wanted to give more of a complete picture.

Essentially the logic that occurs is that for a given person, when the exam is passed, pull out the greatest value of the TST_DTE and STD_SCOR columns. I'm trying this with what seems like multiple variants of max but it's heading in the wrong direction.

Currently this query isn't giving me what I'm looking for.

SELECT DISTINCT
EXAMNE_ID, PASS_STA, TestName, MAX(TST_DTE) AS 'TST_DTE', MAX(STD_SCOR) AS 'STD_SCOR'
FROM dbo.TestScores
GROUP BY EXAMNE_ID, PASS_STA, TestName, STD_SCOR
HAVING PASS_STA = 'Pass'

Part of me is thinking I need to nest the query since I'm looking for two max values (plus one is a date - well, a date-ish, since it's in a varchar) and the other is a number (but again, stored in a varchar) or maybe somehow the RANK functionality?

I'd rather not have to do aggregate CASE statements for each of the five subject areas. There are actually a few dozen subject areas total, it's just this one test type that I'm showing here has five. So while I think aggregate case statements may work, it may be too cumbersome.

Any ideas?

Thanks in advance

Body:
Other than the datatype issue, you need to remove std_scor from your group by, and move your having to where:

Converting the tst_dte to date or int is not necessary given your date format, but I included the conversion anyway.

select
   examne_id
 , pass_sta
 , TestName
 , max(convert(date,tst_dte)) as tst_dte
 , max(convert(int,std_scor)) as std_scor
from dbo.TestScores
group by
   examne_id
 , pass_sta
 , TestName
having pass_sta = 'Pass'

rextester demo: http://rextester.com/BDI16678

returns:

+-----------+----------+----------------+------------+----------+
| examne_id | pass_sta |    TestName    |  tst_dte   | std_scor |
+-----------+----------+----------------+------------+----------+
|         1 | Pass     | Math           | 2016-06-08 |        8 |
|         1 | Pass     | Reading        | 2016-12-02 |        9 |
|         1 | Pass     | Science        | 2016-06-08 |        8 |
|         1 | Pass     | Social Studies | 2016-09-30 |       10 |
|         1 | Pass     | Writing        | 2016-09-30 |       10 |
+-----------+----------+----------------+------------+----------+


问:
Get customers name in confirmation email
I am working with Woocommerce and I am about to make the order confirmation email.

It want the mail to say:

"Hi [customers name]"

How do you get Woocommerce to print the customers name?

答:
As of WooCommerce 3.x the $order object's properties should not be accessed directly as suggested in the previous answers. The proper way is now:

```<code>echo 'Hi ' . $order->get_billing_first_name() . ' ' . $order->get_billing_last_name();
</code>```

Body:
As of WooCommerce 3.x the $order object's properties should not be accessed directly as suggested in the previous answers. The proper way is now:

echo 'Hi ' . $order->get_billing_first_name() . ' ' . $order->get_billing_last_name();


问:
how to force break words that exceed width of parent div
i am running into an issue that i do not think is possible with css. i have a text output dynamically showing in a label that only has the following html

label {
width:94px;
}

i am trying to come up with a solution that will dynamically take any mutliple word that exceeds the width of the div, and force break that word. if a word is to be split but could fit on its own line without breaking within the text, then wrap it to the next line

an example of this working fine as is would be the following screenshot:

here is the current scenario where a letter inside a word is pushed to the next line:

here is what i would like to happen in this scenario:

any help would be greatly appreciated. i am very curious if this is even possible with css without a lot of hacks and cross-browser issues...

答: I guess word-wrap:break-word; would do the job</p>


问:
Setting DatetimeIndex frequency, is it correct?
Having two time series like:

```<code>import pandas
from numpy import nan

# 1-minute period
index = pandas.date_range('1/1/2010', periods=8, freq='T')
series1 = pandas.Series([1., nan, nan, nan, nan, 2., nan, nan], index=index)

# 5-minutes period
index = pandas.date_range('1/1/2010', periods=2, freq='5T')
series5 = pandas.Series([1., 2.], index=index)
</code>```

One of them is 1-minute based, the other is 5-minutes based. They both have the same values (excluding nan) at the same timestamps.

I don't want to keep nan values, so I drop them. However, dropping them also drops the frequency information from the DatetimeIndex:

```<code>series1 = series1.dropna()
print(series1.index.freq)
</code>```

Now, I would really like to be able to differenciate two series like these: same timestamps, same values, but originating from different base frequencies.

In order to do so, I set the frequency back "by hand":

```<code>from pandas.tseries.frequencies import to_offset

series.index.freq = to_offset('T')
</code>```

Question(s):

Can anything go wrong? (i.e.: Pandas maybe expects to have that frequency set only for series with complete/filled indexes)

If so, how else should I store that information?

答:
In short: there is no good way to keep track of this information in the Series itself that I know off.
Here are a few alternatives:

series attributes

you can add your own attribute to the series. Be warned that these will not be maintained when copying the Series or adding it to a DataFrame

```<code>series1._myfreq = 'T'
series5._myfreq = '5T'
</code>```

Index name

same caveat as for the attributes

```<code>series1.index.name = 'T'
series5.index.name = '5T'
</code>```

Outside of the Series

By choosing an appropriate variable name you can distinguish them, or you can keep the Series in a dict, with the freq as one of the other items of the dict

Body:
Having two time series like:

import pandas
from numpy import nan

# 1-minute period
index = pandas.date_range('1/1/2010', periods=8, freq='T')
series1 = pandas.Series([1., nan, nan, nan, nan, 2., nan, nan], index=index)

# 5-minutes period
index = pandas.date_range('1/1/2010', periods=2, freq='5T')
series5 = pandas.Series([1., 2.], index=index)

One of them is 1-minute based, the other is 5-minutes based. They both have the same values (excluding nan) at the same timestamps.

I don't want to keep nan values, so I drop them. However, dropping them also drops the frequency information from the DatetimeIndex:

series1 = series1.dropna()
print(series1.index.freq)

Now, I would really like to be able to differenciate two series like these: same timestamps, same values, but originating from different base frequencies.

In order to do so, I set the frequency back "by hand":

from pandas.tseries.frequencies import to_offset

series.index.freq = to_offset('T')

Question(s):

Can anything go wrong? (i.e.: Pandas maybe expects to have that frequency set only for series with complete/filled indexes)

If so, how else should I store that information?

Body:
In short: there is no good way to keep track of this information in the Series itself that I know off.
Here are a few alternatives:

series attributes

you can add your own attribute to the series. Be warned that these will not be maintained when copying the Series or adding it to a DataFrame

series1._myfreq = 'T'
series5._myfreq = '5T'

Index name

same caveat as for the attributes

series1.index.name = 'T'
series5.index.name = '5T'

Outside of the Series

By choosing an appropriate variable name you can distinguish them, or you can keep the Series in a dict, with the freq as one of the other items of the dict


问:
How to modify certain fields in entity using only associative array?
I'm implementing editing user profile via API. The page where user edits its data contains a lot of fields, but when user submits the form, only edited fields are  sent to my API endpoint. Also I'm not using form mapping.

Only way I see is to write something like this:

```<code>public function editProfile(FormInterface $form, User $user): User
{
    $args = $form->getData();

    if ($args['email']) {
        $user->setEmail($args['email']);
    }

    if ($args['phone']) {
        $user->setPhone($args['phone']);
    }

    // ...

    $this->em->persist($user);
    $this->em->flush();

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

But it looks terrible and my form may contain up to several tens of fields.

Does anybody know good solution for this case?

答:
Use form mapping and submit form with disabled clear missing fields option:

In form builder:

```<code>$options->setDefaults([
    'data_class' => MyEntity:class
]);
</code>```

In controller:

```<code>$data = $request->request->all();
$form->submit($data, false);`
</code>```

instead of $form->handleRequest($request);

Body:
I'm implementing editing user profile via API. The page where user edits its data contains a lot of fields, but when user submits the form, only edited fields are  sent to my API endpoint. Also I'm not using form mapping.

Only way I see is to write something like this:

public function editProfile(FormInterface $form, User $user): User
{
    $args = $form->getData();

    if ($args['email']) {
        $user->setEmail($args['email']);
    }

    if ($args['phone']) {
        $user->setPhone($args['phone']);
    }

    // ...

    $this->em->persist($user);
    $this->em->flush();

    return $user;
}

But it looks terrible and my form may contain up to several tens of fields.

Does anybody know good solution for this case?

Body:
Use form mapping and submit form with disabled clear missing fields option:

In form builder:

$options->setDefaults([
    'data_class' => MyEntity:class
]);

In controller:

$data = $request->request->all();
$form->submit($data, false);`

instead of $form->handleRequest($request);


问:
Phonegap Plugin Activity Import Layout
I'm developing a Cordova Plugin that has an Activity, and I need to access the application R.layout from this activity so I can call setContentView.

I'm currently doing this by making an import com.example.hello.R and then on the onCreate method I callsetContentView(R.layout.mysurfaceview)`:

The problem is that my plugin will only work if the application name is com.example.hello, but I need to install my plugin on different applications without manually making the imports.

Is there a way to make a generic import, something like import <appName>.R, or any other ways to do that?

答:
As @insomniac stated, hooks can be used to replace source file contents to remove wrong imports and/or add the right imports of resources.

Based on his answer, I could create a script that do it without needing to specify the files. It tries to find source files (with .java extension), removes any resource import already in it and then put the right resources import (if needed), using the Cordova application package name.

This is the script:

```<code>#!/usr/bin/env node

/*
 * A hook to add resources class (R.java) import to Android classes which uses it.
 */

function getRegexGroupMatches(string, regex, index) {
    index || (index = 1)

    var matches = [];
    var match;
    if (regex.global) {
        while (match = regex.exec(string)) {
            matches.push(match[index]);
            console.log('Match:', match);
        }
    }
    else {
        if (match = regex.exec(string)) {
            matches.push(match[index]);
        }
    }

    return matches;
}

module.exports = function (ctx) {
    // If Android platform is not installed, don't even execute
    if (ctx.opts.cordova.platforms.indexOf('android') < 0)
        return;

    var fs = ctx.requireCordovaModule('fs'),
        path = ctx.requireCordovaModule('path'),
        Q = ctx.requireCordovaModule('q');

    var deferral = Q.defer();

    var platformSourcesRoot = path.join(ctx.opts.projectRoot, 'platforms/android/src');
    var pluginSourcesRoot = path.join(ctx.opts.plugin.dir, 'src/android');

    var androidPluginsData = JSON.parse(fs.readFileSync(path.join(ctx.opts.projectRoot, 'plugins', 'android.json'), 'utf8'));
    var appPackage = androidPluginsData.installed_plugins[ctx.opts.plugin.id]['PACKAGE_NAME'];

    fs.readdir(pluginSourcesRoot, function (err, files) {
        if (err) {
            console.error('Error when reading file:', err)
            deferral.reject();
            return
        }

        var deferrals = [];

        files.filter(function (file) { return path.extname(file) === '.java'; })
            .forEach(function (file) {
                var deferral = Q.defer();

                var filename = path.basename(file);
                var file = path.join(pluginSourcesRoot, filename);
                fs.readFile(file, 'utf-8', function (err, contents) {
                    if (err) {
                        console.error('Error when reading file:', err)
                        deferral.reject();
                        return
                    }

                    if (contents.match(/[^\.\w]R\./)) {
                        console.log('Trying to get packages from file:', filename);
                        var packages = getRegexGroupMatches(contents, /package ([^;]+);/);
                        for (var p = 0; p < packages.length; p++) {
                            try {
                                var package = packages[p];

                                var sourceFile = path.join(platformSourcesRoot, package.replace(/\./g, '/'), filename)
                                if (!fs.existsSync(sourceFile))
                                    throw 'Can\'t find file in installed platform directory: "' + sourceFile + '".';

                                var sourceFileContents = fs.readFileSync(sourceFile, 'utf8');
                                if (!sourceFileContents)
                                    throw 'Can\'t read file contents.';

                                var newContents = sourceFileContents
                                    .replace(/(import ([^;]+).R;)/g, '')
                                    .replace(/(package ([^;]+);)/g, '$1 import ' + appPackage + '.R;');

                                fs.writeFileSync(sourceFile, newContents, 'utf8');
                                break;
                            }
                            catch (ex) {
                                console.log('Could not add import to "' +  filename + '" using package "' + package + '". ' + ex);
                            }
                        }
                    }
                });

                deferrals.push(deferral.promise);
            });

        Q.all(deferrals)
            .then(function() {
                console.log('Done with the hook!');
                deferral.resolve();
            })
    });

    return deferral.promise;
}
</code>```

Just add as an after_plugin_install hook (for Android platform) in your plugin.xml:

```<code><hook type="after_plugin_install" src="scripts/android/addResourcesClassImport.js" />
</code>```

Hope it helps someone!

Title: Phonegap Plugin Activity Import Layout

Body:
As @insomniac stated, hooks can be used to replace source file contents to remove wrong imports and/or add the right imports of resources.

Based on his answer, I could create a script that do it without needing to specify the files. It tries to find source files (with .java extension), removes any resource import already in it and then put the right resources import (if needed), using the Cordova application package name.

This is the script:

#!/usr/bin/env node

/*
 * A hook to add resources class (R.java) import to Android classes which uses it.
 */

function getRegexGroupMatches(string, regex, index) {
    index || (index = 1)

    var matches = [];
    var match;
    if (regex.global) {
        while (match = regex.exec(string)) {
            matches.push(match[index]);
            console.log('Match:', match);
        }
    }
    else {
        if (match = regex.exec(string)) {
            matches.push(match[index]);
        }
    }

    return matches;
}

module.exports = function (ctx) {
    // If Android platform is not installed, don't even execute
    if (ctx.opts.cordova.platforms.indexOf('android') < 0)
        return;

    var fs = ctx.requireCordovaModule('fs'),
        path = ctx.requireCordovaModule('path'),
        Q = ctx.requireCordovaModule('q');

    var deferral = Q.defer();

    var platformSourcesRoot = path.join(ctx.opts.projectRoot, 'platforms/android/src');
    var pluginSourcesRoot = path.join(ctx.opts.plugin.dir, 'src/android');

    var androidPluginsData = JSON.parse(fs.readFileSync(path.join(ctx.opts.projectRoot, 'plugins', 'android.json'), 'utf8'));
    var appPackage = androidPluginsData.installed_plugins[ctx.opts.plugin.id]['PACKAGE_NAME'];

    fs.readdir(pluginSourcesRoot, function (err, files) {
        if (err) {
            console.error('Error when reading file:', err)
            deferral.reject();
            return
        }

        var deferrals = [];

        files.filter(function (file) { return path.extname(file) === '.java'; })
            .forEach(function (file) {
                var deferral = Q.defer();

                var filename = path.basename(file);
                var file = path.join(pluginSourcesRoot, filename);
                fs.readFile(file, 'utf-8', function (err, contents) {
                    if (err) {
                        console.error('Error when reading file:', err)
                        deferral.reject();
                        return
                    }

                    if (contents.match(/[^\.\w]R\./)) {
                        console.log('Trying to get packages from file:', filename);
                        var packages = getRegexGroupMatches(contents, /package ([^;]+);/);
                        for (var p = 0; p < packages.length; p++) {
                            try {
                                var package = packages[p];

                                var sourceFile = path.join(platformSourcesRoot, package.replace(/\./g, '/'), filename)
                                if (!fs.existsSync(sourceFile))
                                    throw 'Can\'t find file in installed platform directory: "' + sourceFile + '".';

                                var sourceFileContents = fs.readFileSync(sourceFile, 'utf8');
                                if (!sourceFileContents)
                                    throw 'Can\'t read file contents.';

                                var newContents = sourceFileContents
                                    .replace(/(import ([^;]+).R;)/g, '')
                                    .replace(/(package ([^;]+);)/g, '$1 import ' + appPackage + '.R;');

                                fs.writeFileSync(sourceFile, newContents, 'utf8');
                                break;
                            }
                            catch (ex) {
                                console.log('Could not add import to "' +  filename + '" using package "' + package + '". ' + ex);
                            }
                        }
                    }
                });

                deferrals.push(deferral.promise);
            });

        Q.all(deferrals)
            .then(function() {
                console.log('Done with the hook!');
                deferral.resolve();
            })
    });

    return deferral.promise;
}

Just add as an after_plugin_install hook (for Android platform) in your plugin.xml:

<hook type="after_plugin_install" src="scripts/android/addResourcesClassImport.js" />

Hope it helps someone!


问:
Issue with Validating Phone number on user input,Int to large c#
Overview of Project:

I am creating a multi form application, which consist of two forms and one parent class. Both Forms have a series of validation functions, such as isLetter() isNumber() and isValidEmail(). My Issue comes when using the isNumber() Function.

```<code>public static bool numValidation(string strNum)
        {
            if (!string.IsNullOrWhiteSpace(strNum))
            {
                int temp;
                if (int.TryParse(strNum, out temp))
                {
                    Console.WriteLine("Phone Number is a valid input: " + temp);
                    return true;
                }
                else
                { Console.WriteLine(temp + "Is not Valid input!!"); }
            }
            return false;
        }
</code>```

At first glance it works fine but once I tried to break it, I realised that when an actual phone number is entered I get an error saying that the number is too high. Any ideas how to get round this constraint ? as the only reason I need this validation is for phone numbers, Fax etc. I simply need this function to accept very large numbers such as phone numbers

答:
I suggest that you use a regular expresion to validate the input in your case

```<code>public static bool numValidation(string strNum)
{

    Regex regex = new Regex(@"^[0-9]+$");

    return (regex.IsMatch(strNum)) ;
}
</code>```

Parsing a string and not using that value is not really needed.

For more details checkout this answers - Regex for numbers only

Body:
Overview of Project:

I am creating a multi form application, which consist of two forms and one parent class. Both Forms have a series of validation functions, such as isLetter() isNumber() and isValidEmail(). My Issue comes when using the isNumber() Function.

public static bool numValidation(string strNum)
        {
            if (!string.IsNullOrWhiteSpace(strNum))
            {
                int temp;
                if (int.TryParse(strNum, out temp))
                {
                    Console.WriteLine("Phone Number is a valid input: " + temp);
                    return true;
                }
                else
                { Console.WriteLine(temp + "Is not Valid input!!"); }
            }
            return false;
        }

At first glance it works fine but once I tried to break it, I realised that when an actual phone number is entered I get an error saying that the number is too high. Any ideas how to get round this constraint ? as the only reason I need this validation is for phone numbers, Fax etc. I simply need this function to accept very large numbers such as phone numbers

Body:
I suggest that you use a regular expresion to validate the input in your case

public static bool numValidation(string strNum)
{

    Regex regex = new Regex(@"^[0-9]+$");

    return (regex.IsMatch(strNum)) ;
}

Parsing a string and not using that value is not really needed.

For more details checkout this answers - Regex for numbers only


问:
Button and AJAX not responding
Im working on trying to get a button to run a php script with AJAX. To be clear I am really new to javaScript and PHP so my code might be completely wrong. I think that the problem is in my button click code not so much the ajax code. Any help is great</p>

```<code><script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
    $(".submit").click(function myCall() {
        var subdata = $("#form").serializeArray();
        var request = $.ajax({
            url: "construct_new.php",
            type: "GET",
            data: subdata
        });
        return false;
    });
    </script>
    <div>
        <form id="form">
            Name of Product: <input type="text" name="productName" value="Enter Here">
            <input type="button" name="submit" value="Submit" class="submit">
        </form>
    </div>
</code>```

答:
Put your jQuery inside a document ready like this, and prevent the default action (to submit the form):

```<code> <script type="text/javascript">
    $(document).ready(function(){
            $(".submit").click(function(e) {
                e.preventDefault();
                var subdata = $("#form").serializeArray();
                $.get("construct_new.php",{data: subdata}, function(){
                     console.log(data); // whatever returned by php
                });
            });
        });
    </script>
</code>```

Document ready makes sure page has finished loading everything. e.preventDefault() stops the default action (for a form, submission, for an a tag, following the link).

Title: Button and AJAX not responding

Body:
Im working on trying to get a button to run a php script with AJAX. To be clear I am really new to javaScript and PHP so my code might be completely wrong. I think that the problem is in my button click code not so much the ajax code. Any help is great

        <form id="form">
            Name of Product: <input type="text" name="productName" value="Enter Here">
            <input type="button" name="submit" value="Submit" class="submit">
        </form>

Body:
Put your jQuery inside a document ready like this, and prevent the default action (to submit the form):

 <script type="text/javascript">
    $(document).ready(function(){
            $(".submit").click(function(e) {
                e.preventDefault();
                var subdata = $("#form").serializeArray();
                $.get("construct_new.php",{data: subdata}, function(){
                     console.log(data); // whatever returned by php
                });
            });
        });
    </script>

Document ready makes sure page has finished loading everything. e.preventDefault() stops the default action (for a form, submission, for an a tag, following the link).


问:
Order by custom meta value (int) confusion
I have the follow args:

```<code>array(7) {
  ["post_type"]=>
  string(6) "website"
  ["posts_per_page"]=>
  string(3) "150"
  ["meta_key"]=>
  string(11) "website_rank"
  ["order"]=>
  string(3) "ASC"
  ["orderby"]=>
  string(14) "meta_value_num"
  ["meta_value"]=>
  string(1) "6"
  ["meta_compare"]=>
  string(1) ">"
}
</code>```

Rather than returning posts with meta_values of 7, 8, 9 ... 150 (desired) they return as 7, 8, 9, 60, 61 ...

I've tried casting as (int) rather than a string but to no avail.

答:
I was missing 'type' from my meta query. Having used ACF this has never been necessary, but appears that when querying by a post with meta set by update_post_meta() 'type' needs to be used.

In my case

```<code>'type' => 'NUMERIC'
</code>```

Resolved my issue.

https://codex.wordpress.org/Class_Reference/WP_Meta_Query

Body:
I have the follow args:

array(7) {
  ["post_type"]=>
  string(6) "website"
  ["posts_per_page"]=>
  string(3) "150"
  ["meta_key"]=>
  string(11) "website_rank"
  ["order"]=>
  string(3) "ASC"
  ["orderby"]=>
  string(14) "meta_value_num"
  ["meta_value"]=>
  string(1) "6"
  ["meta_compare"]=>
  string(1) ">"
}

Rather than returning posts with meta_values of 7, 8, 9 ... 150 (desired) they return as 7, 8, 9, 60, 61 ...

I've tried casting as (int) rather than a string but to no avail.

Body:
I was missing 'type' from my meta query. Having used ACF this has never been necessary, but appears that when querying by a post with meta set by update_post_meta() 'type' needs to be used.

In my case

'type' => 'NUMERIC'

Resolved my issue.

https://codex.wordpress.org/Class_Reference/WP_Meta_Query


问:
Spring Boot: @Autowired is not working for one of the class
I am developing OAuth implementation with Jwt tokens.
It's kind of weird but for class TokenAuthenticationService When I try to Autowired this class in a different package, I get
Consider defining a bean of type 'com.company.security.TokenAuthenticationService' in your configuration.
I did a workaround and added @Bean TokenAuthenticationService in that class.
Now when I am trying to initialize an interface in the TokenAuthenticationService class, it gives the same type of error for that interface.
Consider defining a bean of type 'com.company.security.UserService' in your configuration.

ComponentScan annotation is configured like @ComponentScan({"com.company"})

What I am missing here and why?

答:
You have two ways to define beans for autowiring in your project.

With classes defined by you, you can use the @Component annotation (or, for service classes, @Service annotation) this way:

```<code>@Service
public class TokenAuthenticationService { ... }
</code>```

If you are using third party classes, you can configure them in a configuration class:

```<code>@Configuration
public MyProjectConfig {
    @Bean
    public ThirdPartyClass serviceClass() { new ThirdPartyClass(); }
}
</code>```

(Using @Bean annotation is not a workround. You just need to understand its purpose...)

This way autowiring should work...

Pay attention to difference between @Component and @Bean annotations.

Body:
You have two ways to define beans for autowiring in your project.

With classes defined by you, you can use the @Component annotation (or, for service classes, @Service annotation) this way:

@Service
public class TokenAuthenticationService { ... }

If you are using third party classes, you can configure them in a configuration class:

@Configuration
public MyProjectConfig {
    @Bean
    public ThirdPartyClass serviceClass() { new ThirdPartyClass(); }
}

(Using @Bean annotation is not a workround. You just need to understand its purpose...)

This way autowiring should work...

Pay attention to difference between @Component and @Bean annotations.


问:
Not sure how to build this bell-curve chart
Here is problem I'm trying to solve. It's for logistics company. I got all other inputs/variations taken care of so I have 1 straight-forward thing to do.

There is table with historical orders and prices paid per/mile. I need to present/visualize pricing distribution. Let's say prices vary from 0.80 to 1.80 per mile. Most loads done at around 1.40 per mile.

There is no special requirement HOW I should visualize that but the way I see it -
X axis will show price
Y axis will show loads count
I will show it as a curved line.

To make it look nice - I probably need to aggregate gata into 5c buckets so I don't have many points on X axis.

Does it sound right? I don't want' to reinvent wheel and maybe there is built-in function to take care of all that in 4.0 chart control?

Thanks in advance.

答: Your methodology sounds good to me. Aggregating things into buckets can definitely help to drive the point home ... just don't hesitate to play with the bucket sizes as an arbitrary 5c might not be the "right" size. I would also recommend giving the old bar charts a try ... depending on how many data points you have, I find it sometimes just looks better as a series of bar charts :-)</p>


问:
Deleting Emoji Bug
I followed this link Find out if Character in String is emoji? to try to limit the amount of characters my text field even with emojis. According to this link, I have to count emojis based on their glyphs and everything is working except for one little bug, when my glyph count is reached, it won't let me delete the string anymore.

Here's the code the handle the character limit using UITextField Delegate

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

var canEditString : Bool = false

if textField == self.descTxtField {

    // Description Text Field
    if textField.text != nil || textField.text != "" {

        let currentString = textField.text
        if (currentString?.containsEmoji)! {
            print("I have an emoji")
            let glyphCount = currentString!.glyphCount
            print(glyphCount)
            canEditString = glyphCount <= descriptionLimit
        }else {
            print("I have no emoji's")
            let currentCharacterCount = textField.text?.characters.count ?? 0
            //print(currentCharacterCount)
            if (range.length + range.location > currentCharacterCount){
                return false
            }
            let newLength = currentCharacterCount + string.characters.count - range.length
            canEditString = newLength <= descriptionLimit
        }
    }
    return canEditString

} else {

    // Number Text Field
    let currentCharacterCount = textField.text?.characters.count ?? 0
    if (range.length + range.location > currentCharacterCount){
        return false
    }
    let newLength = currentCharacterCount + string.characters.count - range.length
    return newLength <= numberLimit
}
}
</code>```

答:
String Manifesto

Swift 4

Emojis now have a character count of 1, making it a lot easier to keep track of character counts in Strings.

Title: Deleting Emoji Bug

Body:
I followed this link Find out if Character in String is emoji? to try to limit the amount of characters my text field even with emojis. According to this link, I have to count emojis based on their glyphs and everything is working except for one little bug, when my glyph count is reached, it won't let me delete the string anymore.

Here's the code the handle the character limit using UITextField Delegate

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

var canEditString : Bool = false

if textField == self.descTxtField {

    // Description Text Field
    if textField.text != nil || textField.text != "" {

        let currentString = textField.text
        if (currentString?.containsEmoji)! {
            print("I have an emoji")
            let glyphCount = currentString!.glyphCount
            print(glyphCount)
            canEditString = glyphCount <= descriptionLimit
        }else {
            print("I have no emoji's")
            let currentCharacterCount = textField.text?.characters.count ?? 0
            //print(currentCharacterCount)
            if (range.length + range.location > currentCharacterCount){
                return false
            }
            let newLength = currentCharacterCount + string.characters.count - range.length
            canEditString = newLength <= descriptionLimit
        }
    }
    return canEditString

} else {

    // Number Text Field
    let currentCharacterCount = textField.text?.characters.count ?? 0
    if (range.length + range.location > currentCharacterCount){
        return false
    }
    let newLength = currentCharacterCount + string.characters.count - range.length
    return newLength <= numberLimit
}
}


问:
get result of a Query in cell to another query dont work
I have some trouble with my queries i have try so hard to get it work. but its seems that Query can only get data from cell that have only text in it. If i try to get data from ex. = funktion its dont work.

Exempel for my Querys.

IN CELL B1

```<code>=query('DATA-IN-All-stocks'!A:B ;"select A where B = '" & TEXT( A2;"") & "'" ;-1)
</code>```

RESULT = This generet IMNP

IN CELL B2

```<code>=QUERY('DATA-IMNP-Swedbank'!A:M;"select C,D where B = '"&B1&"' and C = 'Köp'" ;0)
</code>```

RESULT = This generet N/A  = dont find anny...

When i Change B1 and only typing in text IMNP i get the RESULT correctly

答:
If you check =LEN(B1) you will see it is 14.

This might be because the import has fixed width fields used to split between columns.

You can easily circumvent this in your application by wrapping TRIM around the formula creating the ticker within B1.

Body:
I have some trouble with my queries i have try so hard to get it work. but its seems that Query can only get data from cell that have only text in it. If i try to get data from ex. = funktion its dont work.

Exempel for my Querys.

IN CELL B1

=query('DATA-IN-All-stocks'!A:B ;"select A where B = '" & TEXT( A2;"") & "'" ;-1)

RESULT = This generet IMNP

IN CELL B2

=QUERY('DATA-IMNP-Swedbank'!A:M;"select C,D where B = '"&B1&"' and C = 'Köp'" ;0)

RESULT = This generet N/A  = dont find anny...

When i Change B1 and only typing in text IMNP i get the RESULT correctly


问:
N1ql query couchbase
I have scenario to insert a new attribute in couchbase document.

For ex : I have a document like:
{
 "x" : "value1",
 "y" : "value2"
}

I just want to insert another key "z", for which value should be taken from key "y".

My expected result should be like:
{
 "x" : "value1",
 "y" : "value2",
 "z" : "value2"
}

Note : "x" is unique id.

Kindly suggest me couchbase N1QL query for better performance.

答:
If you need to update all documents

UPDATE default SET z = y;

If you need to update based on condition.

UPDATE default SET z = y WHERE x = "value1";

Title: N1ql query couchbase


问:
Highlight images on page when the user clicks on them
I want to add CSS style with JavaScript: "padding", "background", and "border" to the image clicked by the user, when the user clicks again on that image, the highlight effect is removed.</p>

```<code>var imagesProp = {
  'padding': '3px',
  'backgroundColor': '#eded01',
  'borderSize': '1ps',
  'borderStyle': 'dashed',
  'borderColor': '#0001fe'
};

function highlightimages() {
  var allimages = document.getElementsByid('images');
//How do i start from here
}
</code>```

答:
var imagesProp = {
  'padding': '3px',
  'backgroundColor': '#eded01',
  'borderSize': '1ps',
  'borderStyle': 'dashed',
  'borderColor': '#0001fe'
};

function highlightImages() {
  //You do not use getElementsByid but getElementsByTagName
  var allimages = document.getElementsByTagName('img');
  var nrallimgs = allimages.length;

  // traverses the  elements, and register onclick to each one
  // else, apply the properties defined in $imagesProp
  for(i=0; i<nrallimgs; i++) {
    allimages[i].onclick=function() {

      if(this.style.borderStyle == imagesProp.borderStyle) {
        this.style.padding = 'auto';
        this.style.background = 'none';
        this.style.border = 'none';
      }
      else {
        this.style.padding = imagesProp.padding;
        this.style.backgroundColor = imagesProp.backgroundColor;
        this.style.borderSize = imagesProp.borderSize;
        this.style.borderStyle = imagesProp.borderStyle;
        this.style.borderColor = imagesProp.borderColor;
      }
    }
  }
}

// calls the highlightImages() function to apply the effect
highlightImages();```

Body:
I want to add CSS style with JavaScript: "padding", "background", and "border" to the image clicked by the user, when the user clicks again on that image, the highlight effect is removed.

var imagesProp = {
  'padding': '3px',
  'backgroundColor': '#eded01',
  'borderSize': '1ps',
  'borderStyle': 'dashed',
  'borderColor': '#0001fe'
};

function highlightimages() {
  var allimages = document.getElementsByid('images');
//How do i start from here
}

Body:
var imagesProp = {
  'padding': '3px',
  'backgroundColor': '#eded01',
  'borderSize': '1ps',
  'borderStyle': 'dashed',
  'borderColor': '#0001fe'
};

function highlightImages() {
  //You do not use getElementsByid but getElementsByTagName
  var allimages = document.getElementsByTagName('img');
  var nrallimgs = allimages.length;

  // traverses the <img> elements, and register onclick to each one
  // else, apply the properties defined in $imagesProp
  for(i=0; i<nrallimgs; i++) {
    allimages[i].onclick=function() {

      if(this.style.borderStyle == imagesProp.borderStyle) {
        this.style.padding = 'auto';
        this.style.background = 'none';
        this.style.border = 'none';
      }
      else {
        this.style.padding = imagesProp.padding;
        this.style.backgroundColor = imagesProp.backgroundColor;
        this.style.borderSize = imagesProp.borderSize;
        this.style.borderStyle = imagesProp.borderStyle;
        this.style.borderColor = imagesProp.borderColor;
      }
    }
  }
}

// calls the highlightImages() function to apply the effect
highlightImages();


问:
Conditional summation in python
I have a numpy 2d array (8000x7200). I want to count the number of cells having a value greater than a specified threshold. I tried to do this using a double loop, but it takes a lot of time.
Is there a way to perform this calculation quickly?</p>

答:
Your best bet is probably something like np.count_nonzero(x > threshold), where x is your 2-d array.

As the name implies, count_nonzero counts the number of elements that aren't zero. By making use of the fact that True is 1-ish, you can use it to count the number of elements that are True.

Title: Conditional summation in python


问:
How is data, address and Instruction differentiated in Processor/Register/memory?
In Processor, how are Data, Address and instructions are differentiated? When a program is executed, how is processor differentiate instructions when everything is in 0s and 1s and registers load both data, addresses?

答:
The processor only does what you tell it to do.  As you noted, the processor can't tell the difference between "data" and "code" in memory:  it's all just a sequence of bytes.  It's what you tell it to do with those bytes that defines how it's treated.

When a program is compiled, the generated executable file has information in it that says which parts are code and which parts are data.  When a program is executed, the operating system loads code and data into different parts of memory and then tells the processor to start executing code at the program's entry point.  From there, the processor fetches the first instruction, executes it, and moves on to the next instruction.

That's all very simplified, of course, but I think you get the idea.

In older processors and older operating systems, nothing stops you from telling the processor to start executing instructions that are in the middle of a data segment.  Or, in fact, from modifying "data" in the middle of a code segment--thereby making self-modifying code.  Newer processors and operating systems usually have some form of data execution prevention and locks to prevent modification of code.  Otherwise, self-modifying code can become a huge security risk.

The short answer: the processor treats code as code because you tell it to.  Otherwise, everything's just bytes in memory.


问:
How to stop running Spark application?
I wrote a few Spark job in Java then submitted the jars with submit script.

```<code>bin/spark-submit --class "com.company.spark.jobName.SparkMain" --master local[*] /tmp/spark-job-1.0.jar
</code>```

There will be a service and will run in same server. The service should stop the job when receive the stop command.

I have these information about job in service:

SparkHome

AppName

AppResource

Master uri

app-id

status

Is there any way to stop running spark job in java code.

答: Have you reviewed the REST server and the ability to use /submissions/kill/[submissionId]? That seems like it would work for your need.

Title: How to stop running Spark application?

Body:
I wrote a few Spark job in Java then submitted the jars with submit script.

bin/spark-submit --class "com.company.spark.jobName.SparkMain" --master local[*] /tmp/spark-job-1.0.jar

There will be a service and will run in same server. The service should stop the job when receive the stop command.

I have these information about job in service:

SparkHome

AppName

AppResource

Master uri

app-id

status

Is there any way to stop running spark job in java code.


问:
iOS google maps sdk GMSMarker positioning
I am working with Google maps and I am able to center the map to the GMSMarker by using

```<code> GMSCameraPosition *camera =
    [[GMSCameraPosition alloc] initWithTarget:marker.position
                                         zoom:MAP_ZOOM_LEVEL
                                      bearing:0
                                 viewingAngle:0];
    [mapView animateToCameraPosition:camera];
</code>```

I am showing a custom callout of size 200*150 and part of it gets hidden when the camera position is changed but I want the callout to be in the center and the map point to be below it. Any ideas how to do this.

答:
Swift 4, 3

```<code>func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
    var point:CGPoint = mapView.projection.point(for: marker.position)
    point.x = point.x + 100

    let camera:GMSCameraUpdate = GMSCameraUpdate.setTarget(mapView.projection.coordinate(for: point))
    mapView.animate(with: camera)

    return true
}
</code>```

Body:
I am working with Google maps and I am able to center the map to the GMSMarker by using

 GMSCameraPosition *camera =
    [[GMSCameraPosition alloc] initWithTarget:marker.position
                                         zoom:MAP_ZOOM_LEVEL
                                      bearing:0
                                 viewingAngle:0];
    [mapView animateToCameraPosition:camera];

I am showing a custom callout of size 200*150 and part of it gets hidden when the camera position is changed but I want the callout to be in the center and the map point to be below it. Any ideas how to do this.

Body:
Swift 4, 3

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
    var point:CGPoint = mapView.projection.point(for: marker.position)
    point.x = point.x + 100

    let camera:GMSCameraUpdate = GMSCameraUpdate.setTarget(mapView.projection.coordinate(for: point))
    mapView.animate(with: camera)

    return true
}


问:
Node: How to fix routing?
I need to use a router to integrate applications. To define an application I use app.use ('/ chat'. The application works separately, but it does not work together with the routing file.

How to fix routing?

/app.js

```<code>let express = require('express'),
    sqlite3 = require('sqlite3'),
    app = express(),
    http = require('http').Server(app),
    io = require('socket.io')(http),
    iconv = require('iconv-lite'),
    path = require('path'),
    sassMiddleware = require('node-sass-middleware'),
    fs = require('fs'),
    db = new sqlite3.Database('./chat/history.db');
    var routes = require('./chat');
    app.use('/chat', routes);
http.listen(3000);
</code>```

chat/index.js

```<code>let express = require('express'),
    router = express.Router(),
    sqlite3 = require('sqlite3'),
    app = express(),
    http = require('http').Server(app),
    io = require('socket.io')(http),
    iconv = require('iconv-lite'),
    path = require('path'),
    sassMiddleware = require('node-sass-middleware'),
    fs = require('fs'),
    db = new sqlite3.Database('./history.db');

// DB
if (!fs.existsSync(__dirname + '/history.db'))
    db.run("CREATE TABLE message (id INTEGER PRIMARY KEY AUTOINCREMENT,txt TEXT)");

// VIEWS SETTINGS
app.set('views', __dirname + '/tpl');
app.set('view engine', 'jade');
app.use(sassMiddleware({
    src: path.join(__dirname, '/tpl'),
    dest: path.join(__dirname, '/tpl'),
    debug: true,
    indentedSyntax: true,
    outputStyle: 'compressed',
}));
app.use(express.static(__dirname + '/tpl'));

// ROUTER
router.get("/", function (req, res) {
    res.render('page', {"name": "Виталий"})
});

// DOP FUNC
function addMesToDB(txt) {
    var stmt = db.prepare("INSERT INTO message (txt) VALUES (?)");
    stmt.run(txt);
    stmt.finalize();
}
function loadLast10() {
    db.each("SELECT * FROM message LIMIT 10", function(err, row) {
        io.emit('new message show', row.txt);
    });
}
function loadAll() {
    db.each("SELECT * FROM message", function(err, row) {
        io.emit('new message show', row.txt);
    });
}
function getDateTime() {
    var date = new Date();
    var hour = date.getHours();
    hour = (hour < 10 ? "0" : "") + hour;
    var min  = date.getMinutes();
    min = (min < 10 ? "0" : "") + min;
    var sec  = date.getSeconds();
    sec = (sec < 10 ? "0" : "") + sec;
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    month = (month < 10 ? "0" : "") + month;
    var day  = date.getDate();
    day = (day < 10 ? "0" : "") + day;
    return year + ":" + month + ":" + day + ":" + hour + ":" + min + ":" + sec;
}

// EMIT
let name = '';
io.on('connection', function(socket){
    io.sockets.on('connection', function (client) {});
    socket.on('login', function(msg){
        if(msg == '888') name = 'Оксана';
        else if(msg == '8888') name = 'Виталий';
        if(msg == '888' || msg == '8888') {
            addMesToDB(getDateTime() + ' <span class="name">Вошел пользователь: ' + name + '</span>');
            loadLast10();
        }
    });
    socket.on('loadAll', function(msg){
        loadAll();
    });
    socket.on('new message send', function(msg){
        io.emit('new message show', getDateTime() + ' <span class="name">' + name + ':</span> <span class="msg">' + msg + '</span>');
        addMesToDB(getDateTime() + ' <span class="name">' + name + ':</span> ' + msg);
    });
    socket.on('disconnect', function () {
        io.emit('new message show', getDateTime() + '  <span class="name">Вышел пользователь: ' + name + '</span>');
        addMesToDB(getDateTime() + '  <span class="name">Вышел пользователь: ' + name + '</span>');
    });
});

module.exports = router;
</code>```

err:

```<code>Error: No default engine was specified and no extension was provided.
    at new View (C:\chat2\chat2\node_modules\express\lib\view.js:62:11)
    at Function.render (C:\chat2\chat2\node_modules\express\lib\application.js:570:12)
    at ServerResponse.render (C:\chat2\chat2\node_modules\express\lib\response.js:971:7)
    at C:\chat2\chat2\chat\index.js:41:9
    at Layer.handle [as handle_request] (C:\chat2\chat2\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\chat2\chat2\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\chat2\chat2\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\chat2\chat2\node_modules\express\lib\router\layer.js:95:5)
    at C:\chat2\chat2\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\chat2\chat2\node_modules\express\lib\router\index.js:335:12)
</code>```

答:
just went through your git repo. You need to include jade in your node modules and in your app. I'll issue a pull request against your repo but the short answer is: update your chat/index.js to the following:

```<code>app.set('views', __dirname + '/tpl');
app.engine('jade', require('jade').renderFile);
app.set('view engine', 'jade');
</code>```

You specify an engine via the app.engine() function rather than app.set(). You can then set the view (not views) engine as jade.

complete code: (index.js)

```<code>let express = require('express'),
    app = express(),
    http = require('http').Server(app),
    cfenv = require('cfenv'),
    appEnv = cfenv.getAppEnv();;

    app.set('appName', 'chat');
    app.set('port', appEnv.port);
    app.use('/', require("./chat/index"));

    var server = app.listen(app.get('port'), function() {console.log(app.get('appName')+' is Listening on port %d', server.address().port);});
</code>```

(/chat/index.js)

```<code>let express = require('express'),
    router = express.Router(),
    sqlite3 = require('sqlite3'),
    app = express(),
    http = require('http').Server(app),
    io = require('socket.io')(http),
    iconv = require('iconv-lite'),
    path = require('path'),
    sassMiddleware = require('node-sass-middleware'),
    fs = require('fs'),
    db = new sqlite3.Database('./history.db');

// DB
if (!fs.existsSync(__dirname + '/history.db'))
    db.run("CREATE TABLE message (id INTEGER PRIMARY KEY AUTOINCREMENT,txt TEXT)");

// VIEWS SETTINGS
console.log("__dirname is: "+__dirname);

app.set('views', __dirname + '/tpl');
app.engine('jade', require('jade').renderFile);
app.set('view engine', 'jade');
app.use(sassMiddleware({
    src: path.join(__dirname, '/tpl'),
    dest: path.join(__dirname, '/tpl'),
    debug: true,
    indentedSyntax: true,
    outputStyle: 'compressed',
}));
//app.use(express.static(__dirname + '/tpl'));

// ROUTER
router.get("/", function (req, res) {
    try{
        res.render('page');
    } catch(err){
        console.log(err)
    }

});

// DOP FUNC
function addMesToDB(txt) {
    var stmt = db.prepare("INSERT INTO message (txt) VALUES (?)");
    stmt.run(txt);
    stmt.finalize();
}
function loadLast10() {
    db.each("SELECT * FROM message LIMIT 10", function(err, row) {
        io.emit('new message show', row.txt);
    });
}
function loadAll() {
    db.each("SELECT * FROM message", function(err, row) {
        io.emit('new message show', row.txt);
    });
}
function getDateTime() {
    var date = new Date();
    var hour = date.getHours();
    hour = (hour < 10 ? "0" : "") + hour;
    var min  = date.getMinutes();
    min = (min < 10 ? "0" : "") + min;
    var sec  = date.getSeconds();
    sec = (sec < 10 ? "0" : "") + sec;
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    month = (month < 10 ? "0" : "") + month;
    var day  = date.getDate();
    day = (day < 10 ? "0" : "") + day;
    return year + ":" + month + ":" + day + ":" + hour + ":" + min + ":" + sec;
}

// EMIT
let name = '';
io.on('connection', function(socket){
    io.sockets.on('connection', function (client) {});
    socket.on('login', function(msg){
        if(msg == '888') name = 'Оксана';
        else if(msg == '8888') name = 'Виталий';
        if(msg == '888' || msg == '8888') {
            addMesToDB(getDateTime() + ' <span class="name">Вошел пользователь: ' + name + '</span>');
            loadLast10();
        }
    });
    socket.on('loadAll', function(msg){
        loadAll();
    });
    socket.on('new message send', function(msg){
        io.emit('new message show', getDateTime() + ' <span class="name">' + name + ':</span> <span class="msg">' + msg + '</span>');
        addMesToDB(getDateTime() + ' <span class="name">' + name + ':</span> ' + msg);
    });
    socket.on('disconnect', function () {
        io.emit('new message show', getDateTime() + '  <span class="name">Вышел пользователь: ' + name + '</span>');
        addMesToDB(getDateTime() + '  <span class="name">Вышел пользователь: ' + name + '</span>');
    });
});

module.exports = router;
</code>```

Title: Node: How to fix routing?

Body:
I need to use a router to integrate applications. To define an application I use app.use ('/ chat'. The application works separately, but it does not work together with the routing file.

How to fix routing?

/app.js

let express = require('express'),
    sqlite3 = require('sqlite3'),
    app = express(),
    http = require('http').Server(app),
    io = require('socket.io')(http),
    iconv = require('iconv-lite'),
    path = require('path'),
    sassMiddleware = require('node-sass-middleware'),
    fs = require('fs'),
    db = new sqlite3.Database('./chat/history.db');
    var routes = require('./chat');
    app.use('/chat', routes);
http.listen(3000);

chat/index.js

let express = require('express'),
    router = express.Router(),
    sqlite3 = require('sqlite3'),
    app = express(),
    http = require('http').Server(app),
    io = require('socket.io')(http),
    iconv = require('iconv-lite'),
    path = require('path'),
    sassMiddleware = require('node-sass-middleware'),
    fs = require('fs'),
    db = new sqlite3.Database('./history.db');

// DB
if (!fs.existsSync(__dirname + '/history.db'))
    db.run("CREATE TABLE message (id INTEGER PRIMARY KEY AUTOINCREMENT,txt TEXT)");

// VIEWS SETTINGS
app.set('views', __dirname + '/tpl');
app.set('view engine', 'jade');
app.use(sassMiddleware({
    src: path.join(__dirname, '/tpl'),
    dest: path.join(__dirname, '/tpl'),
    debug: true,
    indentedSyntax: true,
    outputStyle: 'compressed',
}));
app.use(express.static(__dirname + '/tpl'));

// ROUTER
router.get("/", function (req, res) {
    res.render('page', {"name": "Виталий"})
});

// DOP FUNC
function addMesToDB(txt) {
    var stmt = db.prepare("INSERT INTO message (txt) VALUES (?)");
    stmt.run(txt);
    stmt.finalize();
}
function loadLast10() {
    db.each("SELECT * FROM message LIMIT 10", function(err, row) {
        io.emit('new message show', row.txt);
    });
}
function loadAll() {
    db.each("SELECT * FROM message", function(err, row) {
        io.emit('new message show', row.txt);
    });
}
function getDateTime() {
    var date = new Date();
    var hour = date.getHours();
    hour = (hour < 10 ? "0" : "") + hour;
    var min  = date.getMinutes();
    min = (min < 10 ? "0" : "") + min;
    var sec  = date.getSeconds();
    sec = (sec < 10 ? "0" : "") + sec;
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    month = (month < 10 ? "0" : "") + month;
    var day  = date.getDate();
    day = (day < 10 ? "0" : "") + day;
    return year + ":" + month + ":" + day + ":" + hour + ":" + min + ":" + sec;
}

// EMIT
let name = '';
io.on('connection', function(socket){
    io.sockets.on('connection', function (client) {});
    socket.on('login', function(msg){
        if(msg == '888') name = 'Оксана';
        else if(msg == '8888') name = 'Виталий';
        if(msg == '888' || msg == '8888') {
            addMesToDB(getDateTime() + ' Вошел пользователь: ' + name + '');
            loadLast10();
        }
    });
    socket.on('loadAll', function(msg){
        loadAll();
    });
    socket.on('new message send', function(msg){
        io.emit('new message show', getDateTime() + ' ' + name + ': ' + msg + '');
        addMesToDB(getDateTime() + ' ' + name + ': ' + msg);
    });
    socket.on('disconnect', function () {
        io.emit('new message show', getDateTime() + '  Вышел пользователь: ' + name + '');
        addMesToDB(getDateTime() + '  Вышел пользователь: ' + name + '');
    });
});

module.exports = router;

err:

Error: No default engine was specified and no extension was provided.
    at new View (C:\chat2\chat2\node_modules\express\lib\view.js:62:11)
    at Function.render (C:\chat2\chat2\node_modules\express\lib\application.js:570:12)
    at ServerResponse.render (C:\chat2\chat2\node_modules\express\lib\response.js:971:7)
    at C:\chat2\chat2\chat\index.js:41:9
    at Layer.handle [as handle_request] (C:\chat2\chat2\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\chat2\chat2\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\chat2\chat2\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\chat2\chat2\node_modules\express\lib\router\layer.js:95:5)
    at C:\chat2\chat2\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\chat2\chat2\node_modules\express\lib\router\index.js:335:12)

Body:
just went through your git repo. You need to include jade in your node modules and in your app. I'll issue a pull request against your repo but the short answer is: update your chat/index.js to the following:

app.set('views', __dirname + '/tpl');
app.engine('jade', require('jade').renderFile);
app.set('view engine', 'jade');

You specify an engine via the app.engine() function rather than app.set(). You can then set the view (not views) engine as jade.

complete code: (index.js)

let express = require('express'),
    app = express(),
    http = require('http').Server(app),
    cfenv = require('cfenv'),
    appEnv = cfenv.getAppEnv();;

    app.set('appName', 'chat');
    app.set('port', appEnv.port);
    app.use('/', require("./chat/index"));

    var server = app.listen(app.get('port'), function() {console.log(app.get('appName')+' is Listening on port %d', server.address().port);});

(/chat/index.js)

let express = require('express'),
    router = express.Router(),
    sqlite3 = require('sqlite3'),
    app = express(),
    http = require('http').Server(app),
    io = require('socket.io')(http),
    iconv = require('iconv-lite'),
    path = require('path'),
    sassMiddleware = require('node-sass-middleware'),
    fs = require('fs'),
    db = new sqlite3.Database('./history.db');

// DB
if (!fs.existsSync(__dirname + '/history.db'))
    db.run("CREATE TABLE message (id INTEGER PRIMARY KEY AUTOINCREMENT,txt TEXT)");

// VIEWS SETTINGS
console.log("__dirname is: "+__dirname);

app.set('views', __dirname + '/tpl');
app.engine('jade', require('jade').renderFile);
app.set('view engine', 'jade');
app.use(sassMiddleware({
    src: path.join(__dirname, '/tpl'),
    dest: path.join(__dirname, '/tpl'),
    debug: true,
    indentedSyntax: true,
    outputStyle: 'compressed',
}));
//app.use(express.static(__dirname + '/tpl'));

// ROUTER
router.get("/", function (req, res) {
    try{
        res.render('page');
    } catch(err){
        console.log(err)
    }

});

// DOP FUNC
function addMesToDB(txt) {
    var stmt = db.prepare("INSERT INTO message (txt) VALUES (?)");
    stmt.run(txt);
    stmt.finalize();
}
function loadLast10() {
    db.each("SELECT * FROM message LIMIT 10", function(err, row) {
        io.emit('new message show', row.txt);
    });
}
function loadAll() {
    db.each("SELECT * FROM message", function(err, row) {
        io.emit('new message show', row.txt);
    });
}
function getDateTime() {
    var date = new Date();
    var hour = date.getHours();
    hour = (hour < 10 ? "0" : "") + hour;
    var min  = date.getMinutes();
    min = (min < 10 ? "0" : "") + min;
    var sec  = date.getSeconds();
    sec = (sec < 10 ? "0" : "") + sec;
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    month = (month < 10 ? "0" : "") + month;
    var day  = date.getDate();
    day = (day < 10 ? "0" : "") + day;
    return year + ":" + month + ":" + day + ":" + hour + ":" + min + ":" + sec;
}

// EMIT
let name = '';
io.on('connection', function(socket){
    io.sockets.on('connection', function (client) {});
    socket.on('login', function(msg){
        if(msg == '888') name = 'Оксана';
        else if(msg == '8888') name = 'Виталий';
        if(msg == '888' || msg == '8888') {
            addMesToDB(getDateTime() + ' <span class="name">Вошел пользователь: ' + name + '</span>');
            loadLast10();
        }
    });
    socket.on('loadAll', function(msg){
        loadAll();
    });
    socket.on('new message send', function(msg){
        io.emit('new message show', getDateTime() + ' <span class="name">' + name + ':</span> <span class="msg">' + msg + '</span>');
        addMesToDB(getDateTime() + ' <span class="name">' + name + ':</span> ' + msg);
    });
    socket.on('disconnect', function () {
        io.emit('new message show', getDateTime() + '  <span class="name">Вышел пользователь: ' + name + '</span>');
        addMesToDB(getDateTime() + '  <span class="name">Вышел пользователь: ' + name + '</span>');
    });
});

module.exports = router;