问:
python colored text without modifying the string
I have a python string:

```<code>my_string = 'thisisjustadummystringfortestingpurposes'
</code>```

I want to print some regions of the string with color red, so I use ANSI escape codes:

red: '\x1b[31m'

black: '\x1b[0m'

Then what I do is, I create a new string with the ANSI codes inserted.

Example:

```<code>my_color_seq = seq[:5]       # 0:5 will be black
my_color_seq += '\x1b[31m'   # start red
my_color_seq += seq[5:10]    # 5:10 will be red
my_color_seq += '\x1b[0m'    # start black
my_color_seq += seq[10:]     # 10: will be black

print(my_color_seq)
</code>```

This code works and correctly prints the region 5:10 red.
I have even created a loop where I can use a list of indexes and lengths for the regions that I want colored with red.

Now the problem is that in my colored string contain non visible characters (the ANSI codes), so the index of the characters is no longer what it seems to be.

Imagine that I want to now process again the colored string by painting some other fragments in blue. I can no longer trust the indexes since my string is now larger than it seems.

Of course I can update the indexes to point the correct locations in the new string, but I was just wondering if there is an easier way of doing this.

答:
You could make a wrapper around the string coloring, and print the returned values while keeping the original string intact:

Not shown in the example, but you can slice the original string, to selectively pass the substrings to the wrapper, with appropriate kwarg values, and re-assemble the returned values in a new string that can be further processes, or printed.

```<code>def colorize(token, bold_and_al='', fg_color='', bg_color=''):
    prefix = '\x1b['
    suffix = 'm'
    reset = '\x1b[0m'

    return '\x1b[' + bold_and_al + ";" + fg_color + ";" + bg_color + "m" + token + reset

a = 'thisisjustadummystringfortestingpurposes'
print(colorize(a, bold_and_al='1', fg_color='34', bg_color='42'))
</code>```

Edit:

Adding the example proposed by @MadPhysicist in the comments, to illustrate how the colorize wrapper could be used.:

```<code>print(''.join([colorize(a[:5], bold_and_al='1', fg_color='34', bg_color='42'), a[5:10], colorize(a[10:], bold_and_al='1', fg_color='32', bg_color='44')]))
</code>```

Body:
I have a python string:

my_string = 'thisisjustadummystringfortestingpurposes'

I want to print some regions of the string with color red, so I use ANSI escape codes:

red: '\x1b[31m'

black: '\x1b[0m'

Then what I do is, I create a new string with the ANSI codes inserted.

Example:

my_color_seq = seq[:5]       # 0:5 will be black
my_color_seq += '\x1b[31m'   # start red
my_color_seq += seq[5:10]    # 5:10 will be red
my_color_seq += '\x1b[0m'    # start black
my_color_seq += seq[10:]     # 10: will be black

print(my_color_seq)

This code works and correctly prints the region 5:10 red.
I have even created a loop where I can use a list of indexes and lengths for the regions that I want colored with red.

Now the problem is that in my colored string contain non visible characters (the ANSI codes), so the index of the characters is no longer what it seems to be.

Imagine that I want to now process again the colored string by painting some other fragments in blue. I can no longer trust the indexes since my string is now larger than it seems.

Of course I can update the indexes to point the correct locations in the new string, but I was just wondering if there is an easier way of doing this.

Body:
You could make a wrapper around the string coloring, and print the returned values while keeping the original string intact:

Not shown in the example, but you can slice the original string, to selectively pass the substrings to the wrapper, with appropriate kwarg values, and re-assemble the returned values in a new string that can be further processes, or printed.

def colorize(token, bold_and_al='', fg_color='', bg_color=''):
    prefix = '\x1b['
    suffix = 'm'
    reset = '\x1b[0m'

    return '\x1b[' + bold_and_al + ";" + fg_color + ";" + bg_color + "m" + token + reset

a = 'thisisjustadummystringfortestingpurposes'
print(colorize(a, bold_and_al='1', fg_color='34', bg_color='42'))

Edit:

Adding the example proposed by @MadPhysicist in the comments, to illustrate how the colorize wrapper could be used.:

print(''.join([colorize(a[:5], bold_and_al='1', fg_color='34', bg_color='42'), a[5:10], colorize(a[10:], bold_and_al='1', fg_color='32', bg_color='44')]))


来源: stackexchange

问:
HTTP Cache-Control
I'm new to HTTP caching and really need some help...

I saw many people set the "Cache-Control" header when sending XHR to server.
What is the purpose of doing that? Does request header needs caching too?

I've set this header for a XHR:
Cache-Control max-age=30, must-revalidate, but Firefox 3.6.13 seems do not re-validate the file when I refresh(even force refresh) after 30 seconds. No access-log in server either. Is this because I haven't set expire header to the file in Apache?

From Firebug log:

Response Headers

  Date Sat, 22 Jan 2011 09:59:21 GMT

  Last-Modified Thu, 20 Jan 2011 09:05:11 GMT

  Etag "3e000000023ca7-20d-49a436e5b3413"

Request Headers

  Keep-Alive 115

  Connection keep-alive

  Content-Type application/xml

  Cache-Control max-age=30, must-revalidate

The file have been modified, but Firefox does not even do conditional get. Response Date and Last-Modified not update at all.

答:
the server needs to set the re-validate directive, not the client.

the source controls if and how the content should be cacehd or not cached, the clients decides whether to honor it or not.

must-revalidate just means that a head request is sent and if the etag differes, the resources is refreshed. this is a very common an dsenseful practice for big files, because the e-tag generally changes once the content changes.

for small files however it may be your desire to not have any request at all, but a shorter time out. then must-revalidate is wrong.
the server load and the time it consumes of a head request to a 7kb image is not much less than serving the complete image.

ContentLicense: CC BY-SA 2.5

Title: HTTP Cache-Control


问:
Firebase facebook authentication
I am using Facebook Login as authentication in firebase and as I guess FirebaseAuth.getInstance().signOut(); needs an internet connection,but asking user turn internet connection while trying to logOut from the app is not good solution I think,so what could be alternative for preventing the user to have multiple credential for firebase?
Thx

答:
You need to know that FirebaseUser auth tokens expires. This is a website where the token can be verified.

If you use getToken(true), a new token will be created. This involves the linked providers token validation on the firebase servers, for example validating against Facebook authentication whether the user still has the account linked. Note that the latter counts towards your daily token service quotas. Make sure you use it only when it's necessary.

If a force refresh is not taking place, for example you are using firebaseUser.getToken(false), the returned token will not be updated automatically only if it has expired.

There will be no user with multiple credentials.

ContentLicense: CC BY-SA 3.0

Title: Firebase facebook authentication


问:
Oracle SQL Developer Postal Code
I am having a problem with a check constraint in Oracle SQL Developer with Oracle 11g Express Edition.

I want to check if my postal code which is stored as CHAR just contains numbers and no other signs.

Tried various possibilities but nothing worked...

```<code>PLZ VARCHAR(5) NOT NULL

ADD CONSTRAINT TC_PLZ CHECK (PLZ LIKE '[0-9][0-9][0-9][0-9][0-9]')
</code>```

Thanks and best regards,

Michael

答:
Use regexp_like():

```<code>ADD CONSTRAINT TC_PLZ CHECK ( regexp_like(PLZ, '^[0-9]{5}$') )
</code>```

Oracle -- like most databases -- only supports the ANSI standard wildcards in LIKE.  These are % for zero or more characters and _ for exactly one character.

Regular expressions are much more powerful (although generally slower).

This might be a bit more efficient:

```<code>ADD CONSTRAINT TC_PLZ CHECK (translate(PLZ, '0123456789', '000000000') = '00000')
</code>```

although I would go with the regular expression for clarity.

Title: Oracle SQL Developer Postal Code

Body:
I am having a problem with a check constraint in Oracle SQL Developer with Oracle 11g Express Edition.

I want to check if my postal code which is stored as CHAR just contains numbers and no other signs.

Tried various possibilities but nothing worked...

PLZ VARCHAR(5) NOT NULL

ADD CONSTRAINT TC_PLZ CHECK (PLZ LIKE '[0-9][0-9][0-9][0-9][0-9]')

Thanks and best regards,

Michael

Body:
Use regexp_like():

ADD CONSTRAINT TC_PLZ CHECK ( regexp_like(PLZ, '^[0-9]{5}$') )

Oracle -- like most databases -- only supports the ANSI standard wildcards in LIKE.  These are % for zero or more characters and _ for exactly one character.

Regular expressions are much more powerful (although generally slower).

This might be a bit more efficient:

ADD CONSTRAINT TC_PLZ CHECK (translate(PLZ, '0123456789', '000000000') = '00000')

although I would go with the regular expression for clarity.


问:
Rerendering a Pylons form with a querystring parameter after FormEncode validation fails
My question may be the same as this, but the suggested answer didn't seem to help (or I didn't understand it correctly): Pylons FormEncode @validate decorator pass parameters into re-render action

I have a simple form that takes a required querystring (id) value, uses that as a hidden form field value, and validates the posted data. The controller looks like this:

```<code>class NewNodeForm(formencode.Schema):
  parent_id = formencode.validators.Int(not_empty = True)
  child_name = formencode.validators.String(not_empty = True)

def newnode(self, id):
  c.parent_id = id
  return render('newnode.html')

@validate(schema=NewNodeForm(), form='newnode')
def createnode(self):
  parentId = self.form_result.get('parent_id')
  childName = self.form_result.get('child_name')
  nodeId = save_the_data(parentId, childName)
  return redirect_to(controller = 'node', action = 'view', id = nodeId)
</code>```

and the form is very basic:

```<code><form method="post" action="/node/createnode">
  <input type="text" name="child_name">
  <input type="hidden" value="${c.parent_id}" name="parent_id">
  <input name="submit" type="submit" value="Submit">
</form>
</code>```

Everything works fine if the validation passes, but if it fails, newnode can't be called because id isn't passed back. It throws TypeError: newnode() takes exactly 2 arguments (1 given). Simply defining as newnode(self, id = None) gets around this problem, but I can't do that as the id is required by the logic.

This seems so simple, but what am I missing?

答:
When validation failed the validate decorator call you newnode with modified request object, but all GET/POST arguments must be not changed

```<code>def newnode(self, id=None):
  c.parent_id = id or request.params.get('parent_id')
  return render('newnode.html')
</code>```

Body:
My question may be the same as this, but the suggested answer didn't seem to help (or I didn't understand it correctly): Pylons FormEncode @validate decorator pass parameters into re-render action

I have a simple form that takes a required querystring (id) value, uses that as a hidden form field value, and validates the posted data. The controller looks like this:

class NewNodeForm(formencode.Schema):
  parent_id = formencode.validators.Int(not_empty = True)
  child_name = formencode.validators.String(not_empty = True)

def newnode(self, id):
  c.parent_id = id
  return render('newnode.html')

@validate(schema=NewNodeForm(), form='newnode')
def createnode(self):
  parentId = self.form_result.get('parent_id')
  childName = self.form_result.get('child_name')
  nodeId = save_the_data(parentId, childName)
  return redirect_to(controller = 'node', action = 'view', id = nodeId)

and the form is very basic:

