问:
Ionic 2 karma test failed 'ion-label' is not a known element
On running npm test i am getting this error on my component ->

```<code>  **Can't bind to 'formGroup' since it isn't a known property of
   'form'.
   ("
  </div>
<form [ERROR ->][formGroup]="loginForm" text-center>
<ion-list>
"): ng:///DynamicTestModule/Login.html@18:6
'ion-label' is not a known element:
1. If 'ion-label' is an Angular component, then verify that it is part
of this module.
2. If 'ion-label' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA'
to the '@NgModule.schemas' of this component to suppress this message.
 ("
<ion-item>
    [ERROR ->]<ion-label floating>Email</ion-label>
    <ion-input type="email" formControlName="email" [class.inva"):
 ng:///DynamicTestModule/Login.html@25:4
'ion-input' is not a known element:
1. If 'ion-input' is an Angular component, then verify that it is part
of this module.
2. If 'ion-input' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("
<ion-item>
    <ion-label floating>Email</ion-label>
    [ERROR ->]<ion-input type="email" formControlName="email" [class.invalid]="!loginForm.controls.email.valid && ("): ng:///DynamicTestModule/Login.html@26:4
'ion-item' is not a known element:
</code>```

**1. If 'ion-item' is an Angular component, then verify that it is part of this module.
2. If 'ion-item' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' enter code hereof this component to suppress this message. ("
    [ERROR ->]****

this is my test.ts

```<code>     import 'zone.js/dist/long-stack-trace-zone';
      import 'zone.js/dist/proxy.js';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/jasmine-patch';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { getTestBed, TestBed } from '@angular/core/testing';
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';
import { App, Config, Form, IonicModule, Keyboard, DomController, MenuController, NavController, Platform } from 'ionic-angular';
import { ConfigMock } from './mocks';

// Unfortunately there's no typing for the `__karma__` variable. Just
 declare it as any.
declare var __karma__: any;
declare var require: any;

// Prevent Karma from running prematurely.
__karma__.loaded = function (): void {
  // noop
};

// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting(),
);

// Then we find all the tests.
let context: any = require.context('./', true, /\.spec\.ts/);

// And load the modules.
context.keys().map(context);

// Finally, start Karma to run the tests.
__karma__.start();
``
</code>```

答:
Did you import IonicModule when configuring your test suite?
Something like (in test.ts):</p>

```<code>public static configureIonicTestingModule(components: Array<any>): typeof TestBed {
  return TestBed.configureTestingModule({
    declarations: [
      ...components,
    ],
    providers: [
      App, Form, DomController
    ],
    imports: [
      FormsModule,
      IonicModule, // <- this here
    ],
  });
}
</code>```