<form method="post" action="/node/createnode">
  <input type="text" name="child_name">
  <input type="hidden" value="${c.parent_id}" name="parent_id">
  <input name="submit" type="submit" value="Submit">
</form>

Everything works fine if the validation passes, but if it fails, newnode can't be called because id isn't passed back. It throws TypeError: newnode() takes exactly 2 arguments (1 given). Simply defining as newnode(self, id = None) gets around this problem, but I can't do that as the id is required by the logic.

This seems so simple, but what am I missing?

Body:
When validation failed the validate decorator call you newnode with modified request object, but all GET/POST arguments must be not changed

def newnode(self, id=None):
  c.parent_id = id or request.params.get('parent_id')
  return render('newnode.html')


问:
Why JDI Test Framework use static methods for pages
According to documentation https://github.com/epam/JDI

Note: all fields and methods on your Site page are STATIC

Why there is such requirement? And if the test cases will work in parallel?
For example, we know the fact that if webdriver is static - we have a problem.

答:
This is not a requirement. This is possibility. You can use not static.

We recommend static because this do your tests shorter (with static import)

Paralleling works well because of Driver factory manage different driver instances for different threads. And elements has only "driver name"


问:
how to continue with $q.all() when some promises fail
I have an array of promises and each promise calls http.get().

```<code>var items = ["URL1", "URL2", "URL3"];
var promises = [];
//on each URL in items array, I want to create a promise and call http.get
items.forEach(function(el){
    return promises.push($http.get(el));
});
var all = $q.all(promises);
all.then(function success(data){
    console.log(data);
}).catch(function(reason){
    console.log("reason is", reason);
});
</code>```

what's happening in my case

URL2.get does not get resolved, and it immediately triggers the catch() in the $q.all. As a result of this failure all.then() never gets invoked.

what I want

I want all the promises to continue even if one of the promise is rejected.

I found a similar post but the solution suggests to use another angular pacakage called Kris Kowal's Q. so I'm wondering how can I achieve it without using external package?

答:
i wrapped the $resource in $q with only resolve state </p>

```<code>var promises = [
     $q(function (resolve) {
        Me.get({params: 12}).$promise.then(function (data) {
           resolve(data);
        }, function (err) {
           resolve(err);
        });
     }),
     $q(function (resolve) {
        Me.get({params: 123}).$promise.then(function (data) {
           resolve(data);
        }, function (err) {
           resolve(err);
        });
     }),
     $q(function (resolve) {
        Me.get({params: 124}).$promise.then(function (data) {
           resolve(data);
        }, function (err) {
           resolve(err);
        });
     })];
</code>```

<p>and then use $q.all to promises </p>

Body:
I have an array of promises and each promise calls http.get().

var items = ["URL1", "URL2", "URL3"];
var promises = [];
//on each URL in items array, I want to create a promise and call http.get
items.forEach(function(el){
    return promises.push($http.get(el));
});
var all = $q.all(promises);
all.then(function success(data){
    console.log(data);
}).catch(function(reason){
    console.log("reason is", reason);
});

what's happening in my case

URL2.get does not get resolved, and it immediately triggers the catch() in the $q.all. As a result of this failure all.then() never gets invoked.

what I want

I want all the promises to continue even if one of the promise is rejected.

I found a similar post but the solution suggests to use another angular pacakage called Kris Kowal's Q. so I'm wondering how can I achieve it without using external package?

Body:
i wrapped the $resource in $q with only resolve state

var promises = [
     $q(function (resolve) {
        Me.get({params: 12}).$promise.then(function (data) {
           resolve(data);
        }, function (err) {
           resolve(err);
        });
     }),
     $q(function (resolve) {
        Me.get({params: 123}).$promise.then(function (data) {
           resolve(data);
        }, function (err) {
           resolve(err);
        });
     }),
     $q(function (resolve) {
        Me.get({params: 124}).$promise.then(function (data) {
           resolve(data);
        }, function (err) {
           resolve(err);
        });
     })];

and then use $q.all to promises


问:
Formatting a PHP multi line string
I have been trying to create a contact form auto-responder with a select list, one of the main sources I used is this

The only change I did to his code is obviously the variables and changed

```<code>add_action( 'wpcf7_mail_sent', 'contact_form_autoresponders' );
</code>```

to

```<code>add_action( 'wpcf7_mail_sent', array($this, 'contact_form_autoresponders' ), 5);
</code>```

I have been trying to create an automated email responder for any options out of the selected 'select' menu.

I have been importing another file.php which contains all the string variables I need with "<<

all the variables in file.php looks like this:

```<code>$some_variable =<<<EOT multiple
                    lines
                     here
 EOT;
</code>```

Since My email responses are in Hebrew I want the responded mail to be sent right to left and I am looking all over the place for a way to align my string to the right and add some URL marks and can't find it.

I tried adding this to the Headers and String head and it didn't work out for me

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"
direction="rtl">
</code>```

Any help would be appreciated.

答:
Replace...

direction="rtl"

with

dir="rtl"

You can find more informations here https://www.w3.org/International/questions/qa-html-dir

Remember to change lang attribute too.

Title: Formatting a PHP multi line string

Body:
I have been trying to create a contact form auto-responder with a select list, one of the main sources I used is this

The only change I did to his code is obviously the variables and changed

add_action( 'wpcf7_mail_sent', 'contact_form_autoresponders' );

to

add_action( 'wpcf7_mail_sent', array($this, 'contact_form_autoresponders' ), 5);

I have been trying to create an automated email responder for any options out of the selected 'select' menu.

I have been importing another file.php which contains all the string variables I need with "<<

all the variables in file.php looks like this:

$some_variable =<<<EOT multiple
                    lines
                     here
 EOT;

Since My email responses are in Hebrew I want the responded mail to be sent right to left and I am looking all over the place for a way to align my string to the right and add some URL marks and can't find it.

I tried adding this to the Headers and String head and it didn't work out for me

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

Any help would be appreciated.


问:
How to properly catch exceptions from C#'s HttpClient getAsync so the error says more than "One or more errors occurred"?
The following is some code that downloads a file using System.Net.Http.HttpClient

```<code>try
{
    var responseResult = new System.Net.Http.HttpClient().GetAsync(fileUrl);
    using (var memStream = responseResult.Result.Content.ReadAsStreamAsync().Result)
    {
        using (var fileStream = File.Create(saveToPath))
        {
            memStream.CopyTo(fileStream);
        }

    }
}
catch (Exception e)
{
    Console.WriteLine(e.StackTrace);
}
</code>```

Sometimes I call this and a file fails to download. In that situation, the catch is called but doesn't contain any information of the issue:

```<code>One or more errors occurred.
    at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
    at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
    at System.Threading.Tasks.Task`1.get_Result()
    at SpPrefetchIndexBuilder.FileDownloader.StartDownloads(Int32 timeout)
</code>```

How can I get it to the cause of this exception?

答:
Task.Result throws AggregateException, so you can catch that. All exceptions will be inside InnerExceptions property of that exception (there can be multiple in theory, but in your case there will be just one). First of those exceptions (or the only one if there is just one) is also in InnerException property.

If you don't want to dig inside AggregateException, use .GetAwaiter().GetResult() instead of .Result - this will not wrap exception into AggregateException and will throw it as is.

Body:
The following is some code that downloads a file using System.Net.Http.HttpClient

try
{
    var responseResult = new System.Net.Http.HttpClient().GetAsync(fileUrl);
    using (var memStream = responseResult.Result.Content.ReadAsStreamAsync().Result)
    {
        using (var fileStream = File.Create(saveToPath))
        {
            memStream.CopyTo(fileStream);
        }

    }
}
catch (Exception e)
{
    Console.WriteLine(e.StackTrace);
}

Sometimes I call this and a file fails to download. In that situation, the catch is called but doesn't contain any information of the issue:

One or more errors occurred.
    at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
    at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
    at System.Threading.Tasks.Task`1.get_Result()
    at SpPrefetchIndexBuilder.FileDownloader.StartDownloads(Int32 timeout)

How can I get it to the cause of this exception?


问:
Config error with EF 2.0, UWP (targeting 16299 and later), and Nuget
I'm currently trying to build a UWP with EF Core, and decided since I saw 2.0 support was coming with the update today to use EF 2.0 with a UWP targeting 16299 and later.

I got EF Core working (migrations, etc) for sure, using a sample dotnet core console app. When I went to work on the UWP, I ran into the following error, which appears to be Nuget related:

```<code>Error
Cannot find type Microsoft.EntityFrameworkCore.Metadata.Internal.RelationalFullAnnotationNames
in module Microsoft.EntityFrameworkCore.Relational.dll
</code>```

I've installed the relevant package (to my knowledge). I don't know what further information is relevant, so I'll update my post as needed.

Additionally, the output log error is more descriptive:

C:\Program Files (x86)\Windows Kits\10\bin\10.0.16299.0\XamlCompiler\Microsoft.Windows.UI.Xaml.Common.targets(353,5): Xaml Internal Error error WMC9999: Cannot find type Microsoft.EntityFrameworkCore.Metadata.Internal.RelationalFullAnnotationNames in module Microsoft.EntityFrameworkCore.Relational.dll.

答:
I had this problem and it was because I had referenced too much stuff.

I had references to :

```<code>Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Relational
Microsoft.EntityFrameworkCore.Relational.Design
Microsoft.EntityFrameworkCore.SqlServer.Design
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
</code>```

but I only need

```<code>Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
</code>```

when i removed the unneeded references cleaned soln, and restarted vs,
everything worked ok.

ContentLicense: CC BY-SA 4.0

Body:
I'm currently trying to build a UWP with EF Core, and decided since I saw 2.0 support was coming with the update today to use EF 2.0 with a UWP targeting 16299 and later.

I got EF Core working (migrations, etc) for sure, using a sample dotnet core console app. When I went to work on the UWP, I ran into the following error, which appears to be Nuget related:

Error
Cannot find type Microsoft.EntityFrameworkCore.Metadata.Internal.RelationalFullAnnotationNames
in module Microsoft.EntityFrameworkCore.Relational.dll

I've installed the relevant package (to my knowledge). I don't know what further information is relevant, so I'll update my post as needed.

Additionally, the output log error is more descriptive:

C:\Program Files (x86)\Windows Kits\10\bin\10.0.16299.0\XamlCompiler\Microsoft.Windows.UI.Xaml.Common.targets(353,5): Xaml Internal Error error WMC9999: Cannot find type Microsoft.EntityFrameworkCore.Metadata.Internal.RelationalFullAnnotationNames in module Microsoft.EntityFrameworkCore.Relational.dll.

Body:
I had this problem and it was because I had referenced too much stuff.

I had references to :

Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Relational
Microsoft.EntityFrameworkCore.Relational.Design
Microsoft.EntityFrameworkCore.SqlServer.Design
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools

but I only need

Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools

when i removed the unneeded references cleaned soln, and restarted vs,
everything worked ok.


问:
UILocalNotification are showing only on lock screen/Notification screen
Whenever app receive silent push , I am displaying the local notification.
If at the time of receiving the silent push , iPhone is locked , local notification are displaying but if application is in background and iPhone is not locked then local notification are not displaying. What could be wrong. ? I am using below code ? </p>

```<code>    let content = UNMutableNotificationContent()
content.title = "Connect"
content.body = indentificationText
content.sound = UNNotificationSound.default()

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1,
                                                repeats: false)

let appDelegate = UIApplication.shared.delegate as! AppDelegate

UNUserNotificationCenter.current().delegate = appDelegate
content.userInfo = payload.dictionaryPayload

let request = UNNotificationRequest(identifier: content.title, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error) in
    NSLog("UNUserNotificationCenter Add completion Handler : \(String(describing: error?.localizedDescription))")
})
</code>```

答: The app may be suspended in the background , so the code that creates the local notification isn't executed . . .

Body:
Whenever app receive silent push , I am displaying the local notification.
If at the time of receiving the silent push , iPhone is locked , local notification are displaying but if application is in background and iPhone is not locked then local notification are not displaying. What could be wrong. ? I am using below code ?

    let content = UNMutableNotificationContent()
content.title = "Connect"
content.body = indentificationText
content.sound = UNNotificationSound.default()

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1,
                                                repeats: false)

let appDelegate = UIApplication.shared.delegate as! AppDelegate

UNUserNotificationCenter.current().delegate = appDelegate
content.userInfo = payload.dictionaryPayload

let request = UNNotificationRequest(identifier: content.title, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error) in
    NSLog("UNUserNotificationCenter Add completion Handler : \(String(describing: error?.localizedDescription))")
})


问:
Why is my form being flattened without calling the flattenFields method?
I am testing my method with this form https://help.adobe.com/en_US/Acrobat/9.0/Samples/interactiveform_enabled.pdf

It is being called like so:

```<code>Pdf.editForm("./src/main/resources/pdfs/interactiveform_enabled.pdf", "./src/main/resources/pdfs/FILLEDOUT.pdf"));
</code>```

where Pdf is just a worker class and editForm is a static method.

The editForm method looks like this:

```<code>public static int editForm(String inputPath, String outputPath) {
    try {
        PdfDocument pdf = new PdfDocument(new PdfReader(inputPath), new PdfWriter(outputPath));
        PdfAcroForm form = PdfAcroForm.getAcroForm(pdf, true);
        Map<String, PdfFormField> m = form.getFormFields();
        for (String s : m.keySet()) {
            if (s.equals("Name_First")) {
                m.get(s).setValue("Tristan");
            }
            if (s.equals("BACHELORS DEGREE")) {
                m.get(s).setValue("Off"); // On or Off
            }
            if (s.equals("Sex")) {
                m.get(s).setValue("FEMALE");
            }
            System.out.println(s);
        }
        pdf.close();
        logger.info("Completed");
    } catch (IOException e) {
        logger.error("Unable to fill form " + outputPath + "\n\t" + e);
        return 1;
    }

    return 0;
}
</code>```

Unfortunately the FILLEDOUT.pdf file is no longer a form after calling this method. Am I doing something wrong?

I was using this resource for guidance. Notice how I am not calling the form.flattenFields(). If I do call that method however, I get an error of java.lang.IllegalArgumentException.

Thank you for your time.

答:
The filled in PDF is still an AcroForm, otherwise the example below would result in the same PDF twice.

public class Main {
public static final String SRC = "src/main/resources/interactiveform_enabled.pdf";
public static final String DEST = "results/filled_form.pdf";
public static final String DEST2 = "results/filled_form_second_time.pdf";

public static void main(String[] args) throws Exception {
    File file = new File(DEST);
    file.getParentFile().mkdirs();
    Main main = new Main();

    Map<String, String> data1 = new HashMap<>();
    data1.put("Name_First", "Tristan");
    data1.put("BACHELORS DEGREE", "Off");
    main.fillPdf(SRC, DEST, data1, false);

    Map<String, String> data2 = new HashMap<>();
    data2.put("Sex", "FEMALE");
    main.fillPdf(DEST, DEST2, data2, false);
}

private void fillPdf(String src, String dest, Map<String, String> data, boolean flatten) {
    try {
        PdfDocument pdf = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
        PdfAcroForm form = PdfAcroForm.getAcroForm(pdf, true);

        //Delete print field from acroform because it is defined in the contentstream not in the formfields
        form.removeField("Print");

        Map<String, PdfFormField> m = form.getFormFields();

        for (String d : data.keySet()) {
            for (String s : m.keySet()) {
                if(s.equals(d)){
                    m.get(s).setValue(data.get(d));
                }
            }
        }

        if(flatten){
            form.flattenFields();
        }

        pdf.close();
        System.out.println("Completed");
    } catch (IOException e) {
        System.out.println("Unable to fill form " + dest + "\n\t" + e);
    }
}
}
```

The issue you are facing has to do with the 'reader enabled forms'.
What it boils down to is that the PDF file that is initially fed to your program is reader enabled. Hence you can open the PDF in Adobe Reader and fill in the form. This allows Acrobat users to extend the behaviour of Adobe Reader.
Once the PDF is filled in and closed using iText it saves the PDF as 'not reader-extended'.
This makes it so that the AcroForm can still be filled using iText but when you open the PDF using Adobe Reader the extended functionality you see in the original PDF is gone. But this does not mean the form is flattened.

iText cannot make a form reader enabled, as a matter of fact, the only way to create a reader enabled form is using Acrobat Professional. This is how Acrobat and Adobe Reader interact and it is not something iText can imitate or solve. You can find some more info and a possible solution on this link.

The IllegalArgumentException you get when you call the form.flattenFields() method is because of the way the PDF document was constructed.
The "Print form" button should have been defined in the AcroForm, yet it is defined in the contentstream of the PDF, meaning the button in the AcroForm has an empty text value, and this is what causes the exception.

You can fix this by removing the print field from the AcroForm before you flatten.

Body:
I am testing my method with this form https://help.adobe.com/en_US/Acrobat/9.0/Samples/interactiveform_enabled.pdf

It is being called like so:

Pdf.editForm("./src/main/resources/pdfs/interactiveform_enabled.pdf", "./src/main/resources/pdfs/FILLEDOUT.pdf"));

where Pdf is just a worker class and editForm is a static method.

The editForm method looks like this:

public static int editForm(String inputPath, String outputPath) {
    try {
        PdfDocument pdf = new PdfDocument(new PdfReader(inputPath), new PdfWriter(outputPath));
        PdfAcroForm form = PdfAcroForm.getAcroForm(pdf, true);
        Map<String, PdfFormField> m = form.getFormFields();
        for (String s : m.keySet()) {
            if (s.equals("Name_First")) {
                m.get(s).setValue("Tristan");
            }
            if (s.equals("BACHELORS DEGREE")) {
                m.get(s).setValue("Off"); // On or Off
            }
            if (s.equals("Sex")) {
                m.get(s).setValue("FEMALE");
            }
            System.out.println(s);
        }
        pdf.close();
        logger.info("Completed");
    } catch (IOException e) {
        logger.error("Unable to fill form " + outputPath + "\n\t" + e);
        return 1;
    }

    return 0;
}

Unfortunately the FILLEDOUT.pdf file is no longer a form after calling this method. Am I doing something wrong?

I was using this resource for guidance. Notice how I am not calling the form.flattenFields(). If I do call that method however, I get an error of java.lang.IllegalArgumentException.

Thank you for your time.

Body:
The filled in PDF is still an AcroForm, otherwise the example below would result in the same PDF twice.

public class Main {
public static final String SRC = "src/main/resources/interactiveform_enabled.pdf";
public static final String DEST = "results/filled_form.pdf";
public static final String DEST2 = "results/filled_form_second_time.pdf";

public static void main(String[] args) throws Exception {
    File file = new File(DEST);
    file.getParentFile().mkdirs();
    Main main = new Main();

    Map<String, String> data1 = new HashMap<>();
    data1.put("Name_First", "Tristan");
    data1.put("BACHELORS DEGREE", "Off");
    main.fillPdf(SRC, DEST, data1, false);

    Map<String, String> data2 = new HashMap<>();
    data2.put("Sex", "FEMALE");
    main.fillPdf(DEST, DEST2, data2, false);
}

private void fillPdf(String src, String dest, Map<String, String> data, boolean flatten) {
    try {
        PdfDocument pdf = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
        PdfAcroForm form = PdfAcroForm.getAcroForm(pdf, true);

        //Delete print field from acroform because it is defined in the contentstream not in the formfields
        form.removeField("Print");

        Map<String, PdfFormField> m = form.getFormFields();

        for (String d : data.keySet()) {
            for (String s : m.keySet()) {
                if(s.equals(d)){
                    m.get(s).setValue(data.get(d));
                }
            }
        }

        if(flatten){
            form.flattenFields();
        }

        pdf.close();
        System.out.println("Completed");
    } catch (IOException e) {
        System.out.println("Unable to fill form " + dest + "\n\t" + e);
    }
}
}

The issue you are facing has to do with the 'reader enabled forms'.
What it boils down to is that the PDF file that is initially fed to your program is reader enabled. Hence you can open the PDF in Adobe Reader and fill in the form. This allows Acrobat users to extend the behaviour of Adobe Reader.
Once the PDF is filled in and closed using iText it saves the PDF as 'not reader-extended'.
This makes it so that the AcroForm can still be filled using iText but when you open the PDF using Adobe Reader the extended functionality you see in the original PDF is gone. But this does not mean the form is flattened.

iText cannot make a form reader enabled, as a matter of fact, the only way to create a reader enabled form is using Acrobat Professional. This is how Acrobat and Adobe Reader interact and it is not something iText can imitate or solve. You can find some more info and a possible solution on this link.

The IllegalArgumentException you get when you call the form.flattenFields() method is because of the way the PDF document was constructed.
The "Print form" button should have been defined in the AcroForm, yet it is defined in the contentstream of the PDF, meaning the button in the AcroForm has an empty text value, and this is what causes the exception.

You can fix this by removing the print field from the AcroForm before you flatten.


问:
How to send javascript value to views.py django
I am trying to send a value from javascript to views.py function in Django.

The code as following:

```<code><form name="myform" action="" method="get">

    <button id="button" name="button" onclick="click()">send</button>
    <input type="hidden" id="data" name="data" value="">
    <script>
        function click() {
            var d = 100
            document.getElementById("data").value = d;
            document.myform.submit();
        }
    </script>

</form>
</code>```

In views.py,

```<code>def views(request): #assume function name is views
    result = request.GET.get("data")
</code>```

, but this method is failed, please guide me.

答:
This worked for me:

```<code><form name="myform" action="" method="get">
    <button id="button" name="button" onclick="myFunction()">send</button>
    <input type="hidden" id="data" name="data" value="">
    <script>
        function myFunction() {
            var d = 100
            document.getElementById("data").value = d;
            console.log(document.getElementById("data").value);
        }
    </script>

</form>
</code>```

Change the name of the function and comment the submit of the form.

Body:
I am trying to send a value from javascript to views.py function in Django.

The code as following:

<form name="myform" action="" method="get">

    <button id="button" name="button" onclick="click()">send</button>
    <input type="hidden" id="data" name="data" value="">

</form>

In views.py,