Body:
On running npm test i am getting this error on my component ->

  **Can't bind to 'formGroup' since it isn't a known property of
   'form'.
   ("

<form [ERROR ->][formGroup]="loginForm" text-center>
<ion-list>
"): ng:///DynamicTestModule/Login.html@18:6
'ion-label' is not a known element:
1. If 'ion-label' is an Angular component, then verify that it is part
of this module.
2. If 'ion-label' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA'
to the '@NgModule.schemas' of this component to suppress this message.
 ("
<ion-item>
    [ERROR ->]<ion-label floating>Email</ion-label>
    <ion-input type="email" formControlName="email" [class.inva"):
 ng:///DynamicTestModule/Login.html@25:4
'ion-input' is not a known element:
1. If 'ion-input' is an Angular component, then verify that it is part
of this module.
2. If 'ion-input' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("
<ion-item>
    <ion-label floating>Email</ion-label>
    [ERROR ->]<ion-input type="email" formControlName="email" [class.invalid]="!loginForm.controls.email.valid && ("): ng:///DynamicTestModule/Login.html@26:4
'ion-item' is not a known element:

**1. If 'ion-item' is an Angular component, then verify that it is part of this module.
2. If 'ion-item' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' enter code hereof this component to suppress this message. ("
    [ERROR ->]****

this is my test.ts

     import 'zone.js/dist/long-stack-trace-zone';
      import 'zone.js/dist/proxy.js';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/jasmine-patch';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { getTestBed, TestBed } from '@angular/core/testing';
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';
import { App, Config, Form, IonicModule, Keyboard, DomController, MenuController, NavController, Platform } from 'ionic-angular';
import { ConfigMock } from './mocks';

// Unfortunately there's no typing for the `__karma__` variable. Just
 declare it as any.
declare var __karma__: any;
declare var require: any;

// Prevent Karma from running prematurely.
__karma__.loaded = function (): void {
  // noop
};

// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting(),
);

// Then we find all the tests.
let context: any = require.context('./', true, /\.spec\.ts/);

// And load the modules.
context.keys().map(context);

// Finally, start Karma to run the tests.
__karma__.start();
``

Body:
Did you import IonicModule when configuring your test suite?
Something like (in test.ts):

public static configureIonicTestingModule(components: Array<any>): typeof TestBed {
  return TestBed.configureTestingModule({
    declarations: [
      ...components,
    ],
    providers: [
      App, Form, DomController
    ],
    imports: [
      FormsModule,
      IonicModule, // <- this here
    ],
  });
}


来源: stackexchange

问:
Decrypt SSL packets using PyShark
I am able to decrypt SSL packets in wireshark(GUI) using the private keys. In the same manner how to decrypt packets using PyShark (Programmatically). Is there any other way to do same task using any different programmatic approach ?</p>

答:
This is not tested but override_prefs will let you add custom flags to tshark or override some:

.- you can pass a dictionary to override_prefs attribute like

```<code>def create_ssl_override(ssl_key_path, server='127.0.0.1', port='443',
                        protocol='http', ssl_debug_file='ssl_debug.log'):

    ssh_key_info = '{server},{port},{protocol},{pem_path}'.format(
       server=server, port=port, protocol=protocol, pem_path=pem_path)

    return {
      'ssl.desegment_ssl_records': 'TRUE',
      'ssl.desegment_ssl_application_data': 'TRUE',
      'tcp.desegment_tcp_streams': 'TRUE',
      'ssl.keys_list': ssl_key_info,
      'ssl.debug_file': ssl_debug_file
    }

ssl_overrides = create_ssl_override('my_server_key_file.pem')
</code>```

So when creating your capture object pass override_prefs=ssl_overrides as one of the arguments. Again I have not tested this and I'm not sure pyshark would be able to work with the ssl xml output but try it.

If not tshark directly (example from https://wiki.wireshark.org/SSL)

```<code>tshark -o "ssl.desegment_ssl_records: TRUE" -o "ssl.desegment_ssl_application_data: TRUE" -o "ssl.keys_list: 127.0.0.1,4443,http,/home/dirkx/xx/privkey.pem" -o "ssl.debug_file: /home/dirkx/.wireshark-log" -i eth0 -R "tcp.port == 4443"
</code>```

ContentLicense: CC BY-SA 3.0

Title: Decrypt SSL packets using PyShark

Body:
This is not tested but override_prefs will let you add custom flags to tshark or override some:

.- you can pass a dictionary to override_prefs attribute like

def create_ssl_override(ssl_key_path, server='127.0.0.1', port='443',
                        protocol='http', ssl_debug_file='ssl_debug.log'):

    ssh_key_info = '{server},{port},{protocol},{pem_path}'.format(
       server=server, port=port, protocol=protocol, pem_path=pem_path)

    return {
      'ssl.desegment_ssl_records': 'TRUE',
      'ssl.desegment_ssl_application_data': 'TRUE',
      'tcp.desegment_tcp_streams': 'TRUE',
      'ssl.keys_list': ssl_key_info,
      'ssl.debug_file': ssl_debug_file
    }

ssl_overrides = create_ssl_override('my_server_key_file.pem')

So when creating your capture object pass override_prefs=ssl_overrides as one of the arguments. Again I have not tested this and I'm not sure pyshark would be able to work with the ssl xml output but try it.

If not tshark directly (example from https://wiki.wireshark.org/SSL)

tshark -o "ssl.desegment_ssl_records: TRUE" -o "ssl.desegment_ssl_application_data: TRUE" -o "ssl.keys_list: 127.0.0.1,4443,http,/home/dirkx/xx/privkey.pem" -o "ssl.debug_file: /home/dirkx/.wireshark-log" -i eth0 -R "tcp.port == 4443"


问:
How to change the "from" field in nodemailer?
Disclaimer: I'm not very good with technical email aspects.

So I've setup up a free zoho mail account which basically is just an mail server for my domain. This kinda works via mx record forwarding or something, I'm not entirely sure how it works.

Anyway, the point is: I can change easily the from field when using my account per Outlook. So my email address foo@bar.com appears as Foo from bar.com in most email clients.

Now I want to send some automated emails from my donotreply@bar.com account with nodemailer (v1.10.0) over SMTP with SSL. I've tried different approaches I've found in the documentation / on the internet. All of them just have thrown an ambigious stack trace (see below).

As soon as I stop trying to change the from field everything works fine (except for the wrong from field). Since I've no idea whats goin on I'm asking for some help troubleshooting this.

I've tried changing the second argument of createTransport() to my desired from field. Did not work.

```<code>nodemailer.createTransport(auth.mail, {from: auth.mail.auth.user});
</code>```

to

```<code>nodemailer.createTransport(auth.mail, {from: 'Foo from bar.com'});
</code>```

I've tried setting auth.mail.from which did also not work. And I've tried setting auth.mail.from with passing a 2nd parameter to createTransport().

My code

```<code>var nodemailer = require('nodemailer');
var auth = { mail: { host: 'smtp.zoho.com', port: 465, secure: true, auth: { user: 'donotreply@bar.com', pass: 'strongpassword' } };
var log = require('./log');

var transporter = nodemailer.createTransport(auth.mail, {from: auth.mail.auth.user});

function sendText(settings,cb) {
    transporter.sendMail(settings, function (err, info) {
        if (err) {
            log.warn('Failed to send an Email', err);
        } else {
            log.info('Successfully sent email', info);
        }
        if (cb) {
            cb(err, info);
        }
    });
}
</code>```

Here the stacktrace I've talked about before

```<code>Message failed
    at SMTPConnection._formatError (c:\...\node_modules\nodemailer\node_modules\nodemailer-smtp-transport\node_modules\smtp-connection\src\smtp-connection.js:388:15)
    at SMTPConnection._actionStream (c:\...\node_modules\nodemailer\node_modules\nodemailer-smtp-transport\node_modules\smtp-connection\src\smtp-connection.js:948:30)
    at SMTPConnection.<anonymous> (c:\...\node_modules\nodemailer\node_modules\nodemailer-smtp-transport\node_modules\smtp-connection\src\smtp-connection.js:579:14)
    at SMTPConnection._processResponse (c:\...\node_modules\nodemailer\node_modules\nodemailer-smtp-transport\node_modules\smtp-connection\src\smtp-connection.js:511:16)
    at SMTPConnection._onData (c:\...\node_modules\nodemailer\node_modules\nodemailer-smtp-transport\node_modules\smtp-connection\src\smtp-connection.js:357:10)
    at emitOne (events.js:77:13)
    at TLSSocket.emit (events.js:169:7)
    at readableAddChunk (_stream_readable.js:146:16)
    at TLSSocket.Readable.push (_stream_readable.js:110:10)
    at TLSWrap.onread (net.js:523:20)
</code>```

答:
I had the same issue with the from: field and I went back to read gmail setup and this is what i found - as i said, only GMAIL. I haven't tried a different provider yet.
src: nodemailer.com/usage/using-gmail/

Client: Gmail

Gmail also always sets authenticated username as the From: email
  address. So if you authenticate as foo@example.com and set
  bar@example.com as the from: address, then Gmail reverts this and
  replaces the sender with the authenticated user.

basically, you can only specify the authenticated user on the from: field

thank you, if I'm wrong, please let me know

Body:
Disclaimer: I'm not very good with technical email aspects.

So I've setup up a free zoho mail account which basically is just an mail server for my domain. This kinda works via mx record forwarding or something, I'm not entirely sure how it works.

Anyway, the point is: I can change easily the from field when using my account per Outlook. So my email address foo@bar.com appears as Foo from bar.com in most email clients.

Now I want to send some automated emails from my donotreply@bar.com account with nodemailer (v1.10.0) over SMTP with SSL. I've tried different approaches I've found in the documentation / on the internet. All of them just have thrown an ambigious stack trace (see below).

As soon as I stop trying to change the from field everything works fine (except for the wrong from field). Since I've no idea whats goin on I'm asking for some help troubleshooting this.

I've tried changing the second argument of createTransport() to my desired from field. Did not work.

nodemailer.createTransport(auth.mail, {from: auth.mail.auth.user});

to

nodemailer.createTransport(auth.mail, {from: 'Foo from bar.com'});

I've tried setting auth.mail.from which did also not work. And I've tried setting auth.mail.from with passing a 2nd parameter to createTransport().

My code

var nodemailer = require('nodemailer');
var auth = { mail: { host: 'smtp.zoho.com', port: 465, secure: true, auth: { user: 'donotreply@bar.com', pass: 'strongpassword' } };
var log = require('./log');

var transporter = nodemailer.createTransport(auth.mail, {from: auth.mail.auth.user});

function sendText(settings,cb) {
    transporter.sendMail(settings, function (err, info) {
        if (err) {
            log.warn('Failed to send an Email', err);
        } else {
            log.info('Successfully sent email', info);
        }
        if (cb) {
            cb(err, info);
        }
    });
}

Here the stacktrace I've talked about before

Message failed
    at SMTPConnection._formatError (c:\...\node_modules\nodemailer\node_modules\nodemailer-smtp-transport\node_modules\smtp-connection\src\smtp-connection.js:388:15)
    at SMTPConnection._actionStream (c:\...\node_modules\nodemailer\node_modules\nodemailer-smtp-transport\node_modules\smtp-connection\src\smtp-connection.js:948:30)
    at SMTPConnection.<anonymous> (c:\...\node_modules\nodemailer\node_modules\nodemailer-smtp-transport\node_modules\smtp-connection\src\smtp-connection.js:579:14)
    at SMTPConnection._processResponse (c:\...\node_modules\nodemailer\node_modules\nodemailer-smtp-transport\node_modules\smtp-connection\src\smtp-connection.js:511:16)
    at SMTPConnection._onData (c:\...\node_modules\nodemailer\node_modules\nodemailer-smtp-transport\node_modules\smtp-connection\src\smtp-connection.js:357:10)
    at emitOne (events.js:77:13)
    at TLSSocket.emit (events.js:169:7)
    at readableAddChunk (_stream_readable.js:146:16)
    at TLSSocket.Readable.push (_stream_readable.js:110:10)
    at TLSWrap.onread (net.js:523:20)


问:
CSS rules are simply not applied in Internet Explorer. Where should I look for more info?
I don't have a lot of information here.  My site has been working in IE8, but now no styles are applied. The developer tools show all of the CSS files being loaded, but no elements show any evidence of those styles being applied.  Chrome & Firefox still apply all styles with no problem.

I know you can't help me without more information, but maybe you have an idea of where I could look for an error?  All of my javascript is running fine.  Is it possible that an invalid CSS file would just stop all style application, or something like that?

Thanks for any suggestions!

PS: possibly relevant - my base css file imports several others - about 8 in total.

答: There is a cap on number of css files that can be included in a page on IE. Check if u are including lot(>31) of css files refer http://drupaleasy.com/quicktips/internet-explorer-css-file-limits</p>

ContentLicense: CC BY-SA 2.5


问:
VNext build system: don't trigger the build if code is not changed
In XAML build system in VS2012, there is an check box option "Build even if nothing has changed since the previous build", when Schedule option is selected.

This is missing in VNext build and the problem is that nightly build is fired even if no code was committed during the day. In my case it takes two hours to build with complete test suite.

Is there an easy workaround or plug in to achieve this?

Thanks

答:
In TFS VNext build system Microsoft removed this option.

I would use an alternative instance of a workaround, you can create a build definition with a CI-trigger.
Another benefits of this practice is you get fast feedback if a change can not be integrated in the code base.

In this case you maybe need more than one build agent to run parallel builds in the case of parallel check-ins.

There is a feature request for it. But I think MS will not realize this request

https://visualstudio.uservoice.com/forums/121579-visual-studio-2015/suggestions/16300498-add-build-event-if-nothing-has-changed-since-prev


问:
NG-Show if array contains a certain value and not another
I have an 3 user rights - Admin, User, and Editor.  The way this is setup is:

If you are an Admin the return is roles: ["Admin", "User", "Editor"]

If you are an User the return is roles: ["User"]

If you are an Editor the return is roles: ["User", "Editor"]

Now what I have now is ng-show="object.roles.length < 2" = User and etc. for the other two.

I am sure there is a better/smarter way to do this or maybe it is easier to do it this way.  I am just not sure how to go about it differently.  Thanks for the suggestions.

答:
This worked for me:

```<code><div class="lil" ng-show="role.rileName.includes('someother') == 0 && role.rileName.includes('Admin')">
    <a class="{{role.rileName}}" href="javascript:void(0);" title="{{role.rileName}}" ng-controller="sampleRequestController" ng-click="addSamples(role.rileID,items.CanOrder);">{{role.rileName}}</a>
</li>
</code>```

It will not show if == 0, otherwise it will.

Body:
This worked for me:

<div class="lil" ng-show="role.rileName.includes('someother') == 0 && role.rileName.includes('Admin')">
    <a class="{{role.rileName}}" href="javascript:void(0);" title="{{role.rileName}}" ng-controller="sampleRequestController" ng-click="addSamples(role.rileID,items.CanOrder);">{{role.rileName}}</a>
</li>

It will not show if == 0, otherwise it will.


问:
Python threading not working as it is supposed to work
I'm following Bucky's Python tutorial and in his video of threading, he got this output (not exactly):

```<code>Send out messages
Send out messages
Send out messages
Receive messages
Send out messages
Receive messages
Send out messages
Receive messages
Send out messages
Receive messages
Send out messages
Receive messages
Receive messages
Receive messages
</code>```

but when I tried writing similar code, I got this output:

```<code>Receiving messages...
Receiving messages...
Receiving messages...
Receiving messages...
Receiving messages...
Receiving messages...
Receiving messages...
Receiving messages...
Receiving messages...
Receiving messages...
Sending messages...
Sending messages...
Sending messages...
Sending messages...
Sending messages...
Sending messages...
Sending messages...
Sending messages...
Sending messages...
Sending messages...
</code>```

Here's my code:

```<code># threading

import threading

class Messenger(threading.Thread):
    def run(self):
        for _ in range(10): # '_' is used when you want to run a for loop but don't care about the varialble
            print(threading.currentThread().getName())

x = Messenger(name='Sending messages...')
y = Messenger(name='Receiving messages...')

x.start()
y.start()
</code>```

So, is there something wrong with my code or what is wrong here and why my output is different from Bucky's output?

答: Order of output is not guaranteed when you use threads. The order in which threads are executed depends on your OS. I got a totally different output on my system. </p>

Body:
I'm following Bucky's Python tutorial and in his video of threading, he got this output (not exactly):

Send out messages
Send out messages
Send out messages
Receive messages
Send out messages
Receive messages
Send out messages
Receive messages
Send out messages
Receive messages
Send out messages
Receive messages
Receive messages
Receive messages

but when I tried writing similar code, I got this output:

Receiving messages...
Receiving messages...
Receiving messages...
Receiving messages...
Receiving messages...
Receiving messages...
Receiving messages...
Receiving messages...
Receiving messages...
Receiving messages...
Sending messages...
Sending messages...
Sending messages...
Sending messages...
Sending messages...
Sending messages...
Sending messages...
Sending messages...
Sending messages...
Sending messages...

Here's my code:

# threading

import threading

class Messenger(threading.Thread):
    def run(self):
        for _ in range(10): # '_' is used when you want to run a for loop but don't care about the varialble
            print(threading.currentThread().getName())

x = Messenger(name='Sending messages...')
y = Messenger(name='Receiving messages...')

x.start()
y.start()

So, is there something wrong with my code or what is wrong here and why my output is different from Bucky's output?


问:
jQuery create new Array with doubling old one
i have problem where i need to make array from input but each input char need to be doubled in array. for example if input is ABC array need to result in AABBCC.
so i end up with this code

```<code>if (hex.length < 6) {
    hex.splice(hex.indexOf(hex[i]) + 1, 0, hex[i]);
}
</code>```

if input is ABC it will output AABBCC

if input is AAB it will output AAAABB

but if first and last character is same like ABA it will end up AAABBA. Why is that?

答:
This is because indexOf() returns the first occurrence of the specified value. You can use the reduce() method instead:

const double = arr => arr.reduce((acc, next) => [...acc, next, next], []);
console.log(double(Array.from('ABA')).join(''));```

Body:
i have problem where i need to make array from input but each input char need to be doubled in array. for example if input is ABC array need to result in AABBCC.
so i end up with this code

if (hex.length < 6) {
    hex.splice(hex.indexOf(hex[i]) + 1, 0, hex[i]);
}

if input is ABC it will output AABBCC

if input is AAB it will output AAAABB

but if first and last character is same like ABA it will end up AAABBA. Why is that?


问:
Clearing browsing data in chrome custom tab
Is it possible to clear browsing data, cookies, active logins, etc.  behind the scenes(programatically) on chrome custom tabs?

My goal is to have the user be prompted to login every time they open the custom tab (instead of being logged in automatically)

答:
Shared cookie jar and permissions model so users don't have to log in to sites they are already connected to, or re-grant permissions they have already granted.

Chrome Custom Tabs is the Chrome browser (via the Chrome service and custom Intents) and thus the cache, cookies, etc.. are shared (actually the same).

The answer is no, you can not programmatically clear the data of Chrome.

Note: Right now there is no support of creating an Incognito-based Custom Tab

I would issue the user a transient/session cookie so it does not get persisted if you wish to forced a re-login on the start of every new session.


问:
React Native - Registering components with AppRegistry
I'm new to React Native, but I noticed in the main index.js file, you register the App component. I see this as similar to attaching the App component to a root element in React. I know I still have to export each component I create, but do I have to call this line within every component as well? </p>

```<code>AppRegistry.registerComponent('App', () => App)
</code>```

答: No, you only need to do it for your top level app component.</p>

Body:
I'm new to React Native, but I noticed in the main index.js file, you register the App component. I see this as similar to attaching the App component to a root element in React. I know I still have to export each component I create, but do I have to call this line within every component as well?

AppRegistry.registerComponent('App', () => App)


问:
Declare and print an Arabic character as a wchar_t
I'm trying to store an Arabic character as a wchar_t and then print it to the console, but can't get it to work.

I've set my console to UTF-8 and Arabic letters are displaying (albeit not joining) correctly if I just type them into the console.

I've tried a few different methods based off the answers in (How to initialize a wchar_t variable?) and can print out other unicode characters but not Arabic...

So far I've tried:

The code below - gives an error about making an integer from a pointer without a cast:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
#include <locale.h>

int main ()
{
    wchar_t a = L"ي";

    setlocale(LC_ALL, "");
    wprintf (L" here is my character - %lc",a);

    return 0;
}
</code>```

Same but with single quotes - runs but prints an empty space:

```<code>wchar_t a = L'ي';
</code>```

The unicode value itself - gives a warning the character constant too long for its type:

```<code>wchar_t a = L'\xd9\x84';
</code>```

It seems to work when I try non-Arabic characters - if I type in 'g' it comes through fine and 'xd9' gives me a nice accented U character. Is there something extra I need to do for Arabic?

Any help would be very much appreciated! Really I want to be able to type in Arabic and not have to use the unicode number.

I'm using Windows and MinGW (though I'm having problems with it anyway so would be happy to switch compilers if that solved the problem)

答:
For the first example you need to use the %s format to have a chance. I haven't tried it with Arabic so I don't know what to expect. The obvious problem is that Arabic is right to left whilst consoles are designed for left to right. But printing a string as a character isn't going to work.

wchar_t is not used for UTF-8. UTF-8 uses plain char * (the main point of the encoding). wchar_t used extended 16 bit code points. If you look up the Arabic code points and enter them as numbers you should at least get Arabic output from wprintf(). To enter as Arabic glyphs is an issue with the editor as much as C++ itself.

Body:
I'm trying to store an Arabic character as a wchar_t and then print it to the console, but can't get it to work.

I've set my console to UTF-8 and Arabic letters are displaying (albeit not joining) correctly if I just type them into the console.

I've tried a few different methods based off the answers in (How to initialize a wchar_t variable?) and can print out other unicode characters but not Arabic...

So far I've tried:

The code below - gives an error about making an integer from a pointer without a cast:

#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
#include <locale.h>

int main ()
{
    wchar_t a = L"ي";

    setlocale(LC_ALL, "");
    wprintf (L" here is my character - %lc",a);

    return 0;
}

Same but with single quotes - runs but prints an empty space:

wchar_t a = L'ي';

The unicode value itself - gives a warning the character constant too long for its type:

wchar_t a = L'\xd9\x84';

It seems to work when I try non-Arabic characters - if I type in 'g' it comes through fine and 'xd9' gives me a nice accented U character. Is there something extra I need to do for Arabic?

Any help would be very much appreciated! Really I want to be able to type in Arabic and not have to use the unicode number.

I'm using Windows and MinGW (though I'm having problems with it anyway so would be happy to switch compilers if that solved the problem)


问:
Sending multiple values from servlet to jsp
I have a servlet code where I check for username and password in a helper class and after checking it comes back to servlet and lists users. The username along with the list of users must be displayed in the jsp. How to send both the values? Here is the code which I have tried. It displays nothing
String outp=t.Welcome(name, pwd);</p>

```<code>String Users=t.List_Of_Users();
String User[]=Users.trim().split(" ");
request.setAttribute("name", User);
response.sendRedirect("Welcome_User.jsp?Users="+User+"&outp="+outp);
</code>```

答:
If you use forwarding (request.getRequestDispatcher("welcome_user.jsp").forward()) - just add another request.setAttribute("attrName", value);

if you retain the redirect - add another get parameter. Welcome_User.jsp?Users="+User+"&outp="+outp + "&another=" + another; (and remove the request.setAttribute(..))

In order to represent an array as string you have multiple options. One of which is Arrays.toString(array)

(Note that sending a password as a get parameter is a security problem.)

Body:
I have a servlet code where I check for username and password in a helper class and after checking it comes back to servlet and lists users. The username along with the list of users must be displayed in the jsp. How to send both the values? Here is the code which I have tried. It displays nothing
String outp=t.Welcome(name, pwd);

String Users=t.List_Of_Users();
String User[]=Users.trim().split(" ");
request.setAttribute("name", User);
response.sendRedirect("Welcome_User.jsp?Users="+User+"&outp="+outp);


答:
Instead of explicitly iterating using indexOf which only returns the first index, you might want to try array.Map.

var a = "abc";
var b = "aba";
var c = "foo  bar mañana mañana"

function duplicate(phrase) {
  return Array.from(phrase).map(function(elem) {
    return elem + elem;
  }).join("");
}

var aAns = duplicate(a);
var bAns = duplicate(b);
var cAns = duplicate(c);

console.log(aAns);
console.log(bAns);
console.log(cAns);```

Edit

Thanks to Michał Perłakowski for the Unicode callout!

Title: jQuery create new Array with doubling old one

Body:
Instead of explicitly iterating using indexOf which only returns the first index, you might want to try array.Map.

var a = "abc";
var b = "aba";
var c = "foo  bar mañana mañana"

function duplicate(phrase) {
  return Array.from(phrase).map(function(elem) {
    return elem + elem;
  }).join("");
}

var aAns = duplicate(a);
var bAns = duplicate(b);
var cAns = duplicate(c);

console.log(aAns);
console.log(bAns);
console.log(cAns);

Edit

Thanks to Michał Perłakowski for the Unicode callout!


问:
Android Quiz app crashing while updating score
The submit button id is ShowScore
correct answers are right1,right2...right53
when the button is clicked the app crashes...
android studios doest show any errors
right answer awards 1 point
wrong answer is -1
please help me out    </p>

```<code>import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    int score = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void setScore() {
        RadioButton check1 = (RadioButton) findViewById(R.id.right1);
        boolean doit1 = check1.isChecked();
        RadioButton check2 = (RadioButton) findViewById(R.id.right2);
        boolean doit2 = check2.isChecked();
        RadioButton check3 = (RadioButton) findViewById(R.id.right3);
        boolean doit3 = check3.isChecked();
        RadioButton check4 = (RadioButton) findViewById(R.id.right4);
        boolean doit4 = check4.isChecked();
        CheckBox check5 = (CheckBox) findViewById(R.id.right51);
        boolean doit5 = check5.isChecked();
        CheckBox check52 = (CheckBox) findViewById(R.id.right52);
        boolean doit52 = check52.isChecked();
        CheckBox check53 = (CheckBox) findViewById(R.id.right53);
        boolean doit53 = check53.isChecked();
        updateScore(doit1);
        updateScore2(doit2);
        updateScore3(doit3);
        updateScore4(doit4);
        updateScore5(doit5, doit52, doit53);
        showScore();

    }

    private int updateScore(boolean doit1) {
        if (doit1) {
            score = score + 1;
        } else {
            score = score - 1;

        }
        return score;

    }

    private int updateScore2(boolean doit2) {
        if (doit2) {
            score = score + 1;
        } else {
            score = score - 1;
        }
        return score;
    }

    private int updateScore3(boolean doit3) {
        if (doit3) {
            score = score + 1;
        } else {
            score = score - 1;
        }
        return score;
    }

    private int updateScore4(boolean doit4) {
        if (doit4) {
            score = score + 1;
        } else {
            score = score - 1;
        }
        return score;
    }

    private int updateScore5(boolean doit5, boolean doit52, boolean doit53) {
        if (doit5 && doit52 && doit53) {
            score = score + 1;
        } else {
            score = score - 1;
        }
        return score;

    }

    private void showScore() {
        TextView olds = (TextView) findViewById(R.id.ShowScore);
        olds.setText(score);
    }
}
</code>```

答:
Change setText.(score) to (score+"");

Explanation: setText method accepts only String as an argument but yes you can pass in an int but it will give an error and I suppose that output stream in android platform must always be String type.

You can even use String.valueOf(score); since this is the right way and adding quotation marks set in the first paramater is like a geek cheat.  If you have set onClick method in xml, then setScore() must take the parameter setScore (View view) { //text view goes here..}

Hope it works. Cheers!

Body:
The submit button id is ShowScore
correct answers are right1,right2...right53
when the button is clicked the app crashes...
android studios doest show any errors
right answer awards 1 point
wrong answer is -1
please help me out

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    int score = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void setScore() {
        RadioButton check1 = (RadioButton) findViewById(R.id.right1);
        boolean doit1 = check1.isChecked();
        RadioButton check2 = (RadioButton) findViewById(R.id.right2);
        boolean doit2 = check2.isChecked();
        RadioButton check3 = (RadioButton) findViewById(R.id.right3);
        boolean doit3 = check3.isChecked();
        RadioButton check4 = (RadioButton) findViewById(R.id.right4);
        boolean doit4 = check4.isChecked();
        CheckBox check5 = (CheckBox) findViewById(R.id.right51);
        boolean doit5 = check5.isChecked();
        CheckBox check52 = (CheckBox) findViewById(R.id.right52);
        boolean doit52 = check52.isChecked();
        CheckBox check53 = (CheckBox) findViewById(R.id.right53);
        boolean doit53 = check53.isChecked();
        updateScore(doit1);
        updateScore2(doit2);
        updateScore3(doit3);
        updateScore4(doit4);
        updateScore5(doit5, doit52, doit53);
        showScore();

    }

    private int updateScore(boolean doit1) {
        if (doit1) {
            score = score + 1;
        } else {
            score = score - 1;

        }
        return score;

    }

    private int updateScore2(boolean doit2) {
        if (doit2) {
            score = score + 1;
        } else {
            score = score - 1;
        }
        return score;
    }

    private int updateScore3(boolean doit3) {
        if (doit3) {
            score = score + 1;
        } else {
            score = score - 1;
        }
        return score;
    }

    private int updateScore4(boolean doit4) {
        if (doit4) {
            score = score + 1;
        } else {
            score = score - 1;
        }
        return score;
    }

    private int updateScore5(boolean doit5, boolean doit52, boolean doit53) {
        if (doit5 && doit52 && doit53) {
            score = score + 1;
        } else {
            score = score - 1;
        }
        return score;

    }

    private void showScore() {
        TextView olds = (TextView) findViewById(R.id.ShowScore);
        olds.setText(score);
    }
}


问:
Failed to execute user defined function
I have the following UDF:

```<code>val jac_index:(Array[String],Array[String])=>Float=(Sq1:Array[String],Sq2:Array[String])=>
{
    val Sq3=Sq1.intersect(Sq2)
    val Sq4=Sq1.union(Sq2).distinct
    if (!Sq4.isEmpty) Sq3.length.toFloat/Sq4.length.toFloat else 0F
}
val jacUDF=udf(jac_index)
</code>```

and when I execute the following sentence

```<code>val movie_jac_df=movie_pairs_df.withColumn("jac",jacUDF(movie_pairs_df("name"),movie_pairs_df("name2")))
</code>```

I get the error "Failed to execute user defined function"

the schema of movie_pairs_df is the following

```<code>root
 |-- movie: string (nullable = true)
 |-- name: array (nullable = true)
 |    |-- element: string (containsNull = true)
 |-- movie2: string (nullable = true)
 |-- name2: array (nullable = true)
 |    |-- element: string (containsNull = true)
</code>```

So what's the cause?

答:
Spark's DataFrames model Array columns as mutable.WrappedArray, which means your UDF should take two WrappedArrays as its input;

If you change jac_index to expect two such arrays:

```<code>import scala.collection.mutable

val jac_index: (mutable.WrappedArray[String], mutable.WrappedArray[String]) => Float =
  (Sq1, Sq2) => { /* same implementation */ }
</code>```

This will work as expected.

Title: Failed to execute user defined function

Body:
I have the following UDF:

val jac_index:(Array[String],Array[String])=>Float=(Sq1:Array[String],Sq2:Array[String])=>
{
    val Sq3=Sq1.intersect(Sq2)
    val Sq4=Sq1.union(Sq2).distinct
    if (!Sq4.isEmpty) Sq3.length.toFloat/Sq4.length.toFloat else 0F
}
val jacUDF=udf(jac_index)

and when I execute the following sentence

val movie_jac_df=movie_pairs_df.withColumn("jac",jacUDF(movie_pairs_df("name"),movie_pairs_df("name2")))

I get the error "Failed to execute user defined function"

the schema of movie_pairs_df is the following

root
 |-- movie: string (nullable = true)
 |-- name: array (nullable = true)
 |    |-- element: string (containsNull = true)
 |-- movie2: string (nullable = true)
 |-- name2: array (nullable = true)
 |    |-- element: string (containsNull = true)

So what's the cause?

Body:
Spark's DataFrames model Array columns as mutable.WrappedArray, which means your UDF should take two WrappedArrays as its input;

If you change jac_index to expect two such arrays:

import scala.collection.mutable

val jac_index: (mutable.WrappedArray[String], mutable.WrappedArray[String]) => Float =
  (Sq1, Sq2) => { /* same implementation */ }

This will work as expected.


问:
WM_TIMER gets lost in specific conditions
```<code>#include <windows.h>
#include <stdio.h>

class tWnd {
private:
    static LRESULT CALLBACK Disp_test_WndProc(
        HWND hwnd,        // handle to window
        UINT uMsg,        // message identifier
        WPARAM wParam,    // first message parameter
        LPARAM lParam)    // second message parameter
    {
        switch (uMsg)
        {
            case WM_TIMER:{
                printf("timer\n");

                return 0;
            }

            case WM_PAINT:
                // Paint the window's client area.
                return 0;

            case WM_DESTROY:
                return 0;

            case WM_HOTKEY:{

            } return 0;
            //
            // Process other messages.
            //
            default:
                return DefWindowProc(hwnd, uMsg, wParam, lParam);
        }
        return 0;
    }

public:
    tWnd() {

            WNDCLASSA wc;
            wc.style = CS_HREDRAW | CS_VREDRAW;
            wc.lpfnWndProc = (WNDPROC) Disp_test_WndProc;
            wc.cbClsExtra = 0;
            wc.cbWndExtra = 0;
            wc.hInstance = GetModuleHandle(NULL);
            wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
            wc.hCursor = LoadCursor(NULL, IDC_ARROW);
            wc.hbrBackground = (HBRUSH) NULL;
            wc.lpszMenuName =  "";
            wc.lpszClassName = "Test";

            if (!RegisterClass(&wc))
               return; //cannot register window class

        HWND testingWindow = CreateWindowEx(WS_EX_TOPMOST,"Test","topmost",WS_VISIBLE,0,0,200,200,0,0,0,0);

        SetTimer(testingWindow,101,500,(TIMERPROC)NULL);

        MSG recent;
        BOOL result;
        while((result=GetMessage(&recent,testingWindow,0,0))&&result!=-1) { //bool can be -1 in MS world
            if(recent.message==WM_USER+1) break;
            TranslateMessage(&recent);
            DispatchMessage(&recent);
        }
    }
};

int main(int argc, char **argv)
{
    tWnd();
    return 0;
}
</code>```

This code never gets WM_TIMER message.

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

class tWnd {
private:
    static LRESULT CALLBACK Disp_test_WndProc(
        HWND hwnd,        // handle to window
        UINT uMsg,        // message identifier
        WPARAM wParam,    // first message parameter
        LPARAM lParam)    // second message parameter
    {
        switch (uMsg)
        {
            case WM_TIMER:{
                printf("timer\n");

                return 0;
            }

            case WM_DESTROY:
                return 0;

            case WM_HOTKEY:{

            } return 0;
            //
            // Process other messages.
            //
            default:
                return DefWindowProc(hwnd, uMsg, wParam, lParam);
        }
        return 0;
    }

public:
    tWnd() {

            WNDCLASSA wc;
            wc.style = CS_HREDRAW | CS_VREDRAW;
            wc.lpfnWndProc = (WNDPROC) Disp_test_WndProc;
            wc.cbClsExtra = 0;
            wc.cbWndExtra = 0;
            wc.hInstance = GetModuleHandle(NULL);
            wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
            wc.hCursor = LoadCursor(NULL, IDC_ARROW);
            wc.hbrBackground = (HBRUSH) NULL;
            wc.lpszMenuName =  "";
            wc.lpszClassName = "Test";

            if (!RegisterClass(&wc))
               return; //cannot register window class

        HWND testingWindow = CreateWindowEx(WS_EX_TOPMOST,"Test","topmost",WS_VISIBLE,0,0,200,200,0,0,0,0);

        SetTimer(testingWindow,101,500,(TIMERPROC)NULL);

        MSG recent;
        BOOL result;
        while((result=GetMessage(&recent,testingWindow,0,0))&&result!=-1) { //bool can be -1 in MS world
            if(recent.message==WM_USER+1) break;
            TranslateMessage(&recent);
            DispatchMessage(&recent);
        }
    }
};

int main(int argc, char **argv)
{
    tWnd();
    return 0;
}
</code>```

This code gets WM_TIMER messages just fine.

The only difference between the two is that WM_PAINT message is default-processed in second variant. How come that having WM_PAINT handled prevents program from receiving WM_TIMER messages? How can I work around that?

I am using MingW w64 (GCC 5.3.0) if that matters.

答:
A window receives a WM_PAINT message when its invalid region is non-empty. This is called out in the documentation for ValidateRect():

The system continues to generate WM_PAINT messages until the current update region is validated.

A standard WM_PAINT handler validates the invalid region (e.g. by calling BeginPaint()), which the default implementation does. Simply returning 0 will not validate the window, and it continues to receive WM_PAINT messages.

WM_TIMER messages are lower priority than WM_PAINT messages.  Your window procedure never sees a timer message because it is constantly busy ignoring paint messages.  This is called out in the documentation for WM_TIMER:

The WM_TIMER message is a low-priority message. The GetMessage and PeekMessage functions post this message only when no other higher-priority messages are in the thread's message queue.

Body:
#include <windows.h>
#include <stdio.h>

class tWnd {
private:
    static LRESULT CALLBACK Disp_test_WndProc(
        HWND hwnd,        // handle to window
        UINT uMsg,        // message identifier
        WPARAM wParam,    // first message parameter
        LPARAM lParam)    // second message parameter
    {
        switch (uMsg)
        {
            case WM_TIMER:{
                printf("timer\n");

                return 0;
            }

            case WM_PAINT:
                // Paint the window's client area.
                return 0;

            case WM_DESTROY:
                return 0;

            case WM_HOTKEY:{

            } return 0;
            //
            // Process other messages.
            //
            default:
                return DefWindowProc(hwnd, uMsg, wParam, lParam);
        }
        return 0;
    }

public:
    tWnd() {

            WNDCLASSA wc;
            wc.style = CS_HREDRAW | CS_VREDRAW;
            wc.lpfnWndProc = (WNDPROC) Disp_test_WndProc;
            wc.cbClsExtra = 0;
            wc.cbWndExtra = 0;
            wc.hInstance = GetModuleHandle(NULL);
            wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
            wc.hCursor = LoadCursor(NULL, IDC_ARROW);
            wc.hbrBackground = (HBRUSH) NULL;
            wc.lpszMenuName =  "";
            wc.lpszClassName = "Test";

            if (!RegisterClass(&wc))
               return; //cannot register window class

        HWND testingWindow = CreateWindowEx(WS_EX_TOPMOST,"Test","topmost",WS_VISIBLE,0,0,200,200,0,0,0,0);

        SetTimer(testingWindow,101,500,(TIMERPROC)NULL);

        MSG recent;
        BOOL result;
        while((result=GetMessage(&recent,testingWindow,0,0))&&result!=-1) { //bool can be -1 in MS world
            if(recent.message==WM_USER+1) break;
            TranslateMessage(&recent);
            DispatchMessage(&recent);
        }
    }
};

int main(int argc, char **argv)
{
    tWnd();
    return 0;
}

This code never gets WM_TIMER message.

#include <windows.h>
#include <stdio.h>

class tWnd {
private:
    static LRESULT CALLBACK Disp_test_WndProc(
        HWND hwnd,        // handle to window
        UINT uMsg,        // message identifier
        WPARAM wParam,    // first message parameter
        LPARAM lParam)    // second message parameter
    {
        switch (uMsg)
        {
            case WM_TIMER:{
                printf("timer\n");

                return 0;
            }

            case WM_DESTROY:
                return 0;

            case WM_HOTKEY:{

            } return 0;
            //
            // Process other messages.
            //
            default:
                return DefWindowProc(hwnd, uMsg, wParam, lParam);
        }
        return 0;
    }

public:
    tWnd() {

            WNDCLASSA wc;
            wc.style = CS_HREDRAW | CS_VREDRAW;
            wc.lpfnWndProc = (WNDPROC) Disp_test_WndProc;
            wc.cbClsExtra = 0;
            wc.cbWndExtra = 0;
            wc.hInstance = GetModuleHandle(NULL);
            wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
            wc.hCursor = LoadCursor(NULL, IDC_ARROW);
            wc.hbrBackground = (HBRUSH) NULL;
            wc.lpszMenuName =  "";
            wc.lpszClassName = "Test";

            if (!RegisterClass(&wc))
               return; //cannot register window class

        HWND testingWindow = CreateWindowEx(WS_EX_TOPMOST,"Test","topmost",WS_VISIBLE,0,0,200,200,0,0,0,0);

        SetTimer(testingWindow,101,500,(TIMERPROC)NULL);

        MSG recent;
        BOOL result;
        while((result=GetMessage(&recent,testingWindow,0,0))&&result!=-1) { //bool can be -1 in MS world
            if(recent.message==WM_USER+1) break;
            TranslateMessage(&recent);
            DispatchMessage(&recent);
        }
    }
};

int main(int argc, char **argv)
{
    tWnd();
    return 0;
}

This code gets WM_TIMER messages just fine.

The only difference between the two is that WM_PAINT message is default-processed in second variant. How come that having WM_PAINT handled prevents program from receiving WM_TIMER messages? How can I work around that?

I am using MingW w64 (GCC 5.3.0) if that matters.


问:
Get all possible strings in printable ASCII
How can I get all possible strings in printable ASCII (eg. 0x20 () to  0x7E (~)) using a generator? It should output (if continually called with .next()):

```<code>
!
"
#
$
</code>```

...

```<code>~

 !
 "
 #
 $
</code>```

and so on. How can I do this?

```<code>var gen = function * (){
    var counter = 0x20;
    while(true) yield String.fromCharCode(++counter);
};
</code>```

works up to 94 tries (~). How I get this to work after that?

答:
Here's a stab at it. As determined in the comments above, this is a matter of taking each number's base 94 representation and adding 32 and printing the corresponding ASCII characters. That's what the char function below does. The numbers generator function iterates from 0 to infinity, and the str function integer-divides the given number by 94 recursively, concatenating the remainders as characters (per char()) to produce a string.

function* numbers() {
  for (let i = 0;; i++) {
    yield str(i);
  }
}

function str(i) {
  if (i === 0) {
    return '';
  }
  return str(Math.floor(i / 94)) + char(i % 94);
}

function char(i) {
  return String.fromCharCode(i+32);
}

const gen = numbers();
setInterval(() => console.log(gen.next().value), 50);```
</div>
</div>
</p>

<p>If you'd rather have a single function, it might look like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function* numbers() {
  for (let i = 0;; i++) {
    let d = i;
    let s = '';

    while (d > 0) {
      let r = d % 94;
      d = Math.floor(d / 94);
      s = String.fromCharCode(r+32) + s;
    }

    yield s;
  }
}

const gen = numbers();
setInterval(() => console.log(gen.next().value), 50);</code>```

Body:
How can I get all possible strings in printable ASCII (eg. 0x20 () to  0x7E (~)) using a generator? It should output (if continually called with .next()):

!
"
#
$

...

~

 !
 "
 #
 $

and so on. How can I do this?

var gen = function * (){
    var counter = 0x20;
    while(true) yield String.fromCharCode(++counter);
};

works up to 94 tries (~). How I get this to work after that?

Body:
Here's a stab at it. As determined in the comments above, this is a matter of taking each number's base 94 representation and adding 32 and printing the corresponding ASCII characters. That's what the char function below does. The numbers generator function iterates from 0 to infinity, and the str function integer-divides the given number by 94 recursively, concatenating the remainders as characters (per char()) to produce a string.

function* numbers() {
  for (let i = 0;; i++) {
    yield str(i);
  }
}

function str(i) {
  if (i === 0) {
    return '';
  }
  return str(Math.floor(i / 94)) + char(i % 94);
}

function char(i) {
  return String.fromCharCode(i+32);
}

const gen = numbers();
setInterval(() => console.log(gen.next().value), 50);

If you'd rather have a single function, it might look like this:

function* numbers() {
  for (let i = 0;; i++) {
    let d = i;
    let s = '';

    while (d > 0) {
      let r = d % 94;
      d = Math.floor(d / 94);
      s = String.fromCharCode(r+32) + s;
    }

    yield s;
  }
}

const gen = numbers();
setInterval(() => console.log(gen.next().value), 50);


问:
Detect global keypress event using Mono + Gtk# on iOS
I'm trying to create a multiplatform desktop application.

I can register global hotkeys in Windows via P/Invoke like this.

I need to do the same in iOS (probably something with MonoPInvokeCallbackAttribute)

What is the best practice to do this in iOS?
Maybe there is some managed wrapper (in Gtk# or else?) so I can have the same codebase without ifdefs?

Thank you!

答: GTK# is a wrapper to GTK lib written in C. It has a set of diffenet widget and all. It cannot even draw them without other components(GDK, atk and others). And when you're talking about iOS... If you want to create an app on iOS better use Xamarin.iOS or Xamarin.Forms or maybe you're talking about Mac OS?</p>


问:
Android how to make back button perform action on a the first click?
I have back button reprogrammed like that:

```<code>@Override
public void onBackPressed() {
    returnManager();
}
</code>```

The problem that I am facing is that when I touch it for the first time it doesn't do anything. After the first time, it works as intended and calls returnManager. Then, if I press some other buttons on the screen and press back again, it doesn't do anything for the first time but works on next touches. Is there anything I am missing here?

答:
A strange solution:</p>

```<code>int calls = 0;

@Override
public void onBackPressed()
{
    calls++;
    if(calls==1)
    {
        returnManager();
        returnManager();
    }
    else
    {
        returnManager();
    }
}
</code>```

Body:
I have back button reprogrammed like that:

@Override
public void onBackPressed() {
    returnManager();
}

The problem that I am facing is that when I touch it for the first time it doesn't do anything. After the first time, it works as intended and calls returnManager. Then, if I press some other buttons on the screen and press back again, it doesn't do anything for the first time but works on next touches. Is there anything I am missing here?

Body:
A strange solution:

int calls = 0;

@Override
public void onBackPressed()
{
    calls++;
    if(calls==1)
    {
        returnManager();
        returnManager();
    }
    else
    {
        returnManager();
    }
}


问:
Python: how to Add DictReader row as dictionary to list with an update
My code basically just goes thru checking each row of a DictReader (a list of dicts) and puts duplicates in the RejectedEvents list of dicts and returns result, which is a deduplicated dict of dicts. I also need to add a reason to each row of RejectedEvents because I will later be rejecting for other reasons as well. The code is pretty self explanatory as is the problem, but not the solution; The issue is the line marked #PROBLEM, and the problem disappears when I take out the update statement; with the update statement, null is assigned and without it row is assigned, so the update is messing it up.</p>

```<code>def GetScrubbedEventData(MetricID, EventsRaw, RejectEvents):
    start = time.time()
    pass_count = 0
    fail_count = 0

    result = {}
    for row in csv.DictReader(EventsRaw, delimiter=","):
        try:
            #check duplicate
            result[row['AssetID']]
            Reason = {"RejectedFor": "Duplicate AssetID in same file."}
            RejectEvents.append(dict(row).update(Reason)) #PROBLEM
            fail_count += 1
        except KeyError:
            row['EventStart'] = scrub.Date(row['EventStart'])
            row['EventEnd'] = scrub.Date(row['EventEnd'])
            result[row['AssetID']] = row
            pass_count += 1
</code>```

答:
Update the row and then append the updated row, not the return value of .update which is None:

```<code>for row in csv.DictReader(EventsRaw):
    ...
    row.update(Reason)
    RejectEvents.append(row)
</code>```

Or you can set a new directly on dict row without having to create the single-valued dict Reason:

```<code>for row in csv.DictReader(EventsRaw):
    ...
    row["RejectedFor"] = "Duplicate AssetID in same file."
    RejectEvents.append(row)
</code>```

Body:
My code basically just goes thru checking each row of a DictReader (a list of dicts) and puts duplicates in the RejectedEvents list of dicts and returns result, which is a deduplicated dict of dicts. I also need to add a reason to each row of RejectedEvents because I will later be rejecting for other reasons as well. The code is pretty self explanatory as is the problem, but not the solution; The issue is the line marked #PROBLEM, and the problem disappears when I take out the update statement; with the update statement, null is assigned and without it row is assigned, so the update is messing it up.

def GetScrubbedEventData(MetricID, EventsRaw, RejectEvents):
    start = time.time()
    pass_count = 0
    fail_count = 0

    result = {}
    for row in csv.DictReader(EventsRaw, delimiter=","):
        try:
            #check duplicate
            result[row['AssetID']]
            Reason = {"RejectedFor": "Duplicate AssetID in same file."}
            RejectEvents.append(dict(row).update(Reason)) #PROBLEM
            fail_count += 1
        except KeyError:
            row['EventStart'] = scrub.Date(row['EventStart'])
            row['EventEnd'] = scrub.Date(row['EventEnd'])
            result[row['AssetID']] = row
            pass_count += 1

Body:
Update the row and then append the updated row, not the return value of .update which is None:

for row in csv.DictReader(EventsRaw):
    ...
    row.update(Reason)
    RejectEvents.append(row)

Or you can set a new directly on dict row without having to create the single-valued dict Reason:

for row in csv.DictReader(EventsRaw):
    ...
    row["RejectedFor"] = "Duplicate AssetID in same file."
    RejectEvents.append(row)


问:
The type or namespace name 'Membership' does not exist in the namespace 'Microsoft.AspNet'
I'm trying to maintain an application that contains the following line in several different files:

```<code>using Microsoft.AspNet.Membership.OpenAuth;
</code>```

I've tried everything I could find. Removed and re-added the reference; cleared the MEF cache and rebuilt; added a different file as a reference. Nothing works. It's bizarre because VS2017 doesn't report this error in the Error List window, but it does show up in the Output window. Anyway, can someone please suggest a possible solution that maybe I haven't tried yet? Thanks.

答:
I was able to compile the project and I will describe how I got it.

1 - I delete all using Microsoft.AspNet.Membership.OpenAuth; and build project.

2 - After build the code show many errors I use the resource of VS2015 help fixes errors on code Show potential fixes and set again using Microsoft.AspNet.Membership.OpenAuth; build project.

3 - Set a new framework 4.6 and build project.

https://drive.google.com/open?id=0B4aywYtmwk6lT1dDNnIxRmtQcUk

Body:
I'm trying to maintain an application that contains the following line in several different files:

using Microsoft.AspNet.Membership.OpenAuth;

I've tried everything I could find. Removed and re-added the reference; cleared the MEF cache and rebuilt; added a different file as a reference. Nothing works. It's bizarre because VS2017 doesn't report this error in the Error List window, but it does show up in the Output window. Anyway, can someone please suggest a possible solution that maybe I haven't tried yet? Thanks.


问:
Angular2: input checkbox with label doesn't work in table
I need to create table with independent checkboxes in one of the columns. The button is styled as here (it forces input inside label). My problem is that it doesn't change states when is located in table. (Beyond table works ok)

```<code><table>

    <thead>
       <tr>
         <th>Check</th>
       </tr>
    </thead>

    <tbody>
     <tr *ngFor="let item of items">
       <td>
         <label class="switch">
           <input type="checkbox" (click)="changed($event)">
           <div class="slider"></div>
         </label>
       </td>
     </tr>
    </tbody>

</table>
</code>```

I also tried to add specific id to each input but without success.

答:
```<code><table>

<thead>
   <tr>
     <th>Check</th>
   </tr>
</thead>

<tbody>
 <tr *ngFor="let item of items">
   <td>
     <label class="switch">
       <input type="checkbox" (change)="changed($event)" >

       <input type="checkbox" (change)="changed($event, item)" [checked]="item.checkbox">
       <div class="slider"></div>
     </label>
   </td>
 </tr>
</tbody>
</code>```

Body:
I need to create table with independent checkboxes in one of the columns. The button is styled as here (it forces input inside label). My problem is that it doesn't change states when is located in table. (Beyond table works ok)

         Check

           <input type="checkbox" (click)="changed($event)">

I also tried to add specific id to each input but without success.


问:
Editable table in PHP
In a PHP application I'm building, I'd like to have an 'editable' table. The idea is that each row will have an edit button, which, when clicked, will replace certain fields with text fields and select lists and change to a save button. When the user clicks save, the data data should be validated and changed if appropriate.

I'm mainly tackling this as a learning project (I'm aware there's a ton of stuff already out there) and to see if I can get anything 'cool' working. I've created a PHP table-generating class that can take an array of objects as a datasource, and can have columns created based on those class methods.

e.g.

```<code>$table = new Table($dataSource);
$table->addColumn('Name', 'getName');
$table->addColumn('Amount Due', array('getOrdersManager', 'getTotalAmountDue')); //First calls getOrdersManager() on each data item and then calls the getTotalAmountDue() on the result
</code>```

I'd like to try my hand at extending this to be able to the table row and have those changes reflect on the corresponding object in the data source.

I don't really have very much experience with AJAX although it's clearly going to play a very important role in getting this to work correctly.

Any tips on how I should approach such a task?

Edit: I'm not really interesting in looking at Ajax libraries at this point (I do have some experience with jQuery). I'm more interested in learning the basics of Ajax at this point.

答:
Some things to be aware of/think about:

Are you going to send every field change to the server, or only the whole row (the latter is more resource efficient, but not necessarily as accurate)

How are you going to ensure the data displayed stays accurate even if the update to the server fails for some reason (either a network failure or a DB/validation error)

How will you ensure the user has permission to update the record and that you don't open a security hole by allowing the AJAX responder just to update whatever record it is told to. My approach has been that if a record is shown in the interactive table then the user has the permission to update it, so a cache of record IDs is held in the session when the table is created

Are you going to load  options dynamically? If you don't, then a long table can end up containing a lot of HTML because of repetition of the select controls, but again it is more resource efficient not to have a request every time a user clicks into a dropdown. One compromise might be to put the options into a hidden HTML field and load them dynamically into the correct place when a user clicks a dropdown

Title: Editable table in PHP

Body:
In a PHP application I'm building, I'd like to have an 'editable' table. The idea is that each row will have an edit button, which, when clicked, will replace certain fields with text fields and select lists and change to a save button. When the user clicks save, the data data should be validated and changed if appropriate.

I'm mainly tackling this as a learning project (I'm aware there's a ton of stuff already out there) and to see if I can get anything 'cool' working. I've created a PHP table-generating class that can take an array of objects as a datasource, and can have columns created based on those class methods.

e.g.

$table = new Table($dataSource);
$table->addColumn('Name', 'getName');
$table->addColumn('Amount Due', array('getOrdersManager', 'getTotalAmountDue')); //First calls getOrdersManager() on each data item and then calls the getTotalAmountDue() on the result

I'd like to try my hand at extending this to be able to the table row and have those changes reflect on the corresponding object in the data source.

I don't really have very much experience with AJAX although it's clearly going to play a very important role in getting this to work correctly.

Any tips on how I should approach such a task?

Edit: I'm not really interesting in looking at Ajax libraries at this point (I do have some experience with jQuery). I'm more interested in learning the basics of Ajax at this point.


问:
how to use linq to return all ints in another set of ints for this scenario?
I have the following scenario:

```<code>1. int[] contentPermissions
2. Dictionary<int, int[]> userPermssions
</code>```

In #2 above, the key is the user ID and the value is an int[] of user permission ID's. What would be a good way to write a lambda function to return all user ID's which have a permission id which matches at least 1 permission in contentPermissions?

UPDATE

Does this look like a pretty good solution?:

```<code>  var userIdsWithPermissions = userPermissions.Where(
            x => x.Value.Intersect(contentPermissions).Count() > 1)
            .Select(x => x.Key).ToArray();
</code>```

答:
You can use this method:

```<code>public int[] GetUserIDArrayByPermission(int permission)
{
  var dicUserPermission=userPermssions.Where(i => i.Value.Contains(permission));
 int[] userIDArray=dicUserPermission.Select(p => p.Key).ToArray();
 return userIDArray;
}
</code>```

UPDATE:

```<code>public int[] GetUserIDArrayByContentPermissions()
{
  var dicUserPermission = userPermssions.Where(i => i.Value.Count(p=>contentPermissions.Contains(p))>0).ToList();
  int[] userIDArray = dicUserPermission.Select(p => p.Key).ToArray();
  return userIDArray;
}
</code>```

Body:
I have the following scenario:

1. int[] contentPermissions
2. Dictionary<int, int[]> userPermssions

In #2 above, the key is the user ID and the value is an int[] of user permission ID's. What would be a good way to write a lambda function to return all user ID's which have a permission id which matches at least 1 permission in contentPermissions?

UPDATE

Does this look like a pretty good solution?:

  var userIdsWithPermissions = userPermissions.Where(
            x => x.Value.Intersect(contentPermissions).Count() > 1)
            .Select(x => x.Key).ToArray();

Body:
You can use this method:

public int[] GetUserIDArrayByPermission(int permission)
{
  var dicUserPermission=userPermssions.Where(i => i.Value.Contains(permission));
 int[] userIDArray=dicUserPermission.Select(p => p.Key).ToArray();
 return userIDArray;
}

UPDATE:

public int[] GetUserIDArrayByContentPermissions()
{
  var dicUserPermission = userPermssions.Where(i => i.Value.Count(p=>contentPermissions.Contains(p))>0).ToList();
  int[] userIDArray = dicUserPermission.Select(p => p.Key).ToArray();
  return userIDArray;
}


答:
define the udf as below</p>

```<code>val jacUDF = udf((Sq1:mutable.WrappedArray[String], Sq2:mutable.WrappedArray[String]) => {
  val Sq3=Sq1.intersect(Sq2)
  val Sq4=Sq1.union(Sq2).distinct
  if (!Sq4.isEmpty) Sq3.length.toFloat/Sq4.length.toFloat else 0F
})
</code>```

Title: Failed to execute user defined function

Body:
define the udf as below

val jacUDF = udf((Sq1:mutable.WrappedArray[String], Sq2:mutable.WrappedArray[String]) => {
  val Sq3=Sq1.intersect(Sq2)
  val Sq4=Sq1.union(Sq2).distinct
  if (!Sq4.isEmpty) Sq3.length.toFloat/Sq4.length.toFloat else 0F
})


问:
Get author names from CrossRef (get text out of JSON)
I'm trying to get the author names of this paper by using the CrossRef API with curl.

```<code>curl -LH "Accept: application/citeproc+json" http://dx.doi.org/10.3389/fpls.2011.00050 | jq .author
</code>```

Of course I get a JSON as response, but rather need pure text for further bash processing:

```<code>[
  {
    "given": "Fabio",
    "family": "Facchinelli",
    "affiliation": []
  },
  {
    "given": "Andreas P. M.",
    "family": "Weber",
    "affiliation": []
  }
]
</code>```

I thought of using jq, but couldn't figure out, how to just get:

"Fabio Facchinelli, Andreas P. M. Weber"

Do you know a solution (must not be jq)?

答:
Can do it with a sed script:

```<code>$ cat json.sed
/"given":/{
    s/^.*"given"://
    s/[",]//g
    h
}
/"family":/{
    s/^.*"family"://
    s/[",]//g
    G
    s/\n/, /
    p
}
</code>```

Then call it like this:

```<code>$ sed -n -f json.sed curl.json
 Facchinelli,  Fabio
 Weber,  Andreas P. M.
</code>```

Body:
I'm trying to get the author names of this paper by using the CrossRef API with curl.

curl -LH "Accept: application/citeproc+json" http://dx.doi.org/10.3389/fpls.2011.00050 | jq .author

Of course I get a JSON as response, but rather need pure text for further bash processing:

[
  {
    "given": "Fabio",
    "family": "Facchinelli",
    "affiliation": []
  },
  {
    "given": "Andreas P. M.",
    "family": "Weber",
    "affiliation": []
  }
]

I thought of using jq, but couldn't figure out, how to just get:

"Fabio Facchinelli, Andreas P. M. Weber"

Do you know a solution (must not be jq)?

Body:
Can do it with a sed script:

$ cat json.sed
/"given":/{
    s/^.*"given"://
    s/[",]//g
    h
}
/"family":/{
    s/^.*"family"://
    s/[",]//g
    G
    s/\n/, /
    p
}

Then call it like this:

$ sed -n -f json.sed curl.json
 Facchinelli,  Fabio
 Weber,  Andreas P. M.


问:
Send a JSON object to AJAX of jQuery Tabs using WordPress
I am using jQuery Tabs to program a messaging system using WordPress. The point is that when the user clicks one tab, which represents one conversation, an AJAX call is performed automatically with the functionality of jQuery Tabs.

I programmed the jQuery Tab to call an action (that I programmed as well). The action is programmed in PHP using WordPress and I can call it through localhost/mywebpage/wp-admin/admin-ajax.php?action=my_action.

The problem is the following: The default functionality of the jQuery tabs expects the raw output of the PHP file (the ajax action). This means I have to code HTML on the PHP file so I just put the response on the tabs panel (ui.panel.html). However I think this is inefficient and I would like to create a JSON object using WordPres function wp_send_json_success( jsonObject ) which is received on the ui.ajaxSettings.dataFilter function.

When I send HTML to the ui.ajaxSettings.dataFilter function, everything is correctly displayed on the jQuery tabs panel. But when I send a json success, I can see it on the console but I can't display it on the jQuery tabs panel. It appears for a millisecond and then disappears. So the JSON object is being received but for some reason can't be displayed. The only way something is displayed at the jQuery tabs panel is by sending raw HTML by my PHP function. Here is a very simple code example:

This is the JS function:

```<code>$( selector ).tabs( {
    beforeLoad: function( event, ui ) {
        ui.ajaxSettings.dataFilter = function( response ) {
            console.log( response );
            ui.panel.html( response );
    }
} );
</code>```

This is the PHP function that works good:

```<code><?php
    echo 'Hello World!';
</code>```

This is the PHP function that displays on the panel por a millisecond and then disappears.

```<code><?php
    wp_send_json_success( 'Hello World! );
</code>```

In my opinion, I think something else is executing and erasing what I have displayed on the ui.panel.html but I'm not that expert in jQuery tabs so if there is anyone out there with more experience that can tell me what it's going on I would really appreciate it.

答:
I got it working and the fix was obvious but I am still unsure if this is the best way to do it. This is what I did:</p>

```<code>var html = $( '<div>' ).addClass( 'wrapper' );

$( selector ).tabs( {
    beforeLoad: function( event, ui ) {
        ui.ajaxSettings.dataFilter = function( response ) {

            // Do whatever you want with the JSON object (obviously validations)
            // In my case I want to create HTML elements with info from the response
            var response_js_array = JSON.parse( response );

            html.append( $( '<div>' ).text( response_js_array['message'] ) );
    },
    load: function( event, ui ) {

        ui.panel.html( html );

        // Do also whatever you want after the messages have been loaded. In my case,
        // I scroll down to the last message
        scrollDown(); // This is also a function I programmed
    }
} );
</code>```

Body:
I am using jQuery Tabs to program a messaging system using WordPress. The point is that when the user clicks one tab, which represents one conversation, an AJAX call is performed automatically with the functionality of jQuery Tabs.

I programmed the jQuery Tab to call an action (that I programmed as well). The action is programmed in PHP using WordPress and I can call it through localhost/mywebpage/wp-admin/admin-ajax.php?action=my_action.

The problem is the following: The default functionality of the jQuery tabs expects the raw output of the PHP file (the ajax action). This means I have to code HTML on the PHP file so I just put the response on the tabs panel (ui.panel.html). However I think this is inefficient and I would like to create a JSON object using WordPres function wp_send_json_success( jsonObject ) which is received on the ui.ajaxSettings.dataFilter function.

When I send HTML to the ui.ajaxSettings.dataFilter function, everything is correctly displayed on the jQuery tabs panel. But when I send a json success, I can see it on the console but I can't display it on the jQuery tabs panel. It appears for a millisecond and then disappears. So the JSON object is being received but for some reason can't be displayed. The only way something is displayed at the jQuery tabs panel is by sending raw HTML by my PHP function. Here is a very simple code example:

This is the JS function:

$( selector ).tabs( {
    beforeLoad: function( event, ui ) {
        ui.ajaxSettings.dataFilter = function( response ) {
            console.log( response );
            ui.panel.html( response );
    }
} );

This is the PHP function that works good:

<?php
    echo 'Hello World!';

This is the PHP function that displays on the panel por a millisecond and then disappears.

<?php
    wp_send_json_success( 'Hello World! );

In my opinion, I think something else is executing and erasing what I have displayed on the ui.panel.html but I'm not that expert in jQuery tabs so if there is anyone out there with more experience that can tell me what it's going on I would really appreciate it.

Body:
I got it working and the fix was obvious but I am still unsure if this is the best way to do it. This is what I did:

var html = $( '<div>' ).addClass( 'wrapper' );

$( selector ).tabs( {
    beforeLoad: function( event, ui ) {
        ui.ajaxSettings.dataFilter = function( response ) {

            // Do whatever you want with the JSON object (obviously validations)
            // In my case I want to create HTML elements with info from the response
            var response_js_array = JSON.parse( response );

            html.append( $( '<div>' ).text( response_js_array['message'] ) );
    },
    load: function( event, ui ) {

        ui.panel.html( html );

        // Do also whatever you want after the messages have been loaded. In my case,
        // I scroll down to the last message
        scrollDown(); // This is also a function I programmed
    }
} );


问:
Subnet and IP address ANDing trailing 0's
So I have a script that is ANDing an IPv4 address and a subnet address. Not checking to see if it is a valid input (which I should add), it converts the input to binary.

```<code>if ($readInput -match "y"){
    $readIP = read-host "Please input an IPv4 address to be ANDed "

    # need to add subnet mask later.
    $readSub = read-host "Please input the Subnet Mask "

    #need to delimite '.'
    #$readIP.split "."
    #$readSub.split "."

    #need to join them

    #convert IPv4 address to binary, period seperated at each octet. (input ip, base 2)
    $binIP = [convert]::ToString($readIP,2)
    write-host "$binIP" -backgroundcolor "white" -foregroundcolor "black"
    ## need to have two 32 element array that compares each 1 and 0. loop through each one with a counter and compare them with
    ## conditional if statements

    #conditional statements for /cider notion to equal a binary number (mask, base 2)
    $binSub = [convert]::ToString($readSub,2)
    write-host "$binSub" -backgroundcolor "white" -foregroundcolor "black"
}
</code>```

The input is:

```<code>19216823
2552552550
</code>```

The output is:

```<code>1001001010011100110110111
10011000001001001101110001100110
</code>```

Do I have to add 7 trailing 0's at the end of the IP address in order to perform proper ANDing?

答:
It's usually easier to use the [IPAddress] class. Example:

```<code>$ip = [IPAddress] "192.168.32.76"
$networkMask = [IPAddress] "255.255.255.0"
$networkID = [IPAddress] ($ip.Address -band $networkMask.Address)
$networkID.IPAddressToString  # outputs "192.168.32.0"
</code>```

If you want to count the bits in a network mask string, you can use a function like this:

```<code>function ConvertTo-IPv4MaskBits {
  param(
    [parameter(Mandatory=$true)]
    [String] $MaskString
  )
  $mask = ([IPAddress] $MaskString).Address
  for ( $bitCount = 0; $mask -ne 0; $bitCount++ ) {
    $mask = $mask -band ($mask - 1)
  }
  $bitCount
}
</code>```

This function assumes a correctly formed network mask ID.

A full write-up and some more functions are available in an article I wrote a while back:

IT Pro Today - Working with IPv4 Addresses in PowerShell

Body:
So I have a script that is ANDing an IPv4 address and a subnet address. Not checking to see if it is a valid input (which I should add), it converts the input to binary.

if ($readInput -match "y"){
    $readIP = read-host "Please input an IPv4 address to be ANDed "

    # need to add subnet mask later.
    $readSub = read-host "Please input the Subnet Mask "

    #need to delimite '.'
    #$readIP.split "."
    #$readSub.split "."

    #need to join them

    #convert IPv4 address to binary, period seperated at each octet. (input ip, base 2)
    $binIP = [convert]::ToString($readIP,2)
    write-host "$binIP" -backgroundcolor "white" -foregroundcolor "black"
    ## need to have two 32 element array that compares each 1 and 0. loop through each one with a counter and compare them with
    ## conditional if statements

    #conditional statements for /cider notion to equal a binary number (mask, base 2)
    $binSub = [convert]::ToString($readSub,2)
    write-host "$binSub" -backgroundcolor "white" -foregroundcolor "black"
}

The input is:

19216823
2552552550

The output is:

1001001010011100110110111
10011000001001001101110001100110

Do I have to add 7 trailing 0's at the end of the IP address in order to perform proper ANDing?

Body:
It's usually easier to use the [IPAddress] class. Example:

$ip = [IPAddress] "192.168.32.76"
$networkMask = [IPAddress] "255.255.255.0"
$networkID = [IPAddress] ($ip.Address -band $networkMask.Address)
$networkID.IPAddressToString  # outputs "192.168.32.0"

If you want to count the bits in a network mask string, you can use a function like this:

function ConvertTo-IPv4MaskBits {
  param(
    [parameter(Mandatory=$true)]
    [String] $MaskString
  )
  $mask = ([IPAddress] $MaskString).Address
  for ( $bitCount = 0; $mask -ne 0; $bitCount++ ) {
    $mask = $mask -band ($mask - 1)
  }
  $bitCount
}

This function assumes a correctly formed network mask ID.

A full write-up and some more functions are available in an article I wrote a while back:

IT Pro Today - Working with IPv4 Addresses in PowerShell

ContentLicense: CC BY-SA 4.0


问:
Map dynamically array to nested object
I want to retrieve the form content on a submit and map that data into an object.

```<code>let userData = $(e.currentTarget).serializeArray();
let userDataObject = this.serializedToObject(userData);
</code>```

--
Template objects to send through POST

```<code>serializedToObject(serializedArray) {
        let templateObject = {
            privider: '',
            pop3: {
                host: '',
                port: 110,
                ssl: false
            },
            imap: {
                host: '',
                port: 993
            },

            email: '',
            password: ''
        };

        for (let data in serializedArray) {
        }

        return templateObject;
    }
</code>```

--
The form of the userData is

```<code>[Object, Object, Object, Object, Object, Object, Object]
</code>```

-- While on object is of form

```<code>Object: {
  name: 'provider',
  value: 'Aladin'
}

Object: {
  name: 'imap-host',
  value: '955'
}

Object: {
  name: 'imap-port',
  value:
}

Object: {
  email: 'test@gmail.com',
  value:
}
</code>```

So I need some help to map that array of objects to the templateObject.
AnyHelp will be highly appreciated.

Update

```<code>[{"name":"name","value":"Nicholas Barbaros"},{"name":"email","value":"george@google.com"},{"name":"password","value":"nicu121-mujik"},{"name":"imap","value":"imap.server.com"},{"name":"imap-port","value":"ad"},{"name":"pop3-host","value":"pop.server.com"},{"name":"pop3-port","value":"465"}, {"name":"pop3-ssl","value":"false"}]
</code>```

答:
The name-property of each serializedArray's object has a minus-character (-) representing nested objects, you can split by those characters and then set the values of your templateObject's properties:

var serializedArray = [{"name":"name","value":"Nicholas Barbaros"},{"name":"email","value":"george@google.com"},{"name":"password","value":"nicu121-mujik"},{"name":"imap","value":"imap.server.com"},{"name":"imap-port","value":"ad"},{"name":"pop3-host","value":"pop.server.com"},{"name":"pop3-port","value":"465"}, {"name":"pop3-ssl","value":"false"}];

// your defaults
var templateObject = {
    provider: '',
    pop3: {
        host: '',
        port: 110,
        ssl: false
    },
    imap: {
        host: '',
        port: 993
    },
    email: '',
    password: '',
};

serializedArray.forEach(function(obj) {
    var deep = obj.name.split('-');
    var key = deep.pop();

    var level = templateObject;
    deep.forEach(function(inner) {
        var nested = level[inner];
        var isObject = Object(nested) === nested;
        level = isObject ? nested : {};
    });

    level[key] = obj.value;
});

// return templateObject; // when inside your function
console.log(templateObject);```

Title: Map dynamically array to nested object

Body:
I want to retrieve the form content on a submit and map that data into an object.

let userData = $(e.currentTarget).serializeArray();
let userDataObject = this.serializedToObject(userData);

--
Template objects to send through POST

serializedToObject(serializedArray) {
        let templateObject = {
            privider: '',
            pop3: {
                host: '',
                port: 110,
                ssl: false
            },
            imap: {
                host: '',
                port: 993
            },

            email: '',
            password: ''
        };

        for (let data in serializedArray) {
        }

        return templateObject;
    }

--
The form of the userData is

[Object, Object, Object, Object, Object, Object, Object]

-- While on object is of form

Object: {
  name: 'provider',
  value: 'Aladin'
}

Object: {
  name: 'imap-host',
  value: '955'
}

Object: {
  name: 'imap-port',
  value:
}

Object: {
  email: 'test@gmail.com',
  value:
}

So I need some help to map that array of objects to the templateObject.
AnyHelp will be highly appreciated.

Update

[{"name":"name","value":"Nicholas Barbaros"},{"name":"email","value":"george@google.com"},{"name":"password","value":"nicu121-mujik"},{"name":"imap","value":"imap.server.com"},{"name":"imap-port","value":"ad"},{"name":"pop3-host","value":"pop.server.com"},{"name":"pop3-port","value":"465"}, {"name":"pop3-ssl","value":"false"}]


问:
Outlook HTML CSS transparent background in cell within table
* UPDATE * I should've been clearer and perhaps less verbose. The "Web" team w/in the company I work for sent me the HTML. As I said, due to windows (SSIS) -> unix (SAS) -> mainframe (EBCDIC), I can NOT use anything with a !, unless it's content, and then I have to hard code in the ASCII equivalent. So, to shorten my question -- I need to do a table with a nested table that has a background image, and white text on top. This solution needs to work on (nearly) all email & web browser platforms. (We don't care about really old, no longer supported, versions)

An alternate solution is if someone knows how to send the EBCDIC code assignment (5A) to pass and not get jacked, again windows->unix->mainframe. I know another team that sends x5A from SAS and it works. I'm really really trying to avoid ingesting the entire file into SAS just to do a find/replace, which would also likely screw up the fixed width file. But I could figure a way around that.
* /UPDATE *

I'm bashing my head against the wall here .. I'm writing up HTML to be used as content for emails - in one spot there's a table with a nested table -- the outside has an image, the inside has text (as in, like a text box).

I'm able to get it to work on everything (testing on EmailOnAcid) -- using rgba works, cept for ... yes outlook -- researching this (yay google) I now know Outlook doesn't support rgba. I've tried background-color:transparent. no joy. I've tried opacity:0, but that makes the text transparent (i feel like I'm close on that one, but missing something, maybe obvious)

p.s. don't ask my why the code I was given has 3 redundant references to the background jpg. This content was given to me, and now I have to manhandle it into something that'll work in my system.

Things I can't control -

I can't get them to make me an image with text over it, they're being weird about it.

Due to generating the text file which jumps from windows to unix to mainframe I can't use any ! that isn't email content. (i.e. no !important, no !-- comments , which means no if statements within the comment like [if gte mso 9], ...)

There's a new standard of CSS floating around - I'm not a fan. But other orgs w/in the company don't generate the email text files on a windows server -- they do it in SAS (unix/linux) then to mainframe -- so they can use the ebcdic codes. It just won't work if I do the same in my files. :(

Here's a chunk of the code (with the rgba) -- related css is below it

```<code> <table border="0" width="600" cellspacing="0" cellpadding="0" class="deviceWidth">
          <tbody>
            <tr>
              <td background="http://not.real.path/something.jpg" bgcolor="#c8c7bc" valign="top" width="600" height="258" style="background-image: url(http://not.real.path/something.jpg) no-repeat center center;" id="heroImg" >

                   <div id="txtCntr">
                     <table border="0" width="340" cellspacing="0" cellpadding="0" style="margin:50px 5px 10px 25px;display:block;" class="heroTxtTbl">
                        <tr>
                          <td align="left" valign="middle" style="display:block; background-color:rgba(0, 0, 0, 0);">

                        <p href="#" style="margin:0;padding:5px 0;font-size:45px; line-height: 48px; color: #ffffff; font-family: Arial, Myriad, Helvetica, sans-serif;text-decoration: none;font-weight: bold;" class="heroTxt">We will<br>do something<br>really amazing.</p>
                            </td>
                         </tr>
                       </table>

                  </div>
                </td>
            </tr>
          </tbody>
        </table>
</code>```

The background css parts ar:

```<code><style>
.deviceWidth {
width:100% ;
height:auto
}
#heroImg {
display:block;
background-image:url("http://not.real.path/something.jpg");
width:100%;
height: 250px;
padding:0;
}
.heroTxt {
font-size: 38px ;
line-height: 40px ;
}
.heroTxtTbl {
width: 80% ;
float: left;
margin:50px 5px 10px 25px;
display:block;
}
.heroTxtEmp {
font-size: 17px ;
line-height: 22px ;
}
#txtCntr {
padding:5px;
}
</code>```

Thanks in advance for any help

答:
Okay, Soo .. I didn't know if the v:rect, v:textbox things would work on their own, without the IF
We tried it

```<code><v:rect xmlns:v="urn:schemas-microsoft-com:vml" fill="true" stroke="false" style="width:600px;height:258px;">
   <v:fill type="tile"src="http://navient.com/assets/images/email/pcc/NVT-17-14574_PCC_hero.jpg" color="#c8c7bc" />
       <v:textbox inset="0,0,0,0" style="v-text-anchor:middle">

blah blah tables and text and pix

                  </v:textbox>
                </v:rect>
</code>```

and it worked. It didn't seem to corrupt other email clients (tested via emailonacid) ... so we're going with it.

=)

Body:
* UPDATE * I should've been clearer and perhaps less verbose. The "Web" team w/in the company I work for sent me the HTML. As I said, due to windows (SSIS) -> unix (SAS) -> mainframe (EBCDIC), I can NOT use anything with a !, unless it's content, and then I have to hard code in the ASCII equivalent. So, to shorten my question -- I need to do a table with a nested table that has a background image, and white text on top. This solution needs to work on (nearly) all email & web browser platforms. (We don't care about really old, no longer supported, versions)

An alternate solution is if someone knows how to send the EBCDIC code assignment (5A) to pass and not get jacked, again windows->unix->mainframe. I know another team that sends x5A from SAS and it works. I'm really really trying to avoid ingesting the entire file into SAS just to do a find/replace, which would also likely screw up the fixed width file. But I could figure a way around that.
* /UPDATE *

I'm bashing my head against the wall here .. I'm writing up HTML to be used as content for emails - in one spot there's a table with a nested table -- the outside has an image, the inside has text (as in, like a text box).

I'm able to get it to work on everything (testing on EmailOnAcid) -- using rgba works, cept for ... yes outlook -- researching this (yay google) I now know Outlook doesn't support rgba. I've tried background-color:transparent. no joy. I've tried opacity:0, but that makes the text transparent (i feel like I'm close on that one, but missing something, maybe obvious)

p.s. don't ask my why the code I was given has 3 redundant references to the background jpg. This content was given to me, and now I have to manhandle it into something that'll work in my system.

Things I can't control -

I can't get them to make me an image with text over it, they're being weird about it.

Due to generating the text file which jumps from windows to unix to mainframe I can't use any ! that isn't email content. (i.e. no !important, no !-- comments , which means no if statements within the comment like [if gte mso 9], ...)

There's a new standard of CSS floating around - I'm not a fan. But other orgs w/in the company don't generate the email text files on a windows server -- they do it in SAS (unix/linux) then to mainframe -- so they can use the ebcdic codes. It just won't work if I do the same in my files. :(

Here's a chunk of the code (with the rgba) -- related css is below it

We will
do something
really amazing.

The background css parts ar:

Body:
Okay, Soo .. I didn't know if the v:rect, v:textbox things would work on their own, without the IF
We tried it

<v:rect xmlns:v="urn:schemas-microsoft-com:vml" fill="true" stroke="false" style="width:600px;height:258px;">
   <v:fill type="tile"src="http://navient.com/assets/images/email/pcc/NVT-17-14574_PCC_hero.jpg" color="#c8c7bc" />
       <v:textbox inset="0,0,0,0" style="v-text-anchor:middle">

blah blah tables and text and pix

                  </v:textbox>
                </v:rect>

and it worked. It didn't seem to corrupt other email clients (tested via emailonacid) ... so we're going with it.

=)


问:
Increase number every 7 days in PHP
I select the date range from Input field for ex:

```<code><?php

    $Startdate = '2017-06-12'; // date format Y-m-d
    $Enddate = '2017-06-17';
    Number = 1;

?>
</code>```

For example if I select the above date range or any date between above range the number should be 1; when I change the range for next 7 days or any date between next 7 days the number should be 2 and so on.

答:
By using following code you can get days between dates and implement your logic.  </p>

```<code><?php
$Startdate = '2017-06-12';
$Enddate = '2017-06-17';

$date1=date_create($Startdate);
$date2=date_create($Enddate);
$diff=date_diff($date1,$date2);

$days = $diff->format('%a');

echo $days;
?>
</code>```

Title: Increase number every 7 days in PHP

Body:
I select the date range from Input field for ex:

<?php

    $Startdate = '2017-06-12'; // date format Y-m-d
    $Enddate = '2017-06-17';
    Number = 1;

?>

For example if I select the above date range or any date between above range the number should be 1; when I change the range for next 7 days or any date between next 7 days the number should be 2 and so on.

Body:
By using following code you can get days between dates and implement your logic.

<?php
$Startdate = '2017-06-12';
$Enddate = '2017-06-17';

$date1=date_create($Startdate);
$date2=date_create($Enddate);
$diff=date_diff($date1,$date2);

$days = $diff->format('%a');

echo $days;
?>


问:
How can I add a control derived from TabPage to a TabControl through the Windows Forms Designer?
I'm new to C# and Visual Studio. I have some experience working with Java before. So I want to create a class (e.g. MyTabPage) which extends TabPage and contains some predefined elements, so I can just add it to a TabControl collection. Is there a way to set this custom TabPage with the Windows Forms designer?</p>

答:
As mentioned in the comments on this question, I don't think this is possible. I think the Windows Forms designer code for the TabControl is only aware of the base TabPage class. You will likely have to set this up in code yourself. If you do something like this in your form's constructor Load event, you should get something similar to what you're trying to do:

```<code>Dim tabPageToAdd As New MyTabPage()
theTabControl.TabPages.Add(tabPageToAdd)
</code>```

This makes use of the TabControl.TabPageCollection.Add(TabPage) method.

Body:
As mentioned in the comments on this question, I don't think this is possible. I think the Windows Forms designer code for the TabControl is only aware of the base TabPage class. You will likely have to set this up in code yourself. If you do something like this in your form's constructor Load event, you should get something similar to what you're trying to do:

Dim tabPageToAdd As New MyTabPage()
theTabControl.TabPages.Add(tabPageToAdd)

This makes use of the TabControl.TabPageCollection.Add(TabPage) method.


问:
Is there a better way to block property overloading?
```<code><?php
class Item {
 public function __set($name, $value){
  throw new Exception('Overloading is forbidden.');
 }

 public function __get($name){
  throw new Exception('Overloading is forbidden.');
 }
}
</code>```

<p>I want to make sure I set all required object properties, but if I mistype a property name PHP just adds a new property and the prop I wanted to initialize remains null. </p>

答:
Just using the constructor will not solve the problem.
The problem he describes is very common and throwing an exception if __get or __set are called is a nice idea.
If you want to, you can make those final but I see no reason why you should do this. Only classes that require dynamic propertys will override  the methods.
The only improvement I can suggest is enclosing the method definitions in
//DEBUG
and
///
When you are finished debugging you can then easily run a replace(//*DEBUG with /*DEBUG) on all your code files and comment out __get and __set

Body:
<?php
class Item {
 public function __set($name, $value){
  throw new Exception('Overloading is forbidden.');
 }

 public function __get($name){
  throw new Exception('Overloading is forbidden.');
 }
}

I want to make sure I set all required object properties, but if I mistype a property name PHP just adds a new property and the prop I wanted to initialize remains null.


问:
jQuery create new Array with doubling old one
i have problem where i need to make array from input but each input char need to be doubled in array. for example if input is ABC array need to result in AABBCC.
so i end up with this code

```<code>if (hex.length < 6) {
    hex.splice(hex.indexOf(hex[i]) + 1, 0, hex[i]);
}
</code>```

if input is ABC it will output AABBCC

if input is AAB it will output AAAABB

but if first and last character is same like ABA it will end up AAABBA. Why is that?

答:
This is a perfect opportunity to use .map():

var hex = 'ABC';

var doubledHex = Array.from(hex).map(function(i) {
  return i + i;
}).join('');

console.log(hex);
console.log(doubledHex);```

Body:
i have problem where i need to make array from input but each input char need to be doubled in array. for example if input is ABC array need to result in AABBCC.
so i end up with this code

if (hex.length < 6) {
    hex.splice(hex.indexOf(hex[i]) + 1, 0, hex[i]);
}

if input is ABC it will output AABBCC

if input is AAB it will output AAAABB

but if first and last character is same like ABA it will end up AAABBA. Why is that?