def views(request): #assume function name is views
    result = request.GET.get("data")

, but this method is failed, please guide me.

Body:
This worked for me:

<form name="myform" action="" method="get">
    <button id="button" name="button" onclick="myFunction()">send</button>
    <input type="hidden" id="data" name="data" value="">
    <script>
        function myFunction() {
            var d = 100
            document.getElementById("data").value = d;
            console.log(document.getElementById("data").value);
        }
    </script>

</form>

Change the name of the function and comment the submit of the form.


问:
How to debug code for reset functionality in Java GUI application?
I am writing some simulation code and managed to get my model running as expected. However when I reset the model (it sits on top of a large amount of code written by others that i don't have access to right now) and want to rerun it I run into trouble.

From what I have gathered from reading posts on the site and errors i receive problems occur because of null pointer exceptions and Awt-queue errors because of some of the graphical elements running into trouble after the reset (because of those items they relate to are no longer valid).

0- What generally happens when the reset button is pressed in a simulation code? I guess (hope) everyone else has done their homework right and since i am ignorant about this i need to do some clean up of my own to make everything act nice.

1-Now what is the easiest way to fix these sort of problems that only happen after when rerunning code?

2-Also what are general guidelines for clean up of code after each run of a simulation?

答:
I don't know the answer to items 0 and 2 so any contribution is appreciated.

I just realised what the problem was. The GUI was not being refreshed properly so it referred back to "cleaned up" items that after the first run did not exist any more and thus all sorts of weird errors were thrown...


问:
How to use substitute function to decrypt and encrypt messages
I want to encrypt and decrypt messages by changing the character A to N, and B to O ..like you see in my code. I need some help to to that, thanks!!</p>

```<code>Sub MacroCryptage()
Dim ws1 As Worksheet
Set ws1 = Worksheets("Feuil1")
Dim rng As Range, cell As Range
Set rng = ws1.Range("G" & 6)
Set cell = ws1.Range("G" & 5)

    rng = WorksheetFunction.Substitute(cell, "A", "N")
    rng = WorksheetFunction.Substitute(cell, "B", "O")
    rng = WorksheetFunction.Substitute(cell, "C", "P")
    rng = WorksheetFunction.Substitute(cell, "D", "Q")
    rng = WorksheetFunction.Substitute(cell, "E", "R")
    rng = WorksheetFunction.Substitute(cell, "F", "S")
    rng = WorksheetFunction.Substitute(cell, "G", "T")
    rng = WorksheetFunction.Substitute(cell, "H", "U")
    rng = WorksheetFunction.Substitute(cell, "I", "V")
    rng = WorksheetFunction.Substitute(cell, "J", "W")
    rng = WorksheetFunction.Substitute(cell, "K", "X")
    rng = WorksheetFunction.Substitute(cell, "L", "Y")
    rng = WorksheetFunction.Substitute(cell, "M", "Z")
    rng = WorksheetFunction.Substitute(cell, "N", "A")
    rng = WorksheetFunction.Substitute(cell, "O", "B")
    rng = WorksheetFunction.Substitute(cell, "P", "C")
    rng = WorksheetFunction.Substitute(cell, "Q", "D")
    rng = WorksheetFunction.Substitute(cell, "R", "E")
    rng = WorksheetFunction.Substitute(cell, "S", "F")
    rng = WorksheetFunction.Substitute(cell, "T", "G")
    rng = WorksheetFunction.Substitute(cell, "U", "H")
    rng = WorksheetFunction.Substitute(cell, "V", "I")
    rng = WorksheetFunction.Substitute(cell, "W", "J")
    rng = WorksheetFunction.Substitute(cell, "X", "K")
    rng = WorksheetFunction.Substitute(cell, "Y", "L")
    rng = WorksheetFunction.Substitute(cell, "Z", "M")

End Sub
</code>```

答:
Your immediate problem is that your solution only applies to two specified cells. You should write it as a function that accepts the original text and returns the coded string

What you are looking at is ROT13. The simplest way to implement this is to use the ASCII values of the characters. In VBA you can use the ASC() function to return the ascii value of a char, then add 13 and then use the CHR() function to turn that value back into a character. This version only works on upper case text - characters 65 to 90. Lower case run 97 to 122 so you could add a test for that if you wanted

```<code>Public Function Cypher(origtext as string) as string
dim s as string
dim answer as string
dim x as integer
dim myvar as integer
for x = 1 to len(origtext)
     s = mid(origtext,x,1)
     myvar = asc(s)+13
     if myvar > 90 then myvar = 65 + (myvar-91) ' 91 maps to 65, etc. Could instead just use myvar = myvar - 26
     s = chr(myvar)
     answer = answer & s
next x
Cypher = answer
End Function
</code>```

To use this, in the spreadsheet enter =Cypher(cell ref) where cell ref contains the text you want to cypher

Body:
I want to encrypt and decrypt messages by changing the character A to N, and B to O ..like you see in my code. I need some help to to that, thanks!!

Sub MacroCryptage()
Dim ws1 As Worksheet
Set ws1 = Worksheets("Feuil1")
Dim rng As Range, cell As Range
Set rng = ws1.Range("G" & 6)
Set cell = ws1.Range("G" & 5)

    rng = WorksheetFunction.Substitute(cell, "A", "N")
    rng = WorksheetFunction.Substitute(cell, "B", "O")
    rng = WorksheetFunction.Substitute(cell, "C", "P")
    rng = WorksheetFunction.Substitute(cell, "D", "Q")
    rng = WorksheetFunction.Substitute(cell, "E", "R")
    rng = WorksheetFunction.Substitute(cell, "F", "S")
    rng = WorksheetFunction.Substitute(cell, "G", "T")
    rng = WorksheetFunction.Substitute(cell, "H", "U")
    rng = WorksheetFunction.Substitute(cell, "I", "V")
    rng = WorksheetFunction.Substitute(cell, "J", "W")
    rng = WorksheetFunction.Substitute(cell, "K", "X")
    rng = WorksheetFunction.Substitute(cell, "L", "Y")
    rng = WorksheetFunction.Substitute(cell, "M", "Z")
    rng = WorksheetFunction.Substitute(cell, "N", "A")
    rng = WorksheetFunction.Substitute(cell, "O", "B")
    rng = WorksheetFunction.Substitute(cell, "P", "C")
    rng = WorksheetFunction.Substitute(cell, "Q", "D")
    rng = WorksheetFunction.Substitute(cell, "R", "E")
    rng = WorksheetFunction.Substitute(cell, "S", "F")
    rng = WorksheetFunction.Substitute(cell, "T", "G")
    rng = WorksheetFunction.Substitute(cell, "U", "H")
    rng = WorksheetFunction.Substitute(cell, "V", "I")
    rng = WorksheetFunction.Substitute(cell, "W", "J")
    rng = WorksheetFunction.Substitute(cell, "X", "K")
    rng = WorksheetFunction.Substitute(cell, "Y", "L")
    rng = WorksheetFunction.Substitute(cell, "Z", "M")

End Sub

Body:
Your immediate problem is that your solution only applies to two specified cells. You should write it as a function that accepts the original text and returns the coded string

What you are looking at is ROT13. The simplest way to implement this is to use the ASCII values of the characters. In VBA you can use the ASC() function to return the ascii value of a char, then add 13 and then use the CHR() function to turn that value back into a character. This version only works on upper case text - characters 65 to 90. Lower case run 97 to 122 so you could add a test for that if you wanted

Public Function Cypher(origtext as string) as string
dim s as string
dim answer as string
dim x as integer
dim myvar as integer
for x = 1 to len(origtext)
     s = mid(origtext,x,1)
     myvar = asc(s)+13
     if myvar > 90 then myvar = 65 + (myvar-91) ' 91 maps to 65, etc. Could instead just use myvar = myvar - 26
     s = chr(myvar)
     answer = answer & s
next x
Cypher = answer
End Function

To use this, in the spreadsheet enter =Cypher(cell ref) where cell ref contains the text you want to cypher


问:
How to reformat old code into new one with table prefixes?
we have a bunch of stored procedures which we would like to have cleary and unified formatted, including a table prefixes.

E.g.:
We have:

```<code>SELECT [SalesRegionId], [SalesRegionName]
FROM dim.[SalesRegion]
WHERE [SalesRegionId] BETWEEN 1 AND 7
</code>```

and we want:

```<code>SELECT
        [sr].[SalesRegionId]
       ,[sr].[SalesRegionName]
FROM
       dim.[SalesRegion] sr
WHERE
      [sr].[SalesRegionId] BETWEEN 1 AND 7
</code>```

Is there a way how to automate the process?
Thanks in advance.

答:
I found what appears to be this exact question on MSDN here. The basics of it are as follows:

Position to AdventureWorks2008 or your database  in SSMS Query Editor

Enter the following or your query:

select * from Sales.SalesOrderHeader soh inner join
  Sales.SalesOrderDetail sod on soh.SalesOrderID = sod.SalesOrderID

Select Design Query in Query drop-down menu

You will see  the * replaced by columns with aliases.

Press OK at the bottom

Using this method, you can change your query to use *, and then just clean up the field list, or you should be able to select the actual columns you want from the query designer.

Body:
we have a bunch of stored procedures which we would like to have cleary and unified formatted, including a table prefixes.

E.g.:
We have:

SELECT [SalesRegionId], [SalesRegionName]
FROM dim.[SalesRegion]
WHERE [SalesRegionId] BETWEEN 1 AND 7

and we want:

SELECT
        [sr].[SalesRegionId]
       ,[sr].[SalesRegionName]
FROM
       dim.[SalesRegion] sr
WHERE
      [sr].[SalesRegionId] BETWEEN 1 AND 7

Is there a way how to automate the process?
Thanks in advance.


答:
If you want to use regular expression patterns you need to use a regex function in the CHECK constraint. This will work:

```<code>create table t23 (

PLZ VARCHAR(5) NOT NULL
, CONSTRAINT TC_PLZ CHECK (regexp_LIKE(plz, '^[0-9]{5}$'))
);
</code>```

Although there's no need for regex; here's an alternative implementation:

```<code>create table t42 (

PLZ NUMBER(5,0) NOT NULL
, CONSTRAINT T42_PLZ CHECK (length(plz)=5)
);
</code>```

It's good practice to store numeric values using the correct datatype.

Check out this LiveSQL demo.

As @MT0 points out, the numeric implementation is not correct if a valid value can start with a leading zero. My purist data modeller persona states that values which must be a fixed number of digits should start at 10000 (for five digit values). However, I must admit I know of one system that did permit leading zeroes in a "numeric" field; they compounded this by allowing variable level values, which meant code 0300 identified something different from 00300. What larks!

Title: Oracle SQL Developer Postal Code

Body:
I am having a problem with a check constraint in Oracle SQL Developer with Oracle 11g Express Edition.

I want to check if my postal code which is stored as CHAR just contains numbers and no other signs.

Tried various possibilities but nothing worked...

PLZ VARCHAR(5) NOT NULL

ADD CONSTRAINT TC_PLZ CHECK (PLZ LIKE '[0-9][0-9][0-9][0-9][0-9]')

Thanks and best regards,

Michael

Body:
If you want to use regular expression patterns you need to use a regex function in the CHECK constraint. This will work:

create table t23 (

PLZ VARCHAR(5) NOT NULL
, CONSTRAINT TC_PLZ CHECK (regexp_LIKE(plz, '^[0-9]{5}$'))
);

Although there's no need for regex; here's an alternative implementation:

create table t42 (

PLZ NUMBER(5,0) NOT NULL
, CONSTRAINT T42_PLZ CHECK (length(plz)=5)
);

It's good practice to store numeric values using the correct datatype.

Check out this LiveSQL demo.

As @MT0 points out, the numeric implementation is not correct if a valid value can start with a leading zero. My purist data modeller persona states that values which must be a fixed number of digits should start at 10000 (for five digit values). However, I must admit I know of one system that did permit leading zeroes in a "numeric" field; they compounded this by allowing variable level values, which meant code 0300 identified something different from 00300. What larks!


问:
UICollectionView - resizing cells on device rotate - Swift
I've created a UICollectionView, so that I can arrange views into neat columns. I'd like there to be a single column on devices > 500 pixels wide.

In order to achieve this, I created this function:

```<code>func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    let size = collectionView.frame.width
    if (size > 500) {
        return CGSize(width: (size/2) - 8, height: (size/2) - 8)
    }
    return CGSize(width: size, height: size)
}
</code>```

This works as expected on first load, however when I rotate the device, the calculation doesn't always happen again, and the views don't always redraw as expected. Here's my code for when the device is rotated:

```<code>override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
    collectionView.collectionViewLayout.invalidateLayout()
    self.view.setNeedsDisplay()
}
</code>```

I'm assuming I've forgotten to redraw something, but I'm not sure what. Any ideas are very gratefully recieved!

答:
traitCollectionDidChange method might be used as well instead of viewWillLayoutSubviews:

```<code>override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(previousTraitCollection)

    guard let previousTraitCollection = previousTraitCollection, traitCollection.verticalSizeClass != previousTraitCollection.verticalSizeClass ||
        traitCollection.horizontalSizeClass != previousTraitCollection.horizontalSizeClass else {
            return
    }

    if traitCollection.horizontalSizeClass == .regular && traitCollection.verticalSizeClass == .regular {
        // iPad portrait and landscape
        // do something here...
    }
    if traitCollection.horizontalSizeClass == .compact && traitCollection.verticalSizeClass == .regular {
        // iPhone portrait
        // do something here...
    }
    if traitCollection.horizontalSizeClass == .regular && traitCollection.verticalSizeClass == .compact {
        // iPhone landscape
        // do something here...
    }
    collectionView?.collectionViewLayout.invalidateLayout()
    collectionView?.reloadData()
}
</code>```

Body:
I've created a UICollectionView, so that I can arrange views into neat columns. I'd like there to be a single column on devices > 500 pixels wide.

In order to achieve this, I created this function:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    let size = collectionView.frame.width
    if (size > 500) {
        return CGSize(width: (size/2) - 8, height: (size/2) - 8)
    }
    return CGSize(width: size, height: size)
}

This works as expected on first load, however when I rotate the device, the calculation doesn't always happen again, and the views don't always redraw as expected. Here's my code for when the device is rotated:

override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
    collectionView.collectionViewLayout.invalidateLayout()
    self.view.setNeedsDisplay()
}

I'm assuming I've forgotten to redraw something, but I'm not sure what. Any ideas are very gratefully recieved!

Body:
traitCollectionDidChange method might be used as well instead of viewWillLayoutSubviews:

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(previousTraitCollection)

    guard let previousTraitCollection = previousTraitCollection, traitCollection.verticalSizeClass != previousTraitCollection.verticalSizeClass ||
        traitCollection.horizontalSizeClass != previousTraitCollection.horizontalSizeClass else {
            return
    }

    if traitCollection.horizontalSizeClass == .regular && traitCollection.verticalSizeClass == .regular {
        // iPad portrait and landscape
        // do something here...
    }
    if traitCollection.horizontalSizeClass == .compact && traitCollection.verticalSizeClass == .regular {
        // iPhone portrait
        // do something here...
    }
    if traitCollection.horizontalSizeClass == .regular && traitCollection.verticalSizeClass == .compact {
        // iPhone landscape
        // do something here...
    }
    collectionView?.collectionViewLayout.invalidateLayout()
    collectionView?.reloadData()
}


问:
How to compare through complete JSON and bind it to another JSON

I have a JSON which looks like this:-

```<code>{
    "property" : value,
    "property" : value,
    "subProperty" : {
        "subProperty1" : {
            "subProperty1a" : {
                "property" : value,
                "property" : value
            },
            "subProperty1b" : {
                "property" : ["1", "2"],
                "property" : value
            },
            .....
        },
        "subProperty2" : {
            "subProperty2a" : {
                "property" : value,
                "property" : value
            },
            "subProperty2b" : {
                "property" : value,
                "property" : value
            },
            .....
        },
        "subProperty3" : {
            "subProperty3a" : {
                "property" : value,
                "property" : value
            },
            "subProperty3b" : {
                "property" : value,
                "property" : value
            },
            .....
        }
    }
}
</code>```

This JSON can have any number of fields added later on in any position.What I want is when I add new fields, then I want to compare old JSON with new JSON. If any propert is missing, bind that property with new one.

Right now I am using following code to achieve this:-

```<code>    scope.tempObj = {};
    scope.findObjectByLabel = function(obj1, obj2, obj3){
                        for(var i in obj1)
                            {
                                obj3[i] = obj2[i];
                                if(obj2[i] == undefined)
                                {
                                    obj3[i] = obj1[i];
                                }
                                if(typeof(obj1[i]) == 'object')
                                {
                                    scope.findObjectByLabel(obj1[i], obj2[i],obj3[i]);
                                }
                            }
                            return obj3;
                    }

scope.newJSON = scope.findObjectByLabel(scope.newJSON, scope.oldJSON ,scope.tempObj);
</code>```

But the above code can only compare through one level. Can any one suggest me any improvement on the above code so that it can compare through entire JSON.

答:
Had the same problem , lodash came to the rescue.

https://lodash.com/docs/4.17.4

Look at merge & and deep equal (which is called just equal).

Usage example:

```<code>  //**********//
 // _.merge //
//**********//
 var object = {
  'a': [{ 'b': 2 }, { 'd': 4 }]
};

var other = {
  'a': [{ 'c': 3 }, { 'e': 5 }]
};

_.merge(object, other);
// => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }

  //**********//
 // _.equal //
//**********//
var object = { 'a': 1 };
var other = { 'a': 1 };

_.isEqual(object, other);
// => true

object === other;
// => false
</code>```

Body:
I have a JSON which looks like this:-

{
    "property" : value,
    "property" : value,
    "subProperty" : {
        "subProperty1" : {
            "subProperty1a" : {
                "property" : value,
                "property" : value
            },
            "subProperty1b" : {
                "property" : ["1", "2"],
                "property" : value
            },
            .....
        },
        "subProperty2" : {
            "subProperty2a" : {
                "property" : value,
                "property" : value
            },
            "subProperty2b" : {
                "property" : value,
                "property" : value
            },
            .....
        },
        "subProperty3" : {
            "subProperty3a" : {
                "property" : value,
                "property" : value
            },
            "subProperty3b" : {
                "property" : value,
                "property" : value
            },
            .....
        }
    }
}

This JSON can have any number of fields added later on in any position.What I want is when I add new fields, then I want to compare old JSON with new JSON. If any propert is missing, bind that property with new one.

Right now I am using following code to achieve this:-

    scope.tempObj = {};
    scope.findObjectByLabel = function(obj1, obj2, obj3){
                        for(var i in obj1)
                            {
                                obj3[i] = obj2[i];
                                if(obj2[i] == undefined)
                                {
                                    obj3[i] = obj1[i];
                                }
                                if(typeof(obj1[i]) == 'object')
                                {
                                    scope.findObjectByLabel(obj1[i], obj2[i],obj3[i]);
                                }
                            }
                            return obj3;
                    }

scope.newJSON = scope.findObjectByLabel(scope.newJSON, scope.oldJSON ,scope.tempObj);

But the above code can only compare through one level. Can any one suggest me any improvement on the above code so that it can compare through entire JSON.

Body:
Had the same problem , lodash came to the rescue.

https://lodash.com/docs/4.17.4

Look at merge & and deep equal (which is called just equal).

Usage example:

  //**********//
 // _.merge //
//**********//
 var object = {
  'a': [{ 'b': 2 }, { 'd': 4 }]
};

var other = {
  'a': [{ 'c': 3 }, { 'e': 5 }]
};

_.merge(object, other);
// => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }

  //**********//
 // _.equal //
//**********//
var object = { 'a': 1 };
var other = { 'a': 1 };

_.isEqual(object, other);
// => true

object === other;
// => false


问:
Maximum Number of Touch Inputs on Android 2.2+
I know I ran across a specific mention of a maximum number of touch inputs that are theoretically recognized by Android (hardware limits not-withstanding), but have Googled and Googled with no tangible results.

Can anyone point me to an official document/spec/blog/something listing touch capabilities (max inputs specifically) of various flavors of Android (Froyo, Gingerbread, etc)?

Thanks for the help,

Paul

答:
Digging through the source, and I think I've come up with a definitive answer.

In the MotionEvent.java class released with Froyo, the number of pointers supported seems to be hard-coded in as 5.  See static value declared on line 212 (with it's associated comment) and how this value is used in object instantiation on line 251.

Incidentally, this restriction appears to be lifted in the Gingerbread source, as the have moved from a pointer array with a defined size of 5, to an array that is defined by a parameter passed into the object constructor, with the MINIMUM size of the pointer array being 5.  See the static value declaration on line 309 (again, with it's associated comment), and the constructor and obtain() methods on lines 352 and 358 respectively.


问:
R dplyr - select values from one column based on position of a specific value in another column
I am working with gait-cycle data. I have 8 events marked for each id and gait trial. The values "LFCH" and "RFCH" occurs twice in each trial, as these represent the beginning and the end of the gait cycles from left and right leg.

Sample Data Frame:

```<code>df <- data.frame(ID = rep(1:5, each = 16),
                 Gait_nr = rep(1:2, each = 8, times=5),
                 Frame = rep(c(1,5,7,9,10,15,22,25), times = 10),
                 Marks = rep(c("LFCH", "LHL", "RFCH", "LTO", "RHL", "LFCH", "RTO", "RFCH"), times =10)

head(df,8)
  ID Gait_nr Frame Marks
1  1       1     1  LFCH
2  1       1     5   LHL
3  1       1     7  RFCH
4  1       1     9   LTO
5  1       1    10   RHL
6  1       1    15  LFCH
7  1       1    22   RTO
8  1       1    25  RFCH
</code>```

I wold like to create something like

```<code>Total_gait_left = Frame[The last time Marks == "LFCH"] - Frame[The first time Marks == "LFCH"]
</code>```

My current code solves the problem, but depends on the position of the Frame values rather than actual values in Marks. Any individual not following the normal gait pattern will have wrong values produced by the code.

```<code>library(tidyverse)
l <- df %>% group_by(ID, Gait_nr) %>% filter(grepl("L.+", Marks)) %>%
  summarize(Total_gait = Frame[4] - Frame[1],
            Side = "left")

r <- df %>% group_by(ID, Gait_nr) %>% filter(grepl("R.+", Marks)) %>%
  summarize(Total_gait = Frame[4] - Frame[1],
            Side = "right")

val <- union(l,r, by=c("ID", "Gait_nr", "Side")) %>% arrange(ID, Gait_nr, Side)
</code>```

Can you help me make my code more stable by helping me change e.g. Frame[4] to something like Frame[Marks=="LFCH" the last time ]?

答:
If both LFCH and RFCH happen exactly twice, you can filter and then use diff in summarize:

```<code>df %>%
    group_by(ID, Gait_nr) %>%
    summarise(
        left = diff(Frame[Marks == 'LFCH']),
        right = diff(Frame[Marks == 'RFCH'])
    )

# A tibble: 10 x 4
# Groups:   ID [?]
#      ID Gait_nr  left right
#   <int>   <int> <dbl> <dbl>
# 1     1       1    14    18
# 2     1       2    14    18
# 3     2       1    14    18
# 4     2       2    14    18
# 5     3       1    14    18
# 6     3       2    14    18
# 7     4       1    14    18
# 8     4       2    14    18
# 9     5       1    14    18
#10     5       2    14    18
</code>```

Body:
I am working with gait-cycle data. I have 8 events marked for each id and gait trial. The values "LFCH" and "RFCH" occurs twice in each trial, as these represent the beginning and the end of the gait cycles from left and right leg.

Sample Data Frame:

df <- data.frame(ID = rep(1:5, each = 16),
                 Gait_nr = rep(1:2, each = 8, times=5),
                 Frame = rep(c(1,5,7,9,10,15,22,25), times = 10),
                 Marks = rep(c("LFCH", "LHL", "RFCH", "LTO", "RHL", "LFCH", "RTO", "RFCH"), times =10)

head(df,8)
  ID Gait_nr Frame Marks
1  1       1     1  LFCH
2  1       1     5   LHL
3  1       1     7  RFCH
4  1       1     9   LTO
5  1       1    10   RHL
6  1       1    15  LFCH
7  1       1    22   RTO
8  1       1    25  RFCH

I wold like to create something like

Total_gait_left = Frame[The last time Marks == "LFCH"] - Frame[The first time Marks == "LFCH"]

My current code solves the problem, but depends on the position of the Frame values rather than actual values in Marks. Any individual not following the normal gait pattern will have wrong values produced by the code.

library(tidyverse)
l <- df %>% group_by(ID, Gait_nr) %>% filter(grepl("L.+", Marks)) %>%
  summarize(Total_gait = Frame[4] - Frame[1],
            Side = "left")

r <- df %>% group_by(ID, Gait_nr) %>% filter(grepl("R.+", Marks)) %>%
  summarize(Total_gait = Frame[4] - Frame[1],
            Side = "right")

val <- union(l,r, by=c("ID", "Gait_nr", "Side")) %>% arrange(ID, Gait_nr, Side)

Can you help me make my code more stable by helping me change e.g. Frame[4] to something like Frame[Marks=="LFCH" the last time ]?

Body:
If both LFCH and RFCH happen exactly twice, you can filter and then use diff in summarize:

df %>%
    group_by(ID, Gait_nr) %>%
    summarise(
        left = diff(Frame[Marks == 'LFCH']),
        right = diff(Frame[Marks == 'RFCH'])
    )

# A tibble: 10 x 4
# Groups:   ID [?]
#      ID Gait_nr  left right
#   <int>   <int> <dbl> <dbl>
# 1     1       1    14    18
# 2     1       2    14    18
# 3     2       1    14    18
# 4     2       2    14    18
# 5     3       1    14    18
# 6     3       2    14    18
# 7     4       1    14    18
# 8     4       2    14    18
# 9     5       1    14    18
#10     5       2    14    18


问:
Extract elements respectively from text
I have such a following text:

```<code>'- `Popen.``terminate`()\n\n  Stop the child. On Posix OSs the method sends SIGTERM to the child. On Windows the Win32 API function `TerminateProcess()` is called to stop the child.\n\n\n- `Popen.``kill`()\n\n  Kills the child. On Posix OSs the function sends SIGKILL to the child. On Windows;...
</code>```

I try to extract a list from the text

```<code>In [46]: pattern = re.compile(r'-\s(.+)\n\n')
In [49]: matches = pattern.findall(content)
In [50]: matches
Out[50]:
['`Popen.``terminate`()',
 '`Popen.``kill`()',
 '`Popen.``args`',
 '`Popen.``stdin`',
 '`Popen.``stdout`']
</code>```

The result I desire is

```<code>['Popen.terminate()',
 'Popen.kill()',
 'Popen.args',
 'Popen.stdin',
 'Popen.stdout']
</code>```

I alter the reges with two groups to capture qualifed parts

```<code>In [55]: pattern2 = re.compile(r'- `(\w+).``(\w+.*)`')
In [64]: matches = pattern2.findall(content)
In [65]: matches
Out[65]:
[('Popen', 'terminate'),
 ('Popen', 'kill'),
 ('Popen', 'args'),
 ('Popen', 'stdin'),
 ('Popen', 'stdout')]
</code>```

It's still not my desired result.

How to solve the problem?

答:
Code

See regex in use here

```<code>-\s`([^`]*)``([^`]*)`((?:\(\))?)\n\n
</code>```

Usage

See code in use here

```<code>import re

r = re.compile(r"-\s`([^`]*)``([^`]*)`((?:\(\))?)\n\n")

s = ("'- `Popen.``terminate`()\n\n"
    "  Stop the child. On Posix OSs the method sends SIGTERM to the child. On Windows the Win32 API function `TerminateProcess()` is called to stop the child.\n\n\n"
    "- `Popen.``kill`()\n\n"
    "  Kills the child. On Posix OSs the function sends SIGKILL to the child. On Windows;...\n")

for m in re.finditer(r, s):
    print m.group(1) + m.group(2) + m.group(3)
</code>```

Results

Input

```<code>'- `Popen.``terminate`()\n\n  Stop the child. On Posix OSs the method sends SIGTERM to the child. On Windows the Win32 API function `TerminateProcess()` is called to stop the child.\n\n\n- `Popen.``kill`()\n\n  Kills the child. On Posix OSs the function sends SIGKILL to the child. On Windows;...
</code>```

Output

Note: The output below doesn't match the OP's expected output because the OP did not post the full string, but only a partial string.

```<code>Popen.terminate()
Popen.kill()
</code>```

Explanation

- Match the hyphen character - literally

\s Match a whitespace character

` Match a grave accent character literally

([^`]*)</code> Capture any number of any characters not present in the set (any character except the grave accent character <code>`) into capture group 1

`` Match two grave accent characters literally

([^`]*)</code> Capture any number of any characters not present in the set (any character except the grave accent character <code>`) into capture group 2

` Match a grave accent character literally

((?:\(\))?) Capture the following into capture group 3

(?:\(\))? Match the following zero or one time

\(\) Match an opening and closing parenthesis literally ()

\n\n Match two newline characters

Title: Extract elements respectively from text

Body:
I have such a following text:

'- `Popen.``terminate`()\n\n  Stop the child. On Posix OSs the method sends SIGTERM to the child. On Windows the Win32 API function `TerminateProcess()` is called to stop the child.\n\n\n- `Popen.``kill`()\n\n  Kills the child. On Posix OSs the function sends SIGKILL to the child. On Windows;...

I try to extract a list from the text

In [46]: pattern = re.compile(r'-\s(.+)\n\n')
In [49]: matches = pattern.findall(content)
In [50]: matches
Out[50]:
['`Popen.``terminate`()',
 '`Popen.``kill`()',
 '`Popen.``args`',
 '`Popen.``stdin`',
 '`Popen.``stdout`']

The result I desire is

['Popen.terminate()',
 'Popen.kill()',
 'Popen.args',
 'Popen.stdin',
 'Popen.stdout']

I alter the reges with two groups to capture qualifed parts

In [55]: pattern2 = re.compile(r'- `(\w+).``(\w+.*)`')
In [64]: matches = pattern2.findall(content)
In [65]: matches
Out[65]:
[('Popen', 'terminate'),
 ('Popen', 'kill'),
 ('Popen', 'args'),
 ('Popen', 'stdin'),
 ('Popen', 'stdout')]

It's still not my desired result.

How to solve the problem?

Body:
Code

See regex in use here

-\s`([^`]*)``([^`]*)`((?:\(\))?)\n\n

Usage

See code in use here

import re

r = re.compile(r"-\s`([^`]*)``([^`]*)`((?:\(\))?)\n\n")

s = ("'- `Popen.``terminate`()\n\n"
    "  Stop the child. On Posix OSs the method sends SIGTERM to the child. On Windows the Win32 API function `TerminateProcess()` is called to stop the child.\n\n\n"
    "- `Popen.``kill`()\n\n"
    "  Kills the child. On Posix OSs the function sends SIGKILL to the child. On Windows;...\n")

for m in re.finditer(r, s):
    print m.group(1) + m.group(2) + m.group(3)

Results

Input

'- `Popen.``terminate`()\n\n  Stop the child. On Posix OSs the method sends SIGTERM to the child. On Windows the Win32 API function `TerminateProcess()` is called to stop the child.\n\n\n- `Popen.``kill`()\n\n  Kills the child. On Posix OSs the function sends SIGKILL to the child. On Windows;...

Output

Note: The output below doesn't match the OP's expected output because the OP did not post the full string, but only a partial string.

Popen.terminate()
Popen.kill()

Explanation

- Match the hyphen character - literally

\s Match a whitespace character

` Match a grave accent character literally

([^`]*)</code> Capture any number of any characters not present in the set (any character except the grave accent character <code>`) into capture group 1

`` Match two grave accent characters literally

([^`]*)</code> Capture any number of any characters not present in the set (any character except the grave accent character <code>`) into capture group 2

` Match a grave accent character literally

((?:\(\))?) Capture the following into capture group 3

(?:\(\))? Match the following zero or one time

\(\) Match an opening and closing parenthesis literally ()

\n\n Match two newline characters


问:
Not able to click on first element in the table through Java selenium
I have to click on first link in the table.
Not able to click the link, it's id and xpath is changing when a new record is created as follows :

```<code>Action  Exception Number
Edit | Del  EX-0000529

Edit | Del  EX-0000528

Edit | Del  EX-0000527

Edit | Del  EX-0000526

Edit | Del  EX-0000525
</code>```

HTML is as follows :

```<code> <td class="x-grid3-col x-grid3-cell x-grid3-td-NAME " tabindex="0"
 style="width:251px;">
 <div id="a3h290000001fC6_NAME" class="x-grid3-cell-inner x-grid3-col-NAME">
 <a href="/a3h290000001fC6">
 <span>EX-0000529</span>
 </a>
 </div>
 </td>
 <td class="x-grid3-col x-grid3-cell x-grid3-td-NAME " tabindex="0"
  style="width:251px;">
  <div id="a3h290000001f9v_NAME" class="x-grid3-cell-inner x-grid3-col-
  NAME">
  <a href="/a3h290000001f9v">
  <span>EX-0000528</span>
  </a>
  </div>
  </td>
</code>```

答:
To click on first link in the table i.e. EX-0000529 you can use the following line of code :

```<code>driver.findElement(By.xpath("//td[@class='x-grid3-col x-grid3-cell x-grid3-td-NAME']//following::span[1]")).click();
</code>```

Body:
I have to click on first link in the table.
Not able to click the link, it's id and xpath is changing when a new record is created as follows :

Action  Exception Number
Edit | Del  EX-0000529

Edit | Del  EX-0000528

Edit | Del  EX-0000527

Edit | Del  EX-0000526

Edit | Del  EX-0000525

HTML is as follows :

 EX-0000529

  EX-0000528

Body:
To click on first link in the table i.e. EX-0000529 you can use the following line of code :

driver.findElement(By.xpath("//td[@class='x-grid3-col x-grid3-cell x-grid3-td-NAME']//following::span[1]")).click();


问:
Selenium: click on

I have the following html code and I want to click on the second option "Plan b".

```<code><ul class="clearfix all">
<li data-content="a" data-tab-target="tab1" class="active"><span>Plan a</span</li>
<li data-content="b" data-tab-target="tab2" class=""><span>Plan b</span></li>
<li data-content="c" data-tab-target="tab3" class=""><span>Plan c</span></li>/ul>
</code>```

I tried to do somthing like this:

1.

```<code>@FindBy(css = "li:nth-child(2)")
WebElement sparpreis;
sparpreis.click();
</code>```

2.

```<code>@FindBy(xpath = "//*[@class='clearfix all']/ul/li[2]")
WebElement sparpreis;
sparpreis.click();
</code>```

My error messages:

org.openqa.selenium.ElementNotVisibleException: element not visible

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@class='clearfix all']/ul/li[2]"}

Perhaphs I should activate the second "class"?

答:
The /ul is not needed, try the following:</p>

```<code>@FindBy(xpath = "//ul[contains(@class, 'clearfix all')]/li[2]")
</code>```

Title: Selenium: click on <li>

Body:
I have the following html code and I want to click on the second option "Plan b".

Plan a</span

Plan b

Plan c
/ul>

I tried to do somthing like this:

1.

@FindBy(css = "li:nth-child(2)")
WebElement sparpreis;
sparpreis.click();

2.

@FindBy(xpath = "//*[@class='clearfix all']/ul/li[2]")
WebElement sparpreis;
sparpreis.click();

My error messages:

org.openqa.selenium.ElementNotVisibleException: element not visible

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@class='clearfix all']/ul/li[2]"}

Perhaphs I should activate the second "class"?

Body:
The /ul is not needed, try the following:

@FindBy(xpath = "//ul[contains(@class, 'clearfix all')]/li[2]")


问:
Returning SetConsoleTextAttribute colour value from function in c
Currently im trying to call a function to change the color the text background using the windows.h functions to do so. I have done it before but not from another function. Is the problem that the function needs to return the color value somehow or there is just something wrong.
The function was called from another function if that changes anything.

Code Together:

```<code>void setColour(HANDLE* hConsole, int ChangeColour, int Red, int Green, int Blue, int Colour) {
    CONSOLE_SCREEN_BUFFER_INFOEX info;
    info.cbSize = sizeof(info);
    GetConsoleScreenBufferInfoEx(hConsole, &info);
    info.ColorTable[ChangeColour] = RGB(Red, Green, Blue);
    SetConsoleTextAttribute(hConsole, Colour);
}

void mainMenu(WindowProp* Dimensions, HANDLE* hConsole) {
    getWindowSize(Dimensions);
    clearScreen();
    setColour(hConsole, 3, 120, 120, 236, 48);
    printf("Set");
    int DisplayRowCount, DisplayColumnCount;
    for (DisplayRowCount = 0; DisplayRowCount <= Dimensions->Y-1; DisplayRowCount++) {
        for (DisplayColumnCount = 0; DisplayColumnCount <= Dimensions->X-1; DisplayColumnCount++) {
            printf(" ");
        }
    }
}
</code>```

mainMenu called from main:

```<code>mainMenu(&WindowP, hConsole);
</code>```

答:
Ok so I got it fixed. I first decided to declare the HANDLE value in the mainMenu() function and remove the HANDLE pointer.

Secondly, the setColour() function's GetConsoleScreenBufferInfoEx() did get called before changing the color values but wasn't called after modifying the color values thus i needed to call GetConsoleScreenBufferInfoEx() a second time to get the new color values to use.

Fixed Code:

```<code>void setColour(HANDLE* hConsole, int ChangeColour, int Red, int Green, int Blue, int Colour) {
    CONSOLE_SCREEN_BUFFER_INFOEX info;
    info.cbSize = sizeof(info);
    GetConsoleScreenBufferInfoEx(hConsole, &info);
    info.ColorTable[ChangeColour] = RGB(Red, Green, Blue);
    GetConsoleScreenBufferInfoEx(hConsole, &info);
    SetConsoleTextAttribute(hConsole, Colour);
}

void mainMenu(WindowProp* Dimensions) {
    getWindowSize(Dimensions);
    clearScreen();
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    setColour(hConsole, 3, 120, 120, 236, 48);
    int DisplayRowCount, DisplayColumnCount;
    for (DisplayRowCount = 0; DisplayRowCount <= Dimensions->Y-1; DisplayRowCount++) {
        for (DisplayColumnCount = 0; DisplayColumnCount <= Dimensions->X-1; DisplayColumnCount++) {
            printf(" ");
        }
    }
}
</code>```

Body:
Currently im trying to call a function to change the color the text background using the windows.h functions to do so. I have done it before but not from another function. Is the problem that the function needs to return the color value somehow or there is just something wrong.
The function was called from another function if that changes anything.

Code Together:

void setColour(HANDLE* hConsole, int ChangeColour, int Red, int Green, int Blue, int Colour) {
    CONSOLE_SCREEN_BUFFER_INFOEX info;
    info.cbSize = sizeof(info);
    GetConsoleScreenBufferInfoEx(hConsole, &info);
    info.ColorTable[ChangeColour] = RGB(Red, Green, Blue);
    SetConsoleTextAttribute(hConsole, Colour);
}

void mainMenu(WindowProp* Dimensions, HANDLE* hConsole) {
    getWindowSize(Dimensions);
    clearScreen();
    setColour(hConsole, 3, 120, 120, 236, 48);
    printf("Set");
    int DisplayRowCount, DisplayColumnCount;
    for (DisplayRowCount = 0; DisplayRowCount <= Dimensions->Y-1; DisplayRowCount++) {
        for (DisplayColumnCount = 0; DisplayColumnCount <= Dimensions->X-1; DisplayColumnCount++) {
            printf(" ");
        }
    }
}

mainMenu called from main:

mainMenu(&WindowP, hConsole);

Body:
Ok so I got it fixed. I first decided to declare the HANDLE value in the mainMenu() function and remove the HANDLE pointer.

Secondly, the setColour() function's GetConsoleScreenBufferInfoEx() did get called before changing the color values but wasn't called after modifying the color values thus i needed to call GetConsoleScreenBufferInfoEx() a second time to get the new color values to use.

Fixed Code:

void setColour(HANDLE* hConsole, int ChangeColour, int Red, int Green, int Blue, int Colour) {
    CONSOLE_SCREEN_BUFFER_INFOEX info;
    info.cbSize = sizeof(info);
    GetConsoleScreenBufferInfoEx(hConsole, &info);
    info.ColorTable[ChangeColour] = RGB(Red, Green, Blue);
    GetConsoleScreenBufferInfoEx(hConsole, &info);
    SetConsoleTextAttribute(hConsole, Colour);
}

void mainMenu(WindowProp* Dimensions) {
    getWindowSize(Dimensions);
    clearScreen();
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    setColour(hConsole, 3, 120, 120, 236, 48);
    int DisplayRowCount, DisplayColumnCount;
    for (DisplayRowCount = 0; DisplayRowCount <= Dimensions->Y-1; DisplayRowCount++) {
        for (DisplayColumnCount = 0; DisplayColumnCount <= Dimensions->X-1; DisplayColumnCount++) {
            printf(" ");
        }
    }
}


问:
svn diff with vim, but with the proper filetype
This blog post gives a simple way to use Vim with svn diff. Unfortunately, Vim doesn't understand the left-hand-side filetype so there's no syntax highlighting. What's the simplest/best way of solving this?

答: Using GVim 8.0 as the Diff Viewer for TortoiseSVN 1.9.7 on Windows 10, I found that the GVim recognises the php file extension correctly and displayed the syntax highlighting perfectly.</p>


问:
Hover over svg does not work when mouse is over text within the svg item
I wanted to apply a simple hover over both the shape and text inside it. It's supposed to change the color (in this case fill), when pointer is over either the shape or the text. I thought that if the text is kind of inside of the svg element, the hover will be applied to it too. Except it isn't.

I'm not good with svg, in fact, this is the first time I'm working with them. Tried to find answers here and in google, but nothing applies to my problem. Please help.

```<code><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 900 170">
      <path class="a" fill={funnels[funnel].bgColor} d="M378.24,59.8l33.39,88.73a11.82,11.82,0,0,0,11.07,7.66h54.6a11.82,11.82,0,0,0,11.07-7.66L521.76,59.8a11.82,11.82,0,0,0-11.07-16H389.31A11.82,11.82,0,0,0,378.24,59.8Z"></path>
      <text x="50%" y="60%" dominant-baseline="middle" text-anchor="middle" font-family="Lato" font-size="2rem" fill="#f2f2f2"> Hello </text>
    </svg>

svg {
      filter: drop-shadow(0px 0px 10px rgba(0,0,0,0.2));

      .a {
        transition: all ease-in 0.5s;

        &:hover {
          fill: darken(red, 10%);
          cursor: pointer;
        }
      }
    }
</code>```

Here's my fiddle: https://jsfiddle.net/Madzik/bkbgf1os/

答:
Apply hover effect to svg not .a.

```<code>svg {
  filter: drop-shadow(0px 0px 10px rgba(0,0,0,0.2));

  .a {
    transition: all ease-in 0.5s;
  }

  &:hover {
    fill: darken(red, 10%);
    cursor: pointer;
  }
}
</code>```

svg {
  filter: drop-shadow(0px 0px 10px rgba(0,0,0,0.2));
}

svg .a {
  transition: all ease-in 0.5s;
}

svg:hover {
  fill: green;
  cursor: pointer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 900 170">
  <path class="a" fill={funnels[funnel].bgColor} d="M378.24,59.8l33.39,88.73a11.82,11.82,0,0,0,11.07,7.66h54.6a11.82,11.82,0,0,0,11.07-7.66L521.76,59.8a11.82,11.82,0,0,0-11.07-16H389.31A11.82,11.82,0,0,0,378.24,59.8Z"></path>
  <text x="50%" y="60%" dominant-baseline="middle" text-anchor="middle" font-family="Lato" font-size="2rem" fill="#f2f2f2"> Hello </text>
</svg></code>```

Body:
I wanted to apply a simple hover over both the shape and text inside it. It's supposed to change the color (in this case fill), when pointer is over either the shape or the text. I thought that if the text is kind of inside of the svg element, the hover will be applied to it too. Except it isn't.

I'm not good with svg, in fact, this is the first time I'm working with them. Tried to find answers here and in google, but nothing applies to my problem. Please help.

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 900 170">
      <path class="a" fill={funnels[funnel].bgColor} d="M378.24,59.8l33.39,88.73a11.82,11.82,0,0,0,11.07,7.66h54.6a11.82,11.82,0,0,0,11.07-7.66L521.76,59.8a11.82,11.82,0,0,0-11.07-16H389.31A11.82,11.82,0,0,0,378.24,59.8Z"></path>
      <text x="50%" y="60%" dominant-baseline="middle" text-anchor="middle" font-family="Lato" font-size="2rem" fill="#f2f2f2"> Hello </text>
    </svg>

svg {
      filter: drop-shadow(0px 0px 10px rgba(0,0,0,0.2));

      .a {
        transition: all ease-in 0.5s;

        &:hover {
          fill: darken(red, 10%);
          cursor: pointer;
        }
      }
    }

Here's my fiddle: https://jsfiddle.net/Madzik/bkbgf1os/

Body:
Apply hover effect to svg not .a.

svg {
  filter: drop-shadow(0px 0px 10px rgba(0,0,0,0.2));

  .a {
    transition: all ease-in 0.5s;
  }

  &:hover {
    fill: darken(red, 10%);
    cursor: pointer;
  }
}

svg {
  filter: drop-shadow(0px 0px 10px rgba(0,0,0,0.2));
}

svg .a {
  transition: all ease-in 0.5s;
}

svg:hover {
  fill: green;
  cursor: pointer;
}

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 900 170">
  <path class="a" fill={funnels[funnel].bgColor} d="M378.24,59.8l33.39,88.73a11.82,11.82,0,0,0,11.07,7.66h54.6a11.82,11.82,0,0,0,11.07-7.66L521.76,59.8a11.82,11.82,0,0,0-11.07-16H389.31A11.82,11.82,0,0,0,378.24,59.8Z"></path>
  <text x="50%" y="60%" dominant-baseline="middle" text-anchor="middle" font-family="Lato" font-size="2rem" fill="#f2f2f2"> Hello </text>
</svg>


问:
jQuery not rebinding event to handler after unbinding
I have the following jQuery code:

```<code>$(document).on('focusout', '#element', function(e){
     alert('test');
});

$(document).on('click', '#element_b', function(e){
     $(document).off('focusout','#element');
     /* do other stuff */
     $(document).on('focusout','#element',function(){});
});
</code>```

On clicking on #element_b, the event bound to #element is supposed to get off and then back on but for some reason after it goes off, it doesn't return back on. How to get it back on?

答:
In order to be able to re-bind a handler, the handler function must be available for reference at the point it would be re-bound. To achieve that, just define the handler function with a name:

```<code>function focusOutHandler(e) {
  alert("test");
}

$(document).on("focusout", "#element", focusOutHandler);
</code>```

Then you can also reference the function in your "click" handler:

```<code>$(document).on('click', '#element_b', function(e){
     $(document).off('focusout','#element');
     /* do other stuff */
     $(document).on('focusout', '#element', focusOutHandler);
});
</code>```

Now, that said, that operation really doesn't make a lot of sense in the context of your question. While the "click" handler code is running, the "focusout" code will not run anyway. Thus, removing the handler at the start of the code and then adding it back at the end won't have any noticeable effect.

Body:
I have the following jQuery code:

$(document).on('focusout', '#element', function(e){
     alert('test');
});

$(document).on('click', '#element_b', function(e){
     $(document).off('focusout','#element');
     /* do other stuff */
     $(document).on('focusout','#element',function(){});
});

On clicking on #element_b, the event bound to #element is supposed to get off and then back on but for some reason after it goes off, it doesn't return back on. How to get it back on?

Body:
In order to be able to re-bind a handler, the handler function must be available for reference at the point it would be re-bound. To achieve that, just define the handler function with a name:

function focusOutHandler(e) {
  alert("test");
}

$(document).on("focusout", "#element", focusOutHandler);

Then you can also reference the function in your "click" handler:

$(document).on('click', '#element_b', function(e){
     $(document).off('focusout','#element');
     /* do other stuff */
     $(document).on('focusout', '#element', focusOutHandler);
});

Now, that said, that operation really doesn't make a lot of sense in the context of your question. While the "click" handler code is running, the "focusout" code will not run anyway. Thus, removing the handler at the start of the code and then adding it back at the end won't have any noticeable effect.


问:
Solution for backup webserver by ubuntu and mysql?
We had a webserver on Ubuntu14.04 server that was implemeted by LAMP (Linux, Apache, MySQL, PHP) and phpMyAdmin to manage database.

Now we will buy one more server for backup our webserver. However, I don't know the solution for this work. I heard about some solution like loadbalancing, cron, mysqldumb, Master Slave Replication... but I don't know which solution suitable with us and how to implement it.

I need a solution for this problem when the web server 1 is disrupted, our system will redirect to web server 2 (server backup) and work well without missing data.

Any ideas??

答:
Master/slave :

Master/slave if your stuff (CMS, etc...) can consider read-only mode of slave to be used.
It's better if your stuff handle master/slave replication in configuration (= is not trying to send UPDATE or DELETE to a slave server which will give errors)
Slave server can also be use as a SELECT server to help DB handling more request..
You don't need anything else but MySQL and 2 servers to do that. You'll find many help on internet about how to install master/slave.

Master/master :

Problem with master/slave replication is that slave server will be accessible in read-only mode only. Most tools (CMS or whatever) require writing DB even when consulting for whatever reason (Session handling etc..)
Master/master replication is probably the best choice , but you'll need a third party : have a look at MMM and its installation guide.


问:
React Native android camera2 aspect ratio issue
I have created a library (check this for more information) for Android for Android Camera2 functionality in Android all is working good, but in the aspect ratio issue with full screen camera.

Please Check below image how it looks in preview and the real picture (Only preview has the issue not the real picture after capturing)

Captured image horizontal:

Preview image horizontal:

Captured image vertical:

Preview image vertical:

Google sample of Camera2 API have similar issue and resolved here.

But same code not working in my react native library code. May be I am using one code for image and video both and add additional code for video capture.

答:
More often than not, the camera sensor aspect ratio won't match the screen aspect ratio. The result is what you're currently experiencing.

Because of this mismatch in aspect ratios. You can't actually force the preview to be full screen. You have to select "valid" dimensions. So how do you do that?

There's nothing we can do about the sensor's dimensions. The question we have to answer is what should the height of my preview be? (assuming portrait mode)

Here's an example:

Sensor (assume portrait):

width: 50

height: 100

aspect ratio: (width / height) = 0.5

Screen (assume portrait):

width: 400

height: 1000

aspect ratio: (width / height) = 0.4

With the values above, your preview image will be  "stretched out".

Here's how to fix it:

We know the aspect ratio we want: 0.5

width / height = 0.5

We know the width of the screen (portrait): 400

400 / height = 0.5

height = 400 / 0.5 = 800

In order to have no stretching in the x or y direction, the height (assume portrait) needs to be: preview width / desired aspect ratio


问:
Linq to exclude a custom object from one List based on membership of another List (c#)
I have a list (List A) of custom Dynamics CRM objects and then I want to create another list (List B) of the same custom object type which will NOT include any custom object which already exists in List A. The unique instance identifier is a parameter called "emailaddress"

I have tried making the lists and then doing a "remove" (or exclude) on List B - this works but seems to be slow and I would rather try to keep any duplicate out them out at initial list (B) creation-time - i.e. as part of the query used to create List B. Does anyone know if this is possible? (C#)

(Assuming List A has already been instantiated) The psuedo/code would be like

```<code>...
from b in context.CreateQuery("contact")
where (string) b["emailaddress"] !=null
and b["emailaddress"] NOT IN ListA
select new object.....toList()
</code>```

Thanks

答:
I think a left outer join will do the trick...</p>

```<code>var q =
(from b in context.CreateQuery("contact")
join c in ListA on c.emailaddress equals b.emailaddress into bc
from c in bc.DefaultIfEmpty()
select new { whatever your object properties are}).ToList();
</code>```

Body:
I have a list (List A) of custom Dynamics CRM objects and then I want to create another list (List B) of the same custom object type which will NOT include any custom object which already exists in List A. The unique instance identifier is a parameter called "emailaddress"

I have tried making the lists and then doing a "remove" (or exclude) on List B - this works but seems to be slow and I would rather try to keep any duplicate out them out at initial list (B) creation-time - i.e. as part of the query used to create List B. Does anyone know if this is possible? (C#)

(Assuming List A has already been instantiated) The psuedo/code would be like

...
from b in context.CreateQuery("contact")
where (string) b["emailaddress"] !=null
and b["emailaddress"] NOT IN ListA
select new object.....toList()

Thanks

Body:
I think a left outer join will do the trick...

var q =
(from b in context.CreateQuery("contact")
join c in ListA on c.emailaddress equals b.emailaddress into bc
from c in bc.DefaultIfEmpty()
select new { whatever your object properties are}).ToList();


问:
Any good 2d engines with a GUI system?
I'm trying to develop a simple app ( it will resemble something like a powerpoint presentation) that will require some simple GUI controls: button, textbox, slider and listbox.

And i would want to be able to skin the controls.
So i'm looking for an easy to learn 2d engine that will aid me in doing what i want.

Any recommendation for such engine?

It can be in python or .net (xna) preferable or if not c/c++ will be ok i guess.

L.E.: I'm looking for a graphic rendering engine that has specified gui controls available.
For example Irrlicht.

答:
WPF for .NET is a very nice platform to do skinable graphics in.  It fully supports skinning right "out of the box".  As a side-benefit, it will do do 3d rendering with very little extra effort.
Most of the standard GUI controls are there, including buttons, listboxes, textboxes and sliders.  By default they have the standard windows appearance, but skinning is as simple as changing colors around, or specifying an image to use instead.</p>

OwnerDisplayName: daniels

Title: Any good 2d engines with a GUI system?

LastEditorDisplayName: daniels

OwnerDisplayName: Josh

LastEditorDisplayName: Josh


问:
vscode: Open file instead of previewing file from quick open
When I open up the Command Palette (Ctrl or Cmd + P), type in a filename and hit Enter, the file will automatically be opened in Preview mode.

Open File Permanently

What I want is to have an option to open a file permanently from the Command Palette. I am aware of the "workbench.editor.enablePreviewFromQuickOpen" settings, but that will disable Preview mode.

For example, selecting a file in the Command Palette and hitting Ctrl + Enter will open the file as Preview in a new Split view. I am looking for a similar shortcut to open a file permanently.

Edit 1

Correction: I meant the Quick Look mode using Cmd + P / Ctrl + P. The Command Palette is used to run commands, and cannot search or open files.

答: Just press the Right arrow when your file is highlighted.  The Command Palette stays exactly where it is and your file opens (in non-preview) in the background.  You can do this as many times as you like.</p>