问:
@Override doesn´t work for a method but for others
I don´t know why I can not override one method but other I can for others.

Here is the method I want to override in another class (without extending the class with the method):

```<code>public static void onOk() throws Exception {
    throw new Exception("test");
}
</code>```

I am trying to override but it says "Annotation not allowed here" but below the method are a lot of other methods whose get just overridden.

```<code>@Override  <- red underlined error "Annotation not allowed here"
InputAdressDialogFragment.onOk(){
}

@Override  <- works! The compiler accepts
    public View onCreateView(
</code>```

答:
A class Child where  Child extends Parent can only override methods defined in its super class Parent which are non static.

In the static context there is no implicit reference of current object (this) as static methods do not need any object upon which to invoke like normal non static methods. Static methods are not object based but based on class.

Body:
I don´t know why I can not override one method but other I can for others.

Here is the method I want to override in another class (without extending the class with the method):

public static void onOk() throws Exception {
    throw new Exception("test");
}

I am trying to override but it says "Annotation not allowed here" but below the method are a lot of other methods whose get just overridden.

@Override  <- red underlined error "Annotation not allowed here"
InputAdressDialogFragment.onOk(){
}

@Override  <- works! The compiler accepts
    public View onCreateView(


来源: stackexchange

问:
Ionic2: backbutton disabled after login
Ionic2: When user login it redirect to dashboard but if he used backbutton they redirect to login. How to restricted to backbutton to not redirect user to login. And also when user logout backbutton again route to dashboard. please help me!</p>

答:
how are you redirecting the user to the dashboard? I think you are using push() from navCtrl. If that is the case, then try using setRoot() from navController like this,

```<code>this.navCtrl.setRoot(DashboardPage);
</code>```

This helps you in removing the back button

ContentLicense: CC BY-SA 3.0

Title: Ionic2: backbutton disabled after login

Body:
how are you redirecting the user to the dashboard? I think you are using push() from navCtrl. If that is the case, then try using setRoot() from navController like this,

this.navCtrl.setRoot(DashboardPage);

This helps you in removing the back button


问:
Issues with gradle build in android studio
This is the situation:

I deleted app.impl and build.properties in my project. I used to do this all the time, but now when I rebuild gradle project, only app.impl is created, build.properties is missing.

When I navigate in application, in certain scenarios I get the following error:

```<code>07-04 10:38:37.784 14201-14201/net.-.- E/AndroidRuntime: FATAL EXCEPTION: main
                                                                    Process: net.-.-, PID: 14201
                                                                    java.lang.NoSuchFieldError: No field scrollView of type I in class Landroid/support/v7/appcompat/R$id; or its superclasses (declaration of 'android.support.v7.appcompat.R$id' appears in /data/app/net.dycode.eorder2-1/split_lib_slice_2_apk.apk)
                                                                        at android.support.v7.app.AlertController.setupContent(AlertController.java:675)
                                                                        at android.support.v7.app.AlertController.setupView(AlertController.java:463)
                                                                        at android.support.v7.app.AlertController.installContent(AlertController.java:215)
                                                                        at android.support.v7.app.AlertDialog.onCreate(AlertDialog.java:257)
                                                                        at android.app.Dialog.dispatchOnCreate(Dialog.java:395)
                                                                        at android.app.Dialog.show(Dialog.java:294)
                                                                        at android.app.DialogFragment.onStart(DialogFragment.java:502)
                                                                        at net.dycode.eorder2.dialog.AlertDialogFragment.onStart(AlertDialogFragment.java:48)
</code>```

What I have tried:

checking out different branch (granted it worked correctly before)

cleaning project

rebuilding project

making project

making app

I also tried updating android studio and it's SDK. Now there are no available updates.

答:
```<code>try this
->clean project
->delete build folder
->rebuilding project
</code>```

or try this command from terminal

```<code>gradlew clean
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is the situation:

I deleted app.impl and build.properties in my project. I used to do this all the time, but now when I rebuild gradle project, only app.impl is created, build.properties is missing.

When I navigate in application, in certain scenarios I get the following error:

07-04 10:38:37.784 14201-14201/net.-.- E/AndroidRuntime: FATAL EXCEPTION: main
                                                                    Process: net.-.-, PID: 14201
                                                                    java.lang.NoSuchFieldError: No field scrollView of type I in class Landroid/support/v7/appcompat/R$id; or its superclasses (declaration of 'android.support.v7.appcompat.R$id' appears in /data/app/net.dycode.eorder2-1/split_lib_slice_2_apk.apk)
                                                                        at android.support.v7.app.AlertController.setupContent(AlertController.java:675)
                                                                        at android.support.v7.app.AlertController.setupView(AlertController.java:463)
                                                                        at android.support.v7.app.AlertController.installContent(AlertController.java:215)
                                                                        at android.support.v7.app.AlertDialog.onCreate(AlertDialog.java:257)
                                                                        at android.app.Dialog.dispatchOnCreate(Dialog.java:395)
                                                                        at android.app.Dialog.show(Dialog.java:294)
                                                                        at android.app.DialogFragment.onStart(DialogFragment.java:502)
                                                                        at net.dycode.eorder2.dialog.AlertDialogFragment.onStart(AlertDialogFragment.java:48)

What I have tried:

checking out different branch (granted it worked correctly before)

cleaning project

rebuilding project

making project

making app

I also tried updating android studio and it's SDK. Now there are no available updates.

Body:
try this
->clean project
->delete build folder
->rebuilding project

or try this command from terminal

gradlew clean


问:
Replicate Base64 decoding of Java in PL/SQL
I am trying to get the same result I am getting in Java when decoding a Base64 String (NVARCHAR2) in Oracle.

I do have the following String: N'AAECAwQFBgdNu+qx2ZcqsA==' which is basically a encrypted password packed into a Base64 encoding.

In Java I am doing this:

```<code>byte[] bytes = Base64.decodeBase64(testValue.getBytes());
for(byte b: bytes){
     System.out.print(String.valueOf(b & 0xFF) + " "); //Decimal (unsigned)
}
for(byte b: bytes){
     System.out.print(Integer.toHexString(b & 0xFF) + " "); //Hex
}
</code>```

which prints me following:

```<code>Unsigned: 0 1 2 3 4 5 6 7 77 187 234 177 217 151 42 176
Hex:      0 1 2 3 4 5 6 7 4d bb  ea  b1  d9  97  2a b0
</code>```

Now I want to replicate the Base64 decoding like it's made in Java. I am trying following in a PL/SQL-Function:

```<code>base64DecodedInput:= UTL_ENCODE.base64_decode(UTL_I18N.STRING_TO_RAW(valueToDecrypt, charset));
DBMS_OUTPUT.PUT_LINE ( 'Base64 decoded is: ' || base64DecodedInput);
</code>```

The charset is: AL16UTF16
and valueToDecrypt is the test String I mentioned above as NVARCHAR2(200)

The DBMS_OUTPUT prints me:

```<code>Base64 decoded is: 0000004200300105A8308FDD02FE02B11B7901EA02C0
</code>```

Which is wrong!...

What did I miss. Is PL/SQL not using url safe decoding or whatever?

I am stuck.

The code is part of a PL/SQL-Function:

```<code>CREATE OR REPLACE FUNCTION decodeBase64
(valueToDecrypt IN NVARCHAR2)
RETURN NVARCHAR2
AS
   --Declaration area
   charset VARCHAR(100);
   base64DecodedInput RAW(2000);
   ...
</code>```

And Server/Database Settings are:

```<code>NLS_RDBMS_VERSION   12.1.0.2.0
NLS_NCHAR_CONV_EXCP FALSE
NLS_LENGTH_SEMANTICS    BYTE
NLS_COMP    BINARY
NLS_DUAL_CURRENCY   $
NLS_TIMESTAMP_TZ_FORMAT DD-MON-RR HH.MI.SSXFF AM TZR
NLS_TIME_TZ_FORMAT  HH.MI.SSXFF AM TZR
NLS_TIMESTAMP_FORMAT    DD-MON-RR HH.MI.SSXFF AM
NLS_TIME_FORMAT HH.MI.SSXFF AM
NLS_SORT    BINARY
NLS_DATE_LANGUAGE   AMERICAN
NLS_DATE_FORMAT DD-MON-RR
NLS_CALENDAR    GREGORIAN
NLS_NUMERIC_CHARACTERS  .,
NLS_NCHAR_CHARACTERSET  AL16UTF16
NLS_CHARACTERSET    WE8MSWIN1252
NLS_ISO_CURRENCY    AMERICA
NLS_CURRENCY    $
NLS_TERRITORY   AMERICA
NLS_LANGUAGE    AMERICAN
</code>```

答:
A better approach to what @Wernfried answered would be to use conversion not casting.

As Java is printing UTF-8 values in this example you have to convert the NVARCHAR2 as well to UTF-8 before decoding it.

```<code>base64DecodedInput:= UTL_ENCODE.base64_decode(UTL_I18N.STRING_TO_RAW(valueToDecrypt, conversionCharset));
</code>```

Body:
I am trying to get the same result I am getting in Java when decoding a Base64 String (NVARCHAR2) in Oracle.

I do have the following String: N'AAECAwQFBgdNu+qx2ZcqsA==' which is basically a encrypted password packed into a Base64 encoding.

In Java I am doing this:

byte[] bytes = Base64.decodeBase64(testValue.getBytes());
for(byte b: bytes){
     System.out.print(String.valueOf(b & 0xFF) + " "); //Decimal (unsigned)
}
for(byte b: bytes){
     System.out.print(Integer.toHexString(b & 0xFF) + " "); //Hex
}

which prints me following:

Unsigned: 0 1 2 3 4 5 6 7 77 187 234 177 217 151 42 176
Hex:      0 1 2 3 4 5 6 7 4d bb  ea  b1  d9  97  2a b0

Now I want to replicate the Base64 decoding like it's made in Java. I am trying following in a PL/SQL-Function:

base64DecodedInput:= UTL_ENCODE.base64_decode(UTL_I18N.STRING_TO_RAW(valueToDecrypt, charset));
DBMS_OUTPUT.PUT_LINE ( 'Base64 decoded is: ' || base64DecodedInput);

The charset is: AL16UTF16
and valueToDecrypt is the test String I mentioned above as NVARCHAR2(200)

The DBMS_OUTPUT prints me:

Base64 decoded is: 0000004200300105A8308FDD02FE02B11B7901EA02C0

Which is wrong!...

What did I miss. Is PL/SQL not using url safe decoding or whatever?

I am stuck.

The code is part of a PL/SQL-Function:

CREATE OR REPLACE FUNCTION decodeBase64
(valueToDecrypt IN NVARCHAR2)
RETURN NVARCHAR2
AS
   --Declaration area
   charset VARCHAR(100);
   base64DecodedInput RAW(2000);
   ...

And Server/Database Settings are:

NLS_RDBMS_VERSION   12.1.0.2.0
NLS_NCHAR_CONV_EXCP FALSE
NLS_LENGTH_SEMANTICS    BYTE
NLS_COMP    BINARY
NLS_DUAL_CURRENCY   $
NLS_TIMESTAMP_TZ_FORMAT DD-MON-RR HH.MI.SSXFF AM TZR
NLS_TIME_TZ_FORMAT  HH.MI.SSXFF AM TZR
NLS_TIMESTAMP_FORMAT    DD-MON-RR HH.MI.SSXFF AM
NLS_TIME_FORMAT HH.MI.SSXFF AM
NLS_SORT    BINARY
NLS_DATE_LANGUAGE   AMERICAN
NLS_DATE_FORMAT DD-MON-RR
NLS_CALENDAR    GREGORIAN
NLS_NUMERIC_CHARACTERS  .,
NLS_NCHAR_CHARACTERSET  AL16UTF16
NLS_CHARACTERSET    WE8MSWIN1252
NLS_ISO_CURRENCY    AMERICA
NLS_CURRENCY    $
NLS_TERRITORY   AMERICA
NLS_LANGUAGE    AMERICAN

Body:
A better approach to what @Wernfried answered would be to use conversion not casting.

As Java is printing UTF-8 values in this example you have to convert the NVARCHAR2 as well to UTF-8 before decoding it.

base64DecodedInput:= UTL_ENCODE.base64_decode(UTL_I18N.STRING_TO_RAW(valueToDecrypt, conversionCharset));


答:
By definition, @Override is for overriding methods.

Static methods can't be overridden - see here for details.

That is one of the reasons why using static is regarded an abnormality in good OOP.

Title: @Override doesn´t work for a method but for others


问:
How to send message with @ID telegram using telethon library
I want send message with telethon but i dont have phone number this .
i have only @username Telegram.
with this code i can send message for my contact phone :

```<code>result = client.invoke(ImportContactsRequest([contact], replace=True))
contacts = client.invoke(GetContactsRequest(""))
for u in result.users:
    client.send_message(u, 'Hi')
</code>```

But i want send message to @username Telegram

答:
You can just do the following now:

```<code>client.send_message('username', 'hello')
</code>```

Old answer:

It's on the Project's wiki, quoted below.

Via ResolveUsernameRequest

An "entity" is used to refer to either an User or a Chat (which includes a Channel). Perhaps the most straightforward way to get these is by resolving their username:

```<code>from telethon.tl.functions.contacts import ResolveUsernameRequest

result = client.invoke(ResolveUsernameRequest('username'))
found_chats = result.chats
found_users = result.users
# result.peer may be a PeerUser, PeerChat or PeerChannel
</code>```

See Peer for more information about this result.

Body:
I want send message with telethon but i dont have phone number this .
i have only @username Telegram.
with this code i can send message for my contact phone :

result = client.invoke(ImportContactsRequest([contact], replace=True))
contacts = client.invoke(GetContactsRequest(""))
for u in result.users:
    client.send_message(u, 'Hi')

But i want send message to @username Telegram

Body:
You can just do the following now:

client.send_message('username', 'hello')

Old answer:

It's on the Project's wiki, quoted below.

Via ResolveUsernameRequest

An "entity" is used to refer to either an User or a Chat (which includes a Channel). Perhaps the most straightforward way to get these is by resolving their username:

from telethon.tl.functions.contacts import ResolveUsernameRequest

result = client.invoke(ResolveUsernameRequest('username'))
found_chats = result.chats
found_users = result.users
# result.peer may be a PeerUser, PeerChat or PeerChannel

See Peer for more information about this result.


问:
SimpleSchema and AutoForm: Render password field as single input
I'm working in a project where a "super admin" user can create another users, setting they usernames and passwords. I have an AutoForm quickForm rendering a form based upon the SimpleSchema attached to the Meteor.users collection (using Collection2).
Following the Collection2 docs recommendation on attaching a schema to the users collection, my schema looks like this:

```<code>Usuarios.schema = new SimpleSchema({
    ...
    username: {
        type: String,
    },
    services: {
        type: Object,
        optional: true,
        blackbox: true
    },
   "services.password": {
      type: String,
      optional: true,
      autoform: {
         type: 'password'
      }
    },
    ...
});
</code>```

The rendered form looks like this:

But I would like to have the Password field rendered like the Username one (without the Services panel).
I haven't found a workaround to this. I need to have the Services Object type atribute in the schema or the validation upon user insert fails (with Accounts.createUser()), and so, the panel is rendered (because of the Object type of the atribute).

Any ideas on how I could achieve the desired template rendering?

答:
Your password is part of the 'service' object, which is why it is automatically rendered inside a afObjectField when using quickForm or quickFields:

afObjectField

When you use the afQuickField component for a field that is an Object,
  it is rendered using the afObjectField component unless you override
  the type or specify options. This happens by default when you use a
  quickForm for a schema that has a field of type Object.

The afObjectField component renders all of an object field's subfields
  together as one group. The group is labeled with the name of the
  object field. The actual visual representation of the group will vary
  based on which theme template you use. For the "bootstrap3" default
  template, the group appears in a panel with a heading.

Solution A: Manual Form Rendering

To render your password as a single field, you need to set up your autForm manually and reference the fields by using afFieldInput. The form mthen may look like (not tested but code should look like) this:

{{> autoForm id="login" schema=Usuarios.schema}}
    {{> afFieldInput type="text" name="username"}}
    {{> afFieldInput type="password" name="services.password"}}
{{/autoForm}}
```

<p>Which has the advantage that your form looks exactly as you wish but has the disadvantage, that you have to add all extras (validation messages and stuff) manually.</p>

<p><strong>Solution B: Change your Schema</strong></p>

<p>When you pull password out of the service group, then you will have the same effect of auto-render as with username: a single input field.</p>

<pre class="lang-js prettyprint-override"><code>Usuarios.schema = new SimpleSchema({
    ...
    username: {
        type: String,
    },
    services: {
        type: Object,
        optional: true,
        blackbox: true
    },
    ...
   password: {
      type: String,
      optional: true,
      autoform: {
         type: 'password'
      }
    },
    ...
});
</code>```

Body:
I'm working in a project where a "super admin" user can create another users, setting they usernames and passwords. I have an AutoForm quickForm rendering a form based upon the SimpleSchema attached to the Meteor.users collection (using Collection2).
Following the Collection2 docs recommendation on attaching a schema to the users collection, my schema looks like this:

Usuarios.schema = new SimpleSchema({
    ...
    username: {
        type: String,
    },
    services: {
        type: Object,
        optional: true,
        blackbox: true
    },
   "services.password": {
      type: String,
      optional: true,
      autoform: {
         type: 'password'
      }
    },
    ...
});

The rendered form looks like this:

But I would like to have the Password field rendered like the Username one (without the Services panel).
I haven't found a workaround to this. I need to have the Services Object type atribute in the schema or the validation upon user insert fails (with Accounts.createUser()), and so, the panel is rendered (because of the Object type of the atribute).

Any ideas on how I could achieve the desired template rendering?

Body:
Your password is part of the 'service' object, which is why it is automatically rendered inside a afObjectField when using quickForm or quickFields:

afObjectField

When you use the afQuickField component for a field that is an Object,
  it is rendered using the afObjectField component unless you override
  the type or specify options. This happens by default when you use a
  quickForm for a schema that has a field of type Object.

The afObjectField component renders all of an object field's subfields
  together as one group. The group is labeled with the name of the
  object field. The actual visual representation of the group will vary
  based on which theme template you use. For the "bootstrap3" default
  template, the group appears in a panel with a heading.

Solution A: Manual Form Rendering

To render your password as a single field, you need to set up your autForm manually and reference the fields by using afFieldInput. The form mthen may look like (not tested but code should look like) this:

{{> autoForm id="login" schema=Usuarios.schema}}
    {{> afFieldInput type="text" name="username"}}
    {{> afFieldInput type="password" name="services.password"}}
{{/autoForm}}

Which has the advantage that your form looks exactly as you wish but has the disadvantage, that you have to add all extras (validation messages and stuff) manually.

Solution B: Change your Schema

When you pull password out of the service group, then you will have the same effect of auto-render as with username: a single input field.

Usuarios.schema = new SimpleSchema({
    ...
    username: {
        type: String,
    },
    services: {
        type: Object,
        optional: true,
        blackbox: true
    },
    ...
   password: {
      type: String,
      optional: true,
      autoform: {
         type: 'password'
      }
    },
    ...
});


问:
How to force to open JNLP File in Java 1.5.0_14 JRE instead of JRE 1.7
I have Java 5-based Java Web Start application which I need to open on a Windows PC. PC has JRE 1.7 installed, with JRE 1.5.0_14 copied manually to the another drive (d:). The problem is that whenever I want to open the JW Start application, it opens using Java 7. Even if I use the javaws executable from JRE 1.5.0_14, somehow  some properties still refer to JRE 7 files. How can I force JRE 1.5.0_14 to run just for this application?

Thanks in advance & Best Regards.

Edit 1: By the way, I forgot to mention that I need to use java 1.7 for my another app. in order to use e-sign app.

Edit 2: The JNLP file has alredy this code inside <j2se java-vm-args="-XX:MaxPermSize=128m -Xmx512m" version="1.5"/>

答:
Here is what I do to solve my issue;

Uninstall the older Java -if there is- (in my case it is 1.5.0_14 )

install java equal/higher than 1.7 just to run e-sign on my web application

I prepared a VBScript in order to just run the desired jre version as follows and put jre1.5.0_14, jnlp file and VBScript on the same folder and make shortcut to the VBScript to run.

Set oShell = WScript.CreateObject("WSCript.shell")
oShell.run "%comspec% /c D:\TMS\jre1.5.0_14\bin\javaws.exe D:\TMS\tt.jnlp -verbose", 1, True

Set oShell = Nothing

Thats it :)


问:
Using momentjs, getting different result locally vs on Azure
he test code:

```<code>var c = moment().tz('America/New_York');
console.log('c.format: ' + c.format());

var b = moment([c.year(), c.month(), c.date(), c.hours(), c.minutes()]).tz('America/Chicago');
console.log("b.format: " + b.format());
</code>```

When I run this code locally, I get:

```<code>c.format: 2017-07-03T16:33:42-04:00
b.format: 2017-07-03T16:33:00-05:00
</code>```

This is what I expect (and want) to happen. Basically I just want to take a time and change the offset without changing the actual time. However, when I run that same code through my Azure hosted app, the output is this:

```<code>c.format: 2017-07-03T16:43:16-04:00
b.format: 2017-07-03T11:43:00-05:00
</code>```

Both the local and Azure apps are running the same node version (8.0.0), as well as moment (2.18.1) and moment-timezone (0.5.13).

Anyone have any ideas what could be causing this? Thanks!

答:
As the docs says:

By default, moment parses and displays in local time.

For your b variable you are creating a moment object using c.year(), c.month(), c.date(), c.hours(), c.minutes() as local time, so the result of converting b to America/Chicago timezone will be system dependent.

You can use moment.tz to create a moment object specifying timezone (e.g. America/New_York), in your case, something like:

```<code>moment.tz([c.year(), c.month(), c.date(), c.hours(), c.minutes()], 'America/New_York')
</code>```

Here a snippet to show live results in the different cases:

// Current time in New York
var c = moment().tz('America/New_York');
console.log('c.format: ' + c.format());

// Create a local moment object for the current time in New York
var mLocal = moment([c.year(), c.month(), c.date(), c.hours(), c.minutes()]);
console.log("mLocal.format: " + mLocal.format());

// Convert local moment to America/Chicago timezone
var b = mLocal.tz('America/Chicago');
console.log("b.format: " + b.format());

// Create moment object for the current time in New York
// specifying timezone and then converting to America/Chicago timezone
var b1 = moment.tz([c.year(), c.month(), c.date(), c.hours(), c.minutes()], 'America/New_York').tz('America/Chicago');
console.log("b1.format: " + b1.format());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.13/moment-timezone-with-data-2012-2022.min.js"></script></code>```

Body:
he test code:

var c = moment().tz('America/New_York');
console.log('c.format: ' + c.format());

var b = moment([c.year(), c.month(), c.date(), c.hours(), c.minutes()]).tz('America/Chicago');
console.log("b.format: " + b.format());

When I run this code locally, I get:

c.format: 2017-07-03T16:33:42-04:00
b.format: 2017-07-03T16:33:00-05:00

This is what I expect (and want) to happen. Basically I just want to take a time and change the offset without changing the actual time. However, when I run that same code through my Azure hosted app, the output is this:

c.format: 2017-07-03T16:43:16-04:00
b.format: 2017-07-03T11:43:00-05:00

Both the local and Azure apps are running the same node version (8.0.0), as well as moment (2.18.1) and moment-timezone (0.5.13).

Anyone have any ideas what could be causing this? Thanks!

Body:
As the docs says:

By default, moment parses and displays in local time.

For your b variable you are creating a moment object using c.year(), c.month(), c.date(), c.hours(), c.minutes() as local time, so the result of converting b to America/Chicago timezone will be system dependent.

You can use moment.tz to create a moment object specifying timezone (e.g. America/New_York), in your case, something like:

moment.tz([c.year(), c.month(), c.date(), c.hours(), c.minutes()], 'America/New_York')

Here a snippet to show live results in the different cases:

// Current time in New York
var c = moment().tz('America/New_York');
console.log('c.format: ' + c.format());

// Create a local moment object for the current time in New York
var mLocal = moment([c.year(), c.month(), c.date(), c.hours(), c.minutes()]);
console.log("mLocal.format: " + mLocal.format());

// Convert local moment to America/Chicago timezone
var b = mLocal.tz('America/Chicago');
console.log("b.format: " + b.format());

// Create moment object for the current time in New York
// specifying timezone and then converting to America/Chicago timezone
var b1 = moment.tz([c.year(), c.month(), c.date(), c.hours(), c.minutes()], 'America/New_York').tz('America/Chicago');
console.log("b1.format: " + b1.format());

<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.13/moment-timezone-with-data-2012-2022.min.js"></script>


问:
How to convert list of filepaths to a JSON object in Java
I've a requirement to convert a set of file structure obtained from DB into a JSON.
For example:
From DB, I get the following path and file attributes:

```<code>Record 1:
    "path": "/sd/card/camera/pics/selfie.jpg"
    "fileName": "selfie.jpg",
    "mimeType": "image/jpeg"

Record 2:
    "path": "/sd/card/camera/pics/personal/selfie1.jpg"
    "fileName": "selfie1.jpg",
    "mimeType": "image/jpeg"
</code>```

and so on..
I need to convert this to a JSON like:

```<code> [{
    "sd": [{
        "card": [{
            "camera": [{
                "pics": [{
                        "fileName": "selfie.jpg",
                        "path": "/sd/card/camera/pics/selfie.jpg",
                        "mimeType": "image/jpeg"
                    },
                    {
                        "personal": [{
                            "fileName": "selfie1.jpg",
                            "path": "/sd/card/camera/pics/personal/selfie1.jpg",
                            "mimeType": "image/jpeg"
                        }]
                    }
                ]
            }]
        }]
    }]
}]
</code>```

答:
I'm going to give you a 'jackson' solution.

First, build an object (or more, I let you deal with the Java inheritance, or use any kind of structure you want to use).
Like this one by example :

```<code> @JsonSerialize(using = CustomSerializer.class)
public class Something {

    private String currentFolder; // Name of the folder if this instance of something is a folder
    private Something[] childs;

    private Map<String,String> currentPicture; // Picture properties if this instance of something is a picture

    public Something() {currentPicture = new HashMap<String,String>();}

    public Something[] getChilds() {
        return childs;
    }

    public void setContent(Something[] _childs) {this.childs = _childs;}
    public String getCurrentFolder() {return currentFolder;}
    public void setCurrentFolder(String _currentFolder) {this.currentFolder = _currentFolder;}
    public Map<String,String> getCurrentPicture() {return currentPicture;}
    public void setCurrentPicture(Map<String,String> currentPicture) {this.currentPicture = currentPicture;}
}
</code>```

Then, create the CustomSerializer, that will help you do whatever you want to do :

```<code>    public class CustomSerializer extends JsonSerializer<Something>{

    @Override
    public void serialize(Something value, JsonGenerator jgen, SerializerProvider provider)
            throws IOException, JsonProcessingException {
        jgen.writeStartObject();
        // Adding the folder into the json, only if it exists
        if(value.getCurrentFolder()!=null){
            jgen.writeObjectField(value.getCurrentFolder(), value.getChilds());
        }

        // Adding properties of the picture, only if they exist
        if(value.getCurrentPicture()!= null){
            for(String k : value.getCurrentPicture().keySet()){
                jgen.writeObjectField(k,value.getCurrentPicture().get(k));
            }
        }
        jgen.writeEndObject();
    }

}
</code>```

Finally (I've not done this one, but you'll do it I'm sure !) create a mapper from what you read to the "Something" class.
I build the object manually here (quickly, so it's not clean):

```<code>public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
    Something s = new Something();
    s.setCurrentFolder("toto");
    Something s2 = new Something();
    s2.setCurrentFolder("tata");

    Something s2bis = new Something();
    s2bis.setCurrentFolder("tataBis");

    Something[] s2Group = {s2bis};
    s2.setContent(s2Group);
    Something s2bispic = new Something();
    s2bispic.getCurrentPicture().put("fileName", "ThatPictureOfMysSelfILikeSoMuch.jpg");
    s2bispic.getCurrentPicture().put("path", "toto/tata/tataBis/ThatPictureOfMysSelfILikeSoMuch.jpg");
    s2bispic.getCurrentPicture().put("mimeType", "image/jpeg");

    Something s2bispic2 = new Something();
    s2bispic2.getCurrentPicture().put("fileName", "ThatPictureOfMysSelfIDontLike.jpg");
    s2bispic2.getCurrentPicture().put("path", "toto/tata/tataBis/ThatPictureOfMysSelfIDontLike.jpg");
    s2bispic2.getCurrentPicture().put("mimeType", "image/jpeg");

    Something[] s2BisGroup = {s2bispic,s2bispic2};
    s2bis.setContent(s2BisGroup);
    Something s3 = new Something();

    s3.getCurrentPicture().put("fileName", "selfie.jpg");
    s3.getCurrentPicture().put("path", "toto/selfie.jpg");
    s3.getCurrentPicture().put("mimeType", "image/jpeg");

    Something[] sGroup = {s2,s3};
    s.setContent(sGroup);

    ObjectMapper mapper = new ObjectMapper();
    String temp = mapper.writeValueAsString(s);
    System.out.println(temp);
}
</code>```

And this is what I get :

```<code>    {
   "toto":[
      {
         "tata":[
            {
               "tataBis":[
                  {
                     "path":"toto/tata/tataBis/ThatPictureOfMysSelfILikeSoMuch.jpg",
                     "fileName":"ThatPictureOfMysSelfILikeSoMuch.jpg",
                     "mimeType":"image/jpeg"
                  },
                  {
                     "path":"toto/tata/tataBis/ThatPictureOfMysSelfIDontLike.jpg",
                     "fileName":"ThatPictureOfMysSelfIDontLike.jpg",
                     "mimeType":"image/jpeg"
                  }
               ]
            }
         ]
      },
      {
         "path":"toto/selfie.jpg",
         "fileName":"selfie.jpg",
         "mimeType":"image/jpeg"
      }
   ]
}
</code>```

Regards,

Body:
I've a requirement to convert a set of file structure obtained from DB into a JSON.
For example:
From DB, I get the following path and file attributes:

Record 1:
    "path": "/sd/card/camera/pics/selfie.jpg"
    "fileName": "selfie.jpg",
    "mimeType": "image/jpeg"

Record 2:
    "path": "/sd/card/camera/pics/personal/selfie1.jpg"
    "fileName": "selfie1.jpg",
    "mimeType": "image/jpeg"

and so on..
I need to convert this to a JSON like:

 [{
    "sd": [{
        "card": [{
            "camera": [{
                "pics": [{
                        "fileName": "selfie.jpg",
                        "path": "/sd/card/camera/pics/selfie.jpg",
                        "mimeType": "image/jpeg"
                    },
                    {
                        "personal": [{
                            "fileName": "selfie1.jpg",
                            "path": "/sd/card/camera/pics/personal/selfie1.jpg",
                            "mimeType": "image/jpeg"
                        }]
                    }
                ]
            }]
        }]
    }]
}]

Body:
I'm going to give you a 'jackson' solution.

First, build an object (or more, I let you deal with the Java inheritance, or use any kind of structure you want to use).
Like this one by example :

 @JsonSerialize(using = CustomSerializer.class)
public class Something {

    private String currentFolder; // Name of the folder if this instance of something is a folder
    private Something[] childs;

    private Map<String,String> currentPicture; // Picture properties if this instance of something is a picture

    public Something() {currentPicture = new HashMap<String,String>();}

    public Something[] getChilds() {
        return childs;
    }

    public void setContent(Something[] _childs) {this.childs = _childs;}
    public String getCurrentFolder() {return currentFolder;}
    public void setCurrentFolder(String _currentFolder) {this.currentFolder = _currentFolder;}
    public Map<String,String> getCurrentPicture() {return currentPicture;}
    public void setCurrentPicture(Map<String,String> currentPicture) {this.currentPicture = currentPicture;}
}

Then, create the CustomSerializer, that will help you do whatever you want to do :

    public class CustomSerializer extends JsonSerializer<Something>{

    @Override
    public void serialize(Something value, JsonGenerator jgen, SerializerProvider provider)
            throws IOException, JsonProcessingException {
        jgen.writeStartObject();
        // Adding the folder into the json, only if it exists
        if(value.getCurrentFolder()!=null){
            jgen.writeObjectField(value.getCurrentFolder(), value.getChilds());
        }

        // Adding properties of the picture, only if they exist
        if(value.getCurrentPicture()!= null){
            for(String k : value.getCurrentPicture().keySet()){
                jgen.writeObjectField(k,value.getCurrentPicture().get(k));
            }
        }
        jgen.writeEndObject();
    }

}

Finally (I've not done this one, but you'll do it I'm sure !) create a mapper from what you read to the "Something" class.
I build the object manually here (quickly, so it's not clean):

public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
    Something s = new Something();
    s.setCurrentFolder("toto");
    Something s2 = new Something();
    s2.setCurrentFolder("tata");

    Something s2bis = new Something();
    s2bis.setCurrentFolder("tataBis");

    Something[] s2Group = {s2bis};
    s2.setContent(s2Group);
    Something s2bispic = new Something();
    s2bispic.getCurrentPicture().put("fileName", "ThatPictureOfMysSelfILikeSoMuch.jpg");
    s2bispic.getCurrentPicture().put("path", "toto/tata/tataBis/ThatPictureOfMysSelfILikeSoMuch.jpg");
    s2bispic.getCurrentPicture().put("mimeType", "image/jpeg");

    Something s2bispic2 = new Something();
    s2bispic2.getCurrentPicture().put("fileName", "ThatPictureOfMysSelfIDontLike.jpg");
    s2bispic2.getCurrentPicture().put("path", "toto/tata/tataBis/ThatPictureOfMysSelfIDontLike.jpg");
    s2bispic2.getCurrentPicture().put("mimeType", "image/jpeg");

    Something[] s2BisGroup = {s2bispic,s2bispic2};
    s2bis.setContent(s2BisGroup);
    Something s3 = new Something();

    s3.getCurrentPicture().put("fileName", "selfie.jpg");
    s3.getCurrentPicture().put("path", "toto/selfie.jpg");
    s3.getCurrentPicture().put("mimeType", "image/jpeg");

    Something[] sGroup = {s2,s3};
    s.setContent(sGroup);

    ObjectMapper mapper = new ObjectMapper();
    String temp = mapper.writeValueAsString(s);
    System.out.println(temp);
}

And this is what I get :

    {
   "toto":[
      {
         "tata":[
            {
               "tataBis":[
                  {
                     "path":"toto/tata/tataBis/ThatPictureOfMysSelfILikeSoMuch.jpg",
                     "fileName":"ThatPictureOfMysSelfILikeSoMuch.jpg",
                     "mimeType":"image/jpeg"
                  },
                  {
                     "path":"toto/tata/tataBis/ThatPictureOfMysSelfIDontLike.jpg",
                     "fileName":"ThatPictureOfMysSelfIDontLike.jpg",
                     "mimeType":"image/jpeg"
                  }
               ]
            }
         ]
      },
      {
         "path":"toto/selfie.jpg",
         "fileName":"selfie.jpg",
         "mimeType":"image/jpeg"
      }
   ]
}

Regards,


问:
X-Frame-Options: .htaccess vs httpd.conf
In httpd.conf (Unix / Mac OS Sierra) I've got "Header set X-Frame-Options SAMEORIGIN"

I'd like to override that for a specific directory to
X-Frame-Options ALLOW-FROM SpecificDomain.com

Goal is to allow iframe acess to that directory but no others.

I tried adding the  ALLOW-FROM line to an .htaccess file in the target directory but no luck.  iFrame is denied, browser console saying "X-Frame-Options" are set to "SAMEORIGIN"

答:
There are compatibility issues with some browsers with the Allow-From parameter for X-Frame-Options response header, chances are you are dealing with a browser which does not support it.

Ideally try this command to see the headers output and make sure the setting you made is being used:

```<code>curl -I http://yourserver.example.com/exceptionpath/
</code>```

If it is, instead of setting that other header you may also want to unset that header in that directory to avoid compatibility issues with that parameter:

```<code>Header unset X-Frame-Options
</code>```

or if the above is not being applied:

```<code>Header always unset X-Frame-Options
</code>```

Sidenote: If you are the admin of the site you don't need to use .htaccess if you have access to main configuration files, set in the appropiate Directory entry instead. Disable .htaccess files altogether with AllowOverride none. Configurations will be simpler and you will gain a bit of performance by not forcing httpd to constantly read that file several times with each hit.

Body:
There are compatibility issues with some browsers with the Allow-From parameter for X-Frame-Options response header, chances are you are dealing with a browser which does not support it.

Ideally try this command to see the headers output and make sure the setting you made is being used:

curl -I http://yourserver.example.com/exceptionpath/

If it is, instead of setting that other header you may also want to unset that header in that directory to avoid compatibility issues with that parameter:

Header unset X-Frame-Options

or if the above is not being applied:

Header always unset X-Frame-Options

Sidenote: If you are the admin of the site you don't need to use .htaccess if you have access to main configuration files, set in the appropiate Directory entry instead. Disable .htaccess files altogether with AllowOverride none. Configurations will be simpler and you will gain a bit of performance by not forcing httpd to constantly read that file several times with each hit.


问:
Hibernate default schema and Table annotation
I am using Spring Boot 1.3.5 and Hibernate 5.1. Property that tells Hibernate what the schema to work with is called is

```<code>spring.jpa.properties.hibernate.default_schema
</code>```

The value (schema name, lets say development), however, Somehow it does not get picked-up when creating tables with spring.jpa.hibernate.ddl-auto. Only way to get it work (at least what works for my case) is that each entity class has schema name defined with

```<code> @Table(name = "some_table", schema = "development")
</code>```

It would be great if tables could be created in the schema defined in spring boot application properties (possibility to be passed as ENV for different environments). If schema is not specified in @Table annotation the table is created in public schema.

Is there a way to set schema for tables without setting it in the Table annotation but with property file config only?

答:
After a year now app evolved and I am using Spring Boot 1.5.4 and Hibernate 5.1.5 with Postgres 9.6. Not sure if there were issues with previous versions but now it works fine.

yaml configuration file:

```<code>spring:
   datasource:
      driver-class-name: org.postgresql.Driver
      platform: postgresql
   jpa:
      properties:
         hibernate:
            dialect: org.hibernate.dialect.PostgreSQL94Dialect
            default_schema: SCHEMA_NAME
</code>```

Although using 9.6, PostgreSQL94Dialect can be used for 9.4 and later as there is no specific PostgreSQL96Dialect for given Hibernate version.

With this there is no need to specify schema in @Table annotation.

Update October 2018

See Hibernate's repository for supported dialects and set git tag to your Hibernate version: https://github.com/hibernate/hibernate-orm/tree/master/hibernate-core/src/main/java/org/hibernate/dialect

Body:
I am using Spring Boot 1.3.5 and Hibernate 5.1. Property that tells Hibernate what the schema to work with is called is

spring.jpa.properties.hibernate.default_schema

The value (schema name, lets say development), however, Somehow it does not get picked-up when creating tables with spring.jpa.hibernate.ddl-auto. Only way to get it work (at least what works for my case) is that each entity class has schema name defined with

 @Table(name = "some_table", schema = "development")

It would be great if tables could be created in the schema defined in spring boot application properties (possibility to be passed as ENV for different environments). If schema is not specified in @Table annotation the table is created in public schema.

Is there a way to set schema for tables without setting it in the Table annotation but with property file config only?

Body:
After a year now app evolved and I am using Spring Boot 1.5.4 and Hibernate 5.1.5 with Postgres 9.6. Not sure if there were issues with previous versions but now it works fine.

yaml configuration file:

spring:
   datasource:
      driver-class-name: org.postgresql.Driver
      platform: postgresql
   jpa:
      properties:
         hibernate:
            dialect: org.hibernate.dialect.PostgreSQL94Dialect
            default_schema: SCHEMA_NAME

Although using 9.6, PostgreSQL94Dialect can be used for 9.4 and later as there is no specific PostgreSQL96Dialect for given Hibernate version.

With this there is no need to specify schema in @Table annotation.

Update October 2018

See Hibernate's repository for supported dialects and set git tag to your Hibernate version: https://github.com/hibernate/hibernate-orm/tree/master/hibernate-core/src/main/java/org/hibernate/dialect


问:
Elasticsearch and kibana, BI data structure
I have an api where a customer comes in, the customer is sent to several 3rd party applications to work out the best possible product for them to use.

I am considering using elasticsearch and kibana as a bi tool for data analysts, they are not hugely experienced so it is going to be down to me to provide a flexible data structure for them to use.

My main question is that I would like to know if I should store data in a flattened structure or to use a more nested option, and whether or not this is an appropriate use case, perhaps there is a better solution or technology to build up a data warehouse.

```<code>{
    "Source": "ppc",
    "firstName": "john",
    "lastName": "doe",
    "emailAddress": "john@doe.com",
    ... // Other rich meta data
    "logsOf3rdParty": [
        {
            "dateSent": "2017-01-01T00:00:00.000",
            "result": "Accepted",
            "commission": 10
        },
        {
            "dateSent": "2017-01-01T00:00:00.000",
            "result": "Rejected",
            "commission": 0
        }
    ]
}
</code>```

答:
Kibana does not yet have support for nested documents, so you would not be able to make use of the visualization tools, but need to write all the queries yourself for the visualizations.

So a flattened structure would be easier to start with.

Body:
I have an api where a customer comes in, the customer is sent to several 3rd party applications to work out the best possible product for them to use.

I am considering using elasticsearch and kibana as a bi tool for data analysts, they are not hugely experienced so it is going to be down to me to provide a flexible data structure for them to use.

My main question is that I would like to know if I should store data in a flattened structure or to use a more nested option, and whether or not this is an appropriate use case, perhaps there is a better solution or technology to build up a data warehouse.

{
    "Source": "ppc",
    "firstName": "john",
    "lastName": "doe",
    "emailAddress": "john@doe.com",
    ... // Other rich meta data
    "logsOf3rdParty": [
        {
            "dateSent": "2017-01-01T00:00:00.000",
            "result": "Accepted",
            "commission": 10
        },
        {
            "dateSent": "2017-01-01T00:00:00.000",
            "result": "Rejected",
            "commission": 0
        }
    ]
}


问:
Incrementing doesn't work in prev, next buttons Angular 4
I had to create a prev and next component to go to the next page using router from Angular. The issue is not about angular, but about the incrementing and decrementing logic.

When I click next first time is ok, but second time I have to click twice to see the next page. The same is happening with prev button. If I want to click back, after I clicked first next, I have to click twice to go to prev page.

I looked and I looked and don't see where is the bug.

HTML file

```<code><button class="btn btn-primary" (click)="prevPage()">Prev</button>
<button class="btn btn-primary" (click)="nextPage()">Next</button>
</code>```

TS file

```<code>pages = [
 {name: '../page1', index: 0},
 {name: '../page2', index: 1},
 {name: '../page3', index: 2}
];
current = this.pages[0];

getIndex(currentIndex: number, shift: number){
 const lenght = this.pages.length;
 const incre = (((currentIndex + shift) + lenght) % lenght);
 console.log(incre);
 return incre;
}

prevPage() {
 const i = this.getIndex(this.current.index, -1);
 this.current = this.pages[i];
 this.router.navigate([this.current.name], { relativeTo: this.route });
 console.log(this.current.name);
}

nextPage() {
 const i = this.getIndex(this.current.index, 1);
 this.current = this.pages[i];
 this.router.navigate([this.current.name], { relativeTo: this.route });
 console.log(this.current.name);
}
</code>```

答:
in the HTML file.

```<code><button class="btn btn-primary" (click)="prevPage()">Prev</button>
<button class="btn btn-primary" (click)="nextPage()">Next</button>
</code>```

change the (click) listener to nextPage().

plus, it is not make sense the ( + length) in

const incre = (((currentIndex + shift) + lenght) % lenght);

it will work fine without it!.

const incre = ((currentIndex + shift) % lenght);

Body:
I had to create a prev and next component to go to the next page using router from Angular. The issue is not about angular, but about the incrementing and decrementing logic.

When I click next first time is ok, but second time I have to click twice to see the next page. The same is happening with prev button. If I want to click back, after I clicked first next, I have to click twice to go to prev page.

I looked and I looked and don't see where is the bug.

HTML file

<button class="btn btn-primary" (click)="prevPage()">Prev</button>
<button class="btn btn-primary" (click)="nextPage()">Next</button>

TS file

pages = [
 {name: '../page1', index: 0},
 {name: '../page2', index: 1},
 {name: '../page3', index: 2}
];
current = this.pages[0];

getIndex(currentIndex: number, shift: number){
 const lenght = this.pages.length;
 const incre = (((currentIndex + shift) + lenght) % lenght);
 console.log(incre);
 return incre;
}

prevPage() {
 const i = this.getIndex(this.current.index, -1);
 this.current = this.pages[i];
 this.router.navigate([this.current.name], { relativeTo: this.route });
 console.log(this.current.name);
}

nextPage() {
 const i = this.getIndex(this.current.index, 1);
 this.current = this.pages[i];
 this.router.navigate([this.current.name], { relativeTo: this.route });
 console.log(this.current.name);
}

Body:
in the HTML file.

<button class="btn btn-primary" (click)="prevPage()">Prev</button>
<button class="btn btn-primary" (click)="nextPage()">Next</button>

change the (click) listener to nextPage().

plus, it is not make sense the ( + length) in

const incre = (((currentIndex + shift) + lenght) % lenght);

it will work fine without it!.

const incre = ((currentIndex + shift) % lenght);


问:
C# How to get specific item from nested array
I have the following model:

```<code>public class Car
{
   public string Id {get; set;}
   public IList<Driver> Drivers {get; set;}
}

public Driver
{
   public string Id {get; set;}
   public bool IsActive {get; set;}
}
</code>```

How can I select driver that is active?

```<code>var carId = "...";
var activeDriver = await _carCollection.Find(a => a.Id == carId
            && a.Drivers.Any(e=>e.IsActive))
            .Project(a=>a.Drivers)
            .SingleOrDefaultAsync();
</code>```

This code returns IList<Driver>, so all items. But I want to retrieve only one Driver that is active.

答:
You basically need to include the positional $ operator in order to just return the matched array element from the query conditions given. You can do this with ElementAt(-1)

```<code>var activeDriver = await _carCollection.Find(a => a.Id == carId
        && a.Drivers.Any(e => e.IsActive))
        .Project(a => a.Drivers.ElementAt(-1))
        .SingleOrDefaultAsync();
</code>```

And can also be written as:

```<code>var builder = Builders<BsonDocument>.Filter;

var activeDriver = await _carCollection.Find(
         builder.Eq("Id", carId) & builder.Eq("Drivers.IsActive", true))
        .Project(Builders<BsonDocument>.Projection.Include("Drivers.$"))
        .SingleOrDefaultAsync();
</code>```

If I run either of those then I get the serialized output of what get's sent to MongoDB as:

```<code> {
    "find" : "cars",
    "filter" : { "_id" : "a", "Drivers" : { "$elemMatch" : { "IsActive" : true } } },
    "projection" : { "Drivers.$" : 1, "_id" : 0 },
    "limit" : 2,
    "$db" : "test"
 }
</code>```

Which matches exactly what the query should be.

Body:
I have the following model:

public class Car
{
   public string Id {get; set;}
   public IList<Driver> Drivers {get; set;}
}

public Driver
{
   public string Id {get; set;}
   public bool IsActive {get; set;}
}

How can I select driver that is active?

var carId = "...";
var activeDriver = await _carCollection.Find(a => a.Id == carId
            && a.Drivers.Any(e=>e.IsActive))
            .Project(a=>a.Drivers)
            .SingleOrDefaultAsync();

This code returns IList<Driver>, so all items. But I want to retrieve only one Driver that is active.

Body:
You basically need to include the positional $ operator in order to just return the matched array element from the query conditions given. You can do this with ElementAt(-1)

var activeDriver = await _carCollection.Find(a => a.Id == carId
        && a.Drivers.Any(e => e.IsActive))
        .Project(a => a.Drivers.ElementAt(-1))
        .SingleOrDefaultAsync();

And can also be written as:

var builder = Builders<BsonDocument>.Filter;

var activeDriver = await _carCollection.Find(
         builder.Eq("Id", carId) & builder.Eq("Drivers.IsActive", true))
        .Project(Builders<BsonDocument>.Projection.Include("Drivers.$"))
        .SingleOrDefaultAsync();

If I run either of those then I get the serialized output of what get's sent to MongoDB as:

 {
    "find" : "cars",
    "filter" : { "_id" : "a", "Drivers" : { "$elemMatch" : { "IsActive" : true } } },
    "projection" : { "Drivers.$" : 1, "_id" : 0 },
    "limit" : 2,
    "$db" : "test"
 }

Which matches exactly what the query should be.


问:
Android API support Real time Text Recognition and support other languages
Good day Sir I've been using Mobile Vision API to detect text using an Android phone camera but based on its documentation it only accepts Latin based languages do you know any API that supports real time text recognition as well as support for different languages like traditional Chinese, Japanese, etc. Thanks in advance</p>

答:
This one supports Real-Time recognition for other languages: http://rtrsdk.com However, Chinese and Japanese are only available in paid version.

Disclaimer: I work for ABBYY


问:
explain these how the conditional operator helps in counting the negative and positive numbers in an array?
my confusion is that how in the program the number of positive and negative numbers are calculated by writing that piece of code shown.
explain these code please!</p>

```<code>int num[5], i, neg = 0, pos = 0;

printf("enter any 5 numbers");
for (i = 0; i <= 4; i++)
    scanf("%d", &num[i]);
for (i = 0; i <= 4; i++) {
    num[i] < 0 ? neg++ : (pos++);
}
printf("\nnegative elements=%d", neg);
printf("\npositive elements=%d", pos);
getch();
</code>```

答:
The line

```<code>num[i]<0?neg++:(pos++);
</code>```

means- compare num[i] to 0, if it is lower, increase the variable neg. Otherwise (num[i] >= 0), increase the variable pos.

hope this helps

Body:
my confusion is that how in the program the number of positive and negative numbers are calculated by writing that piece of code shown.
explain these code please!

int num[5], i, neg = 0, pos = 0;

printf("enter any 5 numbers");
for (i = 0; i <= 4; i++)
    scanf("%d", &num[i]);
for (i = 0; i <= 4; i++) {
    num[i] < 0 ? neg++ : (pos++);
}
printf("\nnegative elements=%d", neg);
printf("\npositive elements=%d", pos);
getch();

Body:
The line

num[i]<0?neg++:(pos++);

means- compare num[i] to 0, if it is lower, increase the variable neg. Otherwise (num[i] >= 0), increase the variable pos.

hope this helps


问:
Enable referential integrity with nHIbernate using SQlite database
Good evening everyone,

I've got a project using nHibernate (2.1.2.4000) and System.Data.SQLite (1.0.66.0). I want to enforce NHibernate to create foreign keys when it creates the database or at least use the "foreign key" keyword then I'll be able to create the triggers.

I googled but I didn't find any documentation on how to do that and I'm loosing the faith. I really don't want to (and I won't) check referential integrity inside my code.

In a word: how do I enable referential integrity (or equivalent) with nHibernate and SQLite?

Thanks in advance,

答:
Better late than never: here's an answer:

Foreign Keys with SchemaExport in Fluent NHibernate using SQLite

nHibernate Issue Tracker

ContentLicense: CC BY-SA 2.5


问:
VS2017 VSIX Installer failed to install
I'm trying to install the VS2017 VSIX Installer so I can create a setup project for my application.  I've tried to run this package several times without success.

It seems to be failing for the following reason...
Package 'VSInstallerProjects,version=0.8.4' failed to install. System.IO.IOException: The file 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\PublicAssemblies\Microsoft.VisualStudio.WizardFramework.dll' already exists.

I've even renamed the .WizardFramework.dll but it just created a new one and then failed again.

Any help to resolve this will be greatly appreciated
Thanks

Here's the entire Log file .....

2017-06-23 11:55:58 AM - Microsoft VSIX Installer
2017-06-23 11:55:58 AM - -------------------------------------------
2017-06-23 11:55:58 AM - vsixinstaller.exe version:
2017-06-23 11:55:58 AM - 15.0.26403.7 built by: D15SVC
2017-06-23 11:55:58 AM - -------------------------------------------
2017-06-23 11:55:58 AM - Command line parameters:
2017-06-23 11:55:58 AM - C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VSIXInstaller.exe,C:\Users\duane\Downloads\InstallerProjects.vsix,/installas:2024,/callingprocessid:21024
2017-06-23 11:55:58 AM - -------------------------------------------
2017-06-23 11:55:58 AM - Microsoft VSIX Installer
2017-06-23 11:55:58 AM - -------------------------------------------
2017-06-23 11:55:59 AM - Initializing Install...
2017-06-23 11:55:59 AM - Extension Details...
2017-06-23 11:55:59 AM -    Identifier         : VSInstallerProjects
2017-06-23 11:55:59 AM -    Name               : Microsoft Visual Studio 2017 Installer Projects
2017-06-23 11:55:59 AM -    Author             : Microsoft
2017-06-23 11:55:59 AM -    Version            : 0.8.4
2017-06-23 11:55:59 AM -    Description        : This official Microsoft extension provides support for Visual Studio Installer Projects in Visual Studio 2017.
2017-06-23 11:55:59 AM -    Locale             : en-US
2017-06-23 11:55:59 AM -    MoreInfoURL        :
2017-06-23 11:55:59 AM -    InstalledByMSI     : False
2017-06-23 11:55:59 AM -    SupportedFrameworkVersionRange : [4.6.1,)
2017-06-23 11:55:59 AM -
2017-06-23 11:55:59 AM -    SignatureState     : ValidSignature
2017-06-23 11:55:59 AM -    SignedBy           : Microsoft Corporation
2017-06-23 11:55:59 AM -    Certificate Info   :
2017-06-23 11:55:59 AM -        -------------------------------------------------------
2017-06-23 11:55:59 AM -        [Subject]       : CN=Microsoft Corporation, OU=MOPR, OU=OPC, O=Microsoft Corporation, L=Redmond, S=Washington, C=US
2017-06-23 11:55:59 AM -        [Issuer]        : CN=Microsoft Code Signing PCA 2010, O=Microsoft Corporation, L=Redmond, S=Washington, C=US
2017-06-23 11:55:59 AM -        [Serial Number] : 330000017D015E4C2BE2BCF66900000000017D
2017-06-23 11:55:59 AM -        [Not Before]    : 2017-02-15 2:10:16 PM
2017-06-23 11:55:59 AM -        [Not After]     : 2018-05-09 3:10:16 PM
2017-06-23 11:55:59 AM -        [Thumbprint]    : 69713C6FF47FADFF90C9465F7783E6E08232B28F
2017-06-23 11:55:59 AM -
2017-06-23 11:55:59 AM -    Supported Products :
2017-06-23 11:55:59 AM -        Microsoft.VisualStudio.Community
2017-06-23 11:55:59 AM -            Version : [15.0]
2017-06-23 11:55:59 AM -
2017-06-23 11:55:59 AM -    References         :
2017-06-23 11:55:59 AM -    Prerequisites      :
2017-06-23 11:55:59 AM -        -------------------------------------------------------
2017-06-23 11:55:59 AM -        Identifier   : Microsoft.VisualStudio.MinShell
2017-06-23 11:55:59 AM -        Name         : Visual Studio Min Shell
2017-06-23 11:55:59 AM -        Version      : [15.0.26205,16.0)
2017-06-23 11:55:59 AM -
2017-06-23 11:55:59 AM -        -------------------------------------------------------
2017-06-23 11:55:59 AM -        Identifier   : Microsoft.Component.ClickOnce
2017-06-23 11:55:59 AM -        Name         : ClickOnce Publishing
2017-06-23 11:55:59 AM -        Version      : [15.0,16.0)
2017-06-23 11:55:59 AM -
2017-06-23 11:55:59 AM - Signature Details...
2017-06-23 11:55:59 AM -    Extension is signed with a valid signature.
2017-06-23 11:55:59 AM -
2017-06-23 11:55:59 AM - Searching for applicable products...
2017-06-23 11:55:59 AM - Found installed product - Microsoft Visual Studio Community 2015
2017-06-23 11:55:59 AM - Found installed product - Microsoft Visual Studio 2015 Shell (Integrated)
2017-06-23 11:55:59 AM - Found installed product - Global Location
2017-06-23 11:55:59 AM - Found installed product - Visual Studio Community 2017
2017-06-23 11:56:00 AM - PKGDEF Information: Looking for master PkgDef file, Path: C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\master.pkgdef

2017-06-23 11:56:00 AM - PKGDEF Information: Creating PkgDefCacheNonVolatile
2017-06-23 11:56:00 AM - PKGDEF Information: Double-checking master pkgdef file
2017-06-23 11:56:00 AM - PKGDEF Information: PkgDefManagement initialized
2017-06-23 11:56:00 AM - PKGDEF Information: RootFolder, Path: C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\

2017-06-23 11:56:00 AM - PKGDEF Information: ShellFolder, Path: C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\

2017-06-23 11:56:00 AM - PKGDEF Information: PkgDefSearchPath, Path: C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\Extensions;C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\CommonExtensions;C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\devenv.admin.pkgdef

2017-06-23 11:56:00 AM - PKGDEF Information: ImageManifestSearchPath, Path: C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\Extensions;C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\CommonExtensions;C:\Users\duane\AppData\Local\Microsoft\VisualStudio\15.0_0ee0412c\Extensions

2017-06-23 11:56:00 AM - PKGDEF Information: ApplicationExtensionsFolder, Path: C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\Extensions

2017-06-23 11:56:00 AM - PKGDEF Information: "ZeroImpact" = dword:0, "MergeRegistry" = dword:3
2017-06-23 11:56:00 AM - PKGDEF Information: Could not find ConfigurationChanged timestamp., PKGDEF: 80070002
2017-06-23 11:56:00 AM - PKGDEF Information: Could not find ConfigurationChanged timestamp., PKGDEF: 80070002
2017-06-23 11:56:00 AM - PKGDEF Information: User extensions enabled by setting, Path: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\15.0_0ee0412c\ExtensionManager\EnableAdminExtensions

2017-06-23 11:56:00 AM - PKGDEF Information: PkgDefCache flags, PKGDEF: 7001
2017-06-23 11:56:00 AM - PKGDEF Information: Could not find ConfigurationChanged timestamp., PKGDEF: 80070002
2017-06-23 11:56:00 AM - PKGDEF Information: Could not find ConfigurationChanged timestamp., PKGDEF: 80070002
2017-06-23 11:56:00 AM - PKGDEF Information: PkgDefManagement startup complete
2017-06-23 11:56:01 AM - The extension with ID 'VSInstallerProjects' is not installed to Visual Studio Community 2017.
2017-06-23 11:56:07 AM - The following target products have been selected...
2017-06-23 11:56:07 AM -    Visual Studio Community 2017
2017-06-23 11:56:07 AM -
2017-06-23 11:56:08 AM - Beginning to install extension to Visual Studio Community 2017...
2017-06-23 11:56:08 AM - VSIX TaskScheduler: VSIX Auto Updatetask already exists.
2017-06-23 11:56:12 AM - Package Microsoft.Windows.UniversalCRT.Msu.8 is not applicable. Skipping it due to the following reason(s): The current OS Version '10.0.15063.0' is not in the supported version range '[6.2,6.3)'.
2017-06-23 11:56:12 AM - Package Microsoft.Windows.UniversalCRT.Msu.81 is not applicable. Skipping it due to the following reason(s): The current OS Version '10.0.15063.0' is not in the supported version range '[6.3,6.4)'.
2017-06-23 11:56:12 AM - Package Microsoft.Net.4.6.FullRedist is not applicable. Skipping it due to the following reason(s): The current OS Version '10.0.15063.0' is not in the supported version range '[6.1.1,6.4)'.
2017-06-23 11:56:13 AM - Package Microsoft.Windows.UniversalCRT.Msu.7 is not applicable. Skipping it due to the following reason(s): The current OS Version '10.0.15063.0' is not in the supported version range '[6.1,6.2)'.
2017-06-23 11:56:13 AM - Package Microsoft.DiagnosticsHub.KB2882822.Win7 is not applicable. Skipping it due to the following reason(s): The current OS Version '10.0.15063.0' is not in the supported version range '[6.1,6.2)'.
2017-06-23 11:56:13 AM - Package WebSocket4NetV2 is not applicable. Skipping it due to the following reason(s): The current OS Version '10.0.15063.0' is not in the supported version range '[6.1,6.2)'.
2017-06-23 11:56:13 AM - Package Microsoft.Net.4.6.1.FullRedist is not applicable. Skipping it due to the following reason(s): The current OS Version '10.0.15063.0' is not in the supported version range '[6.1.1,10.0.10241)'.
2017-06-23 11:56:13 AM - Package Microsoft.Windows.81SDK.Store.DirectX.Msi is not applicable. Skipping it due to the following reason(s): The current OS Version '10.0.15063.0' is not in the supported version range '[6.1,6.3]'.
2017-06-23 11:56:13 AM - Package Microsoft.Windows.81SDK.Store.DirectX.Msi is not applicable. Skipping it due to the following reason(s): The current OS Version '10.0.15063.0' is not in the supported version range '[6.1,6.3]'.
2017-06-23 11:56:13 AM - Package Microsoft.Windows.81SDK.Desktop.DirectX.Msi is not applicable. Skipping it due to the following reason(s): The current OS Version '10.0.15063.0' is not in the supported version range '[6.1,6.3]'.
2017-06-23 11:56:13 AM - Package Microsoft.Windows.81SDK.Desktop.DirectX.Msi is not applicable. Skipping it due to the following reason(s): The current OS Version '10.0.15063.0' is not in the supported version range '[6.1,6.3]'.
2017-06-23 11:56:13 AM - Windows Installer found the package 'sqllocaldb,version=15.1.61703.130,chip=x64,language=en-US' superseded but corresponding compatible package information was not found. Attempts to repair will be skipped and that to uninstall may leave the cache behind.
2017-06-23 11:56:13 AM - Package Microsoft.VisualStudio.OfficeDeveloperTools.WindowsIdentityFoundation.Msu is not applicable. Skipping it due to the following reason(s): The current OS Version '10.0.15063.0' is not in the supported version range '(,6.2)'.
2017-06-23 11:56:22 AM -

Package 'VSInstallerProjects,version=0.8.4' failed to install. System.IO.IOException: The file 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\PublicAssemblies\Microsoft.VisualStudio.WizardFramework.dll' already exists.

at Microsoft.VisualStudio.Setup.Installer.VsixInstaller.InstallCore(String localPath, String installDir, InstallablePackage pkg)
   at Microsoft.VisualStudio.Setup.Installer.InstallerBase.InstallHelper(InstallData installData)
2017-06-23 11:56:22 AM - Skipping cache of package 'Component.VSInstallerProjects,version=0.8.4' since the package or a parent package had a vital failure.
2017-06-23 11:56:28 AM - Install Error : Microsoft.VisualStudio.Setup.PackageFailureException: Package 'VSInstallerProjects' failed to install
   at Microsoft.VisualStudio.Setup.InstallOperation.Run(CancellationToken token)
   at Microsoft.VisualStudio.Setup.Engine.RunOperation(InstallOperation installOperation, CancellationToken token, ExecuteAction action, ITelemetryOperation telemetryOperation)
   at Microsoft.VisualStudio.Setup.Engine.RunCoreOperation(InstallOperation coreOperation, ExecuteAction action, ITelemetryOperation telemetryOperation, CancellationToken token)
   at Microsoft.VisualStudio.Setup.Engine.Install(Product product, String destination, CancellationToken token)
   at Microsoft.VisualStudio.ExtensionManager.ExtensionEngineImpl.PerformSetupEngineInstall(InstallableExtensionImpl extension, Boolean installPerMachine, Boolean isPackComponent, IDictionary2 extensionsInstalledSoFar, List1 extensionsUninstalledSoFar, IInstalledExtensionList modifiedInstalledExtensionsList, IProgress1 progress, InstallFlags installFlags, AsyncOperation asyncOp, IInstalledExtension& newExtension)
   at Microsoft.VisualStudio.ExtensionManager.ExtensionEngineImpl.InstallInternal(InstallableExtensionImpl extension, InstallFlags installFlags, IDictionary2 extensionsInstalledSoFar, List1 extensionsUninstalledSoFar, IInstalledExtensionList modifiedInstalledExtensionsList, AsyncOperation asyncOp, IProgress1 progress)
   at Microsoft.VisualStudio.ExtensionManager.ExtensionEngineImpl.BeginInstall(IInstallableExtension installableExtension, InstallFlags installFlags, AsyncOperation asyncOp)
   at Microsoft.VisualStudio.ExtensionManager.ExtensionEngineImpl.InstallWorker(IInstallableExtension extension, InstallFlags installFlags, AsyncOperation asyncOp)

答:
I had the exact same problem.
What did the trick for me was go to the folder:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\PublicAssemblies

and rename the following 2 files:

Microsoft.VisualStudio.DeployWizard.dll

Microsoft.VisualStudio.WizardFramework.dll

Also rename the following folder if it exists:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\VSI

Once done, I could install the extension.

Mind you, I have a Professional version, so in the folder-paths you should probably replace "Professional" with "Community".

Title: VS2017 VSIX Installer failed to install


问:
How can we schedule nifi data flow ? I'm using HDP 2.5
I want to schedule data flow in daily base through nifi.

For Example,
I need to run schedule on 9.00 AM in every morning.

Can anyone tell me what is procedure to make schedule data flow

答:
There are three scheduling strategy available, see below details

Timer driven: This is the default mode. The Processor will be scheduled to run on a regular interval. The interval at which the Processor is run is defined by the ‘Run schedule’ option (see below).

Event driven: When this mode is selected, the Processor will be triggered to run by an event, and that event occurs when FlowFiles enter Connections feeding this Processor. This mode is currently considered experimental and is not supported by all Processors. When this mode is selected, the ‘Run schedule’ option is not configurable, as the Processor is not triggered to run periodically but as the result of an event. Additionally, this is the only mode for which the ‘Concurrent tasks’ option can be set to 0. In this case, the number of threads is limited only by the size of the Event-Driven Thread Pool that the administrator has configured.

CRON driven: When using the CRON driven scheduling mode, the Processor is scheduled to run periodically, similar to the Timer driven scheduling mode. However, the CRON driven mode provides significantly more flexibility at the expense of increasing the complexity of the configuration. The CRON driven scheduling value is a string of six required fields and one optional field, each separated by a space.

You typically specify values one of the following ways:

Number: Specify one or more valid value. You can enter more than one value using a comma-separated list.

Range: Specify a range using the - syntax.

Increment: Specify an increment using / syntax. For example, in the Minutes field, 0/15 indicates the minutes 0, 15, 30, and 45.

You should also be aware of several valid special characters:

* — Indicates that all values are valid for that field.

?  — Indicates that no specific value is specified. This special character is valid in the Days of Month and Days of Week field.

L  — You can append L to one of the Day of Week values, to specify the last occurrence of this day in the month. For example, 1L indicates the last Sunday of the month.

For example:

The string 0 0 13 * * ? indicates that you want to schedule the processor to run at 1:00 PM every day.

The string 0 20 14 ? * MON-FRI indicates that you want to schedule the processor to run at 2:20 PM every Monday through Friday.

The string 0 15 10 ? * 6L 2011-2017 indicates that you want to schedule the processor to run at 10:15 AM, on the last Friday of every month, between 2011 and 2017.

For your schedule time should be like below;

0109*?** - this meaning every 1 seconds 09 minutes is morning 9 AM other * fields run every day and month.

I hope it helps you!!!


问:
Compile error using C# automatically implemented properties
A C# Noob, I am trying to use SharpDevelop utility to convert my VB.NET application a C#.

I am noticing that my automatically implemented properties are generating a lot of errors. For example, take the following property:

public SqlDateTime DateOfBirth { get; set; }

Whenever I try to access the implied underlying module level variable, _DateOfBirth, I get the error.

Error   699 The name '_DateOfBirth' does not exist in the current context   D:\Users\Chad\Desktop\BESI CSharp\BESI\BESI.BusinessObjects.ConvertedToC#\ChinaVisa.cs  240 13  Besi.BusinessObjects.Converted

I could expand the properties declarations out to full-fledged properties, but this should n't be necessary and I'd like to understand why I am getting this error.

答: If you use automatically generated properties, you cannot rely on the compiler picking any specific name for the backing field. That's entirely compiler-specific, and even if you could access those fields, your code might still break if you use another compiler.</p>


问:
Creating Polygon using Google Map API
I am referring the URL : https://housing.com/in/buy/search?f=eyJiYXNlIjpbeyJ0eXBlIjoiUE9MWSIsInV1aWQiOiJmMGZhNTIwNjI0ZjNhOGRlOWY4NSIsImxhYmVsIjoiUGltcGxlIFNhdWRhZ2FyIn1dLCJ2IjoyLCJzIjoiZCJ9

I am trying to make something similar, can anybody suggest how can I achieve it. I tried to search and explore google map APIs, but could not understand which API in particular can be used.

答:
Polygon is one feature of Drawing tools of Google Maps. The DrawingManager class provides a graphical interface for users to draw polygons, rectangles, polylines, circles, and markers on the map.

The Drawing Tools are a self-contained library, separate from the main Maps API JavaScript code. To use the functionality contained within this library, you must first load it using the libraries parameter in the Maps API bootstrap URL:

Once you’ve added the libraries parameter, you can create a DrawingManager object as follows:

var drawingManager = new google.maps.drawing.DrawingManager();
drawingManager.setMap(map);

Reference: https://developers.google.com/maps/documentation/javascript/examples/drawing-tools

Title: Creating Polygon using Google Map API

Body:
Polygon is one feature of Drawing tools of Google Maps. The DrawingManager class provides a graphical interface for users to draw polygons, rectangles, polylines, circles, and markers on the map.

The Drawing Tools are a self-contained library, separate from the main Maps API JavaScript code. To use the functionality contained within this library, you must first load it using the libraries parameter in the Maps API bootstrap URL:

<script type="text/javascript"
  src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=drawing">
</script>

Once you’ve added the libraries parameter, you can create a DrawingManager object as follows:

var drawingManager = new google.maps.drawing.DrawingManager();
drawingManager.setMap(map);

Reference: https://developers.google.com/maps/documentation/javascript/examples/drawing-tools


问:
How to read CSV file with newline and comma characters inside cells in C++
I've got a CSV file containing cells with break lines ("\n") and/or commas which are enclosed with double quotes.
When I use getline() function to get each row, it consider each line inside cell as a new row of csv file. In addition, when using splitIntoVec to get vector of each row, it condiders comma inside a cell as a new vector element.
I want to store the content of csv file into a vector of vectors which each row is a vector of strings inside its cells.

for instance, for the following csv file content

```<code>"Row 1 cell 1
 With break line","Row1 cell2, with comma"
"Row 2 cell 1
 With break line","Row2 cell2, with comma"
 Row 3 cell 1,Row3 cell 2
</code>```

I get the result vector of 4 string vectors which the first one has only one element and the second one has 3 elements.
Here is my code :

```<code>vector<vector<string>> readFromCsv(string &fileName, char rowDelimiter = "\n", char colDelimiter = ",") {
    ifstream file(fileName); // declare file stream
    string value;
    vector<vector<string>> contentVec;
    vector<string> rowVec;
    string rowStr;
    while (getline(file, rowStr, rowDelimiter)) {
        rowVec = splitIntoVec(rowStr, colDelimiter);
        contentVec.push_back(rowVec);
    }

    return contentVec;
}
</code>```

Is there any other function (in libraries like boost) available to resolve these issues? Any help would be appreciated.

In PHP , I get the content of the csv file by fgetcsv() correctly . Is there any alternative function in c++?

答:
@Simone already said in his comment that it is not the CSV file. But seeing your problem you will need to get your hand dirty and do some text processing to get it separate. You can read complete file in a string and then break it further using loops or which ever way you see fit. For this you will need to keep track of the encountered " while traversing and breaking only when it is not inside double quotes.

For Example,

(opening apostrophes)"Row 1 cell 1
 With break line"(closing apostrophes),"(opening apostrophes)Row1 cell2, with comma"(closing apostrophes)

You will have to keep track of opening and closing double apostrophes using index or number and break for rows only if '\n' is found outside the opening and closing apostrophes.

You can use regex also if you are sure there are no " in the cells.

Thanks @Alex Useful link if someone else faces the same issue : http://mybyteofcode.blogspot.nl/2010/11/parse-csv-file-with-embedded-new-lines.html

Body:
I've got a CSV file containing cells with break lines ("\n") and/or commas which are enclosed with double quotes.
When I use getline() function to get each row, it consider each line inside cell as a new row of csv file. In addition, when using splitIntoVec to get vector of each row, it condiders comma inside a cell as a new vector element.
I want to store the content of csv file into a vector of vectors which each row is a vector of strings inside its cells.

for instance, for the following csv file content

"Row 1 cell 1
 With break line","Row1 cell2, with comma"
"Row 2 cell 1
 With break line","Row2 cell2, with comma"
 Row 3 cell 1,Row3 cell 2

I get the result vector of 4 string vectors which the first one has only one element and the second one has 3 elements.
Here is my code :

vector<vector<string>> readFromCsv(string &fileName, char rowDelimiter = "\n", char colDelimiter = ",") {
    ifstream file(fileName); // declare file stream
    string value;
    vector<vector<string>> contentVec;
    vector<string> rowVec;
    string rowStr;
    while (getline(file, rowStr, rowDelimiter)) {
        rowVec = splitIntoVec(rowStr, colDelimiter);
        contentVec.push_back(rowVec);
    }

    return contentVec;
}

Is there any other function (in libraries like boost) available to resolve these issues? Any help would be appreciated.

In PHP , I get the content of the csv file by fgetcsv() correctly . Is there any alternative function in c++?


问:
Auto completion based on regex
I have a QLineEdit with a QRegularExpressionValidator where the allowed input is:

```<code>^(?<sign>[<>=]|>=|<=)(?<value>\d+\.?\d*)(?<unit>[mc]{0,1}m[²2]\/s|St|cSt)$
</code>```

So for example:

```<code>"<15m²/s"   // good
">=3.14cSt" // good
"27mm2/s"   // bad
</code>```

I search a way to fill a QCompleter based on this regex.

So if the cursor is on the empty QLineEdit the completer proposes:

>, <, =, >= or <=.

After the sign, propose nothing and after the last number, propose:

mm²/s, cm²/s, m²/s, St or cSt

My need is to create a QStringList by reading the allowed sign and unit part of the regex and insert this QStringList in the QCompleter because it is based on a QAbstractItemModel.

答:
I found a workaround by subclassing QLineEdit but it is not the best solution. If someone has better, I take.

lineeditregexgroup.h:

```<code>#ifndef LINEEDITREGEXGROUP_H
#define LINEEDITREGEXGROUP_H

#include <QLineEdit>
#include <QMap>

class QCompleter;
class QStringListModel;
class QRegularExpression;
class QRegularExpressionValidator;

class LineEditRegexGroup : public QLineEdit
{
    Q_OBJECT

public:
    LineEditRegexGroup(const QString pattern, QWidget *parent = Q_NULLPTR);
    ~LineEditRegexGroup();
    static QMap<QString, QStringList> mapCompleter;

public slots:
    void checkValidity(const QString &text);

protected:
    virtual void mouseReleaseEvent(QMouseEvent *e);

private:
    QString                     curGroup;
    QCompleter                  *completer;
    QStringListModel            *listCompleter;
    QRegularExpression          *regex;
    QRegularExpressionValidator *validator;

};

#endif // LINEEDITREGEXGROUP_H
</code>```

lineeditregexgroup.cpp:

```<code>#include "lineeditregexgroup.h"
#include <QCompleter>
#include <QStringListModel>
#include <QRegularExpression>
#include <QRegularExpressionValidator>
#include <QAbstractItemView>

QMap<QString, QStringList> LineEditRegexGroup::mapCompleter = {
    { "sign", QStringList() << "<" << ">" << "=" << "<=" << ">=" },
    { "unit", QStringList() << "mm²/s" << "cm²/s" << "m²/s" << "St" << "cSt" }
};

LineEditRegexGroup::LineEditRegexGroup(const QString pattern, QWidget *parent)
    : QLineEdit(parent)
{
    completer = new QCompleter(this);
    listCompleter = new QStringListModel(completer);
    regex = new QRegularExpression(pattern, QRegularExpression::NoPatternOption);
    validator = new QRegularExpressionValidator(*regex, this);

    completer->setModel(listCompleter);
    completer->setCompletionMode(QCompleter::UnfilteredPopupCompletion);
    setCompleter(completer);
    setValidator(validator);
    curGroup = regex->namedCaptureGroups().at(1);

    connect(this, SIGNAL(textEdited(QString)), this, SLOT(checkValidity(QString)));
}

LineEditRegexGroup::~LineEditRegexGroup()
{
    // dtor ...
}

void LineEditRegexGroup::checkValidity(const QString &text)
{
    bool valid = true;
    int nbCapture = 0;
    QRegularExpressionMatch match = regex->match(text);
    for (int i=1; i<=regex->captureCount() && valid; i++){
        /* +1 to check only groups, not the global string */
        valid &= !match.captured(i).isEmpty();
        if (valid)
            nbCapture++;
        curGroup = regex->namedCaptureGroups().at(i);
        if (curGroup == "value")
            curGroup = regex->namedCaptureGroups().at(i-1);
    }
    if (nbCapture < regex->captureCount()){
        QStringList new_model = mapCompleter.value(curGroup);
        if (curGroup == regex->namedCaptureGroups().at(regex->captureCount())){
            new_model.replaceInStrings(QRegularExpression("^(.*)$"), text+"\\1");
        }
        listCompleter->setStringList(new_model);
        completer->complete();
    }
}

void LineEditRegexGroup::mouseReleaseEvent(QMouseEvent *e)
{
    QLineEdit::mouseReleaseEvent(e);
    if (text().isEmpty())
        checkValidity("");
}
</code>```

And call it like this:

```<code>new LineEditRegexGroup(
    "^(?:(?<sign>[<>=]|>=|<=|)"
    "(?:(?<value>\\d+\\.?\\d*)"
    "(?:(?<unit>[mc]{0,1}m[²2]\\/s|St|cSt))?)?)?$",
    parent
);
</code>```

Result:

Title: Auto completion based on regex

Body:
I have a QLineEdit with a QRegularExpressionValidator where the allowed input is:

^(?<sign>[<>=]|>=|<=)(?<value>\d+\.?\d*)(?<unit>[mc]{0,1}m[²2]\/s|St|cSt)$

So for example:

"<15m²/s"   // good
">=3.14cSt" // good
"27mm2/s"   // bad

I search a way to fill a QCompleter based on this regex.

So if the cursor is on the empty QLineEdit the completer proposes:

>, <, =, >= or <=.

After the sign, propose nothing and after the last number, propose:

mm²/s, cm²/s, m²/s, St or cSt

My need is to create a QStringList by reading the allowed sign and unit part of the regex and insert this QStringList in the QCompleter because it is based on a QAbstractItemModel.

Body:
I found a workaround by subclassing QLineEdit but it is not the best solution. If someone has better, I take.

lineeditregexgroup.h:

#ifndef LINEEDITREGEXGROUP_H
#define LINEEDITREGEXGROUP_H

#include <QLineEdit>
#include <QMap>

class QCompleter;
class QStringListModel;
class QRegularExpression;
class QRegularExpressionValidator;

class LineEditRegexGroup : public QLineEdit
{
    Q_OBJECT

public:
    LineEditRegexGroup(const QString pattern, QWidget *parent = Q_NULLPTR);
    ~LineEditRegexGroup();
    static QMap<QString, QStringList> mapCompleter;

public slots:
    void checkValidity(const QString &text);

protected:
    virtual void mouseReleaseEvent(QMouseEvent *e);

private:
    QString                     curGroup;
    QCompleter                  *completer;
    QStringListModel            *listCompleter;
    QRegularExpression          *regex;
    QRegularExpressionValidator *validator;

};

#endif // LINEEDITREGEXGROUP_H

lineeditregexgroup.cpp:

#include "lineeditregexgroup.h"
#include <QCompleter>
#include <QStringListModel>
#include <QRegularExpression>
#include <QRegularExpressionValidator>
#include <QAbstractItemView>

QMap<QString, QStringList> LineEditRegexGroup::mapCompleter = {
    { "sign", QStringList() << "<" << ">" << "=" << "<=" << ">=" },
    { "unit", QStringList() << "mm²/s" << "cm²/s" << "m²/s" << "St" << "cSt" }
};

LineEditRegexGroup::LineEditRegexGroup(const QString pattern, QWidget *parent)
    : QLineEdit(parent)
{
    completer = new QCompleter(this);
    listCompleter = new QStringListModel(completer);
    regex = new QRegularExpression(pattern, QRegularExpression::NoPatternOption);
    validator = new QRegularExpressionValidator(*regex, this);

    completer->setModel(listCompleter);
    completer->setCompletionMode(QCompleter::UnfilteredPopupCompletion);
    setCompleter(completer);
    setValidator(validator);
    curGroup = regex->namedCaptureGroups().at(1);

    connect(this, SIGNAL(textEdited(QString)), this, SLOT(checkValidity(QString)));
}

LineEditRegexGroup::~LineEditRegexGroup()
{
    // dtor ...
}

void LineEditRegexGroup::checkValidity(const QString &text)
{
    bool valid = true;
    int nbCapture = 0;
    QRegularExpressionMatch match = regex->match(text);
    for (int i=1; i<=regex->captureCount() && valid; i++){
        /* +1 to check only groups, not the global string */
        valid &= !match.captured(i).isEmpty();
        if (valid)
            nbCapture++;
        curGroup = regex->namedCaptureGroups().at(i);
        if (curGroup == "value")
            curGroup = regex->namedCaptureGroups().at(i-1);
    }
    if (nbCapture < regex->captureCount()){
        QStringList new_model = mapCompleter.value(curGroup);
        if (curGroup == regex->namedCaptureGroups().at(regex->captureCount())){
            new_model.replaceInStrings(QRegularExpression("^(.*)$"), text+"\\1");
        }
        listCompleter->setStringList(new_model);
        completer->complete();
    }
}

void LineEditRegexGroup::mouseReleaseEvent(QMouseEvent *e)
{
    QLineEdit::mouseReleaseEvent(e);
    if (text().isEmpty())
        checkValidity("");
}

And call it like this:

new LineEditRegexGroup(
    "^(?:(?<sign>[<>=]|>=|<=|)"
    "(?:(?<value>\\d+\\.?\\d*)"
    "(?:(?<unit>[mc]{0,1}m[²2]\\/s|St|cSt))?)?)?$",
    parent
);

Result:


问:
How do I explicitly run the static constructor of an unknown type?

Possible Duplicate:

  How do I invoke a static constructor with reflection?

I've got some initialization code in the static constructor of various classes. I can't create instances, nor do I know the types in advance. I would like to ensure the classes are loaded.

I tried this:

```<code>fooType.TypeInitializer.Invoke (new object[0]);
</code>```

But got a MemberAccessException: Type initializer was not callable.

I'm assuming this is because the cctor is private? Is there a way to fix this without changing the architecture?

Edit: I found a workaround using RuntimeHelpers.RunClassConstructor, but this way seems to be barely documented in the MSDN and I'm not sure if it is a hack or a reasonable, prod system like way.

答:
I'm not sure why this works, but as far as I reason (with help from Skeet) if i have a static class

```<code>public static class Statics1
{
    public static string Value1 { get; set; }

    static Statics1()
    {
        Console.WriteLine("Statics1 cctor");
        Value1 = "Initialized 1";
    }
}
</code>```

The code:

```<code>Type staticType = typeof (Statics1);
staticType.TypeInitializer.Invoke(null);
or
staticType.TypeInitializer.Invoke(new object[0]);
</code>```

will throw with an exception, because somehow this resolves to the .ctor, instead of the .cctor of the class.

If I use an explicitly static class, it is treated like an abstract sealed class, so the exception is that an abstract class cannot be instantiated, and if I use a regular class with a static constructor, the exception is that the type initializer is not callable.

But if I use the Invoke overload with two parameters (instance, params), like this:

```<code>Type staticType = typeof (Statics1);
staticType.TypeInitializer.Invoke(null, null);
</code>```

explicitly stating that I am invoking a static method (that's the meaning of the first null - no instance == static), this works and initializes the class.

That said, static constructors are strange beasts. Invoking one in this way will call the static constructor even if it was already executed, i.e., this code:

```<code>Console.WriteLine(Statics1.Value1);

Type staticType = typeof (Statics1);
staticType.TypeInitializer.Invoke(null, null);
</code>```

will call the static constructor twice. So if your cctors have potentially important sideeffects, such as creating files, opening databases, etc, you might want to rethink this approach.

Also, even though I prefer static constructors for reasons of readability, from a performance perspective, field initializers are a bit faster than static constructors

Body:
Possible Duplicate:

  How do I invoke a static constructor with reflection?

I've got some initialization code in the static constructor of various classes. I can't create instances, nor do I know the types in advance. I would like to ensure the classes are loaded.

I tried this:

fooType.TypeInitializer.Invoke (new object[0]);

But got a MemberAccessException: Type initializer was not callable.

I'm assuming this is because the cctor is private? Is there a way to fix this without changing the architecture?

Edit: I found a workaround using RuntimeHelpers.RunClassConstructor, but this way seems to be barely documented in the MSDN and I'm not sure if it is a hack or a reasonable, prod system like way.

Body:
I'm not sure why this works, but as far as I reason (with help from Skeet) if i have a static class

public static class Statics1
{
    public static string Value1 { get; set; }

    static Statics1()
    {
        Console.WriteLine("Statics1 cctor");
        Value1 = "Initialized 1";
    }
}

The code:

Type staticType = typeof (Statics1);
staticType.TypeInitializer.Invoke(null);
or
staticType.TypeInitializer.Invoke(new object[0]);

will throw with an exception, because somehow this resolves to the .ctor, instead of the .cctor of the class.

If I use an explicitly static class, it is treated like an abstract sealed class, so the exception is that an abstract class cannot be instantiated, and if I use a regular class with a static constructor, the exception is that the type initializer is not callable.

But if I use the Invoke overload with two parameters (instance, params), like this:

Type staticType = typeof (Statics1);
staticType.TypeInitializer.Invoke(null, null);

explicitly stating that I am invoking a static method (that's the meaning of the first null - no instance == static), this works and initializes the class.

That said, static constructors are strange beasts. Invoking one in this way will call the static constructor even if it was already executed, i.e., this code:

Console.WriteLine(Statics1.Value1);

Type staticType = typeof (Statics1);
staticType.TypeInitializer.Invoke(null, null);

will call the static constructor twice. So if your cctors have potentially important sideeffects, such as creating files, opening databases, etc, you might want to rethink this approach.

Also, even though I prefer static constructors for reasons of readability, from a performance perspective, field initializers are a bit faster than static constructors


问:
How to properly setup flow to work with react-apollo?
I know that some initial flow typing were merged in apollo-client.

How can I use it?

Should I declare my own lib definitions? (I use flow-typed currently).

Could you please share an example of such definitions (particularly for react-apollo)?

For example, If I have such code:

```<code>// @flow
import { ApolloClient, createNetworkInterface } from 'react-apollo';
import fetch from 'isomorphic-fetch';

let apolloClient = null;

// Polyfill fetch() on the server (used by apollo-client)
if (!process.browser) {
  global.fetch = fetch;
}

function create() {
  return new ApolloClient({
    ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once)
    networkInterface: createNetworkInterface({
      uri: 'https://api.graph.cool/simple/v1/cixmkt2ul01q00122mksg82pn', // Server URL (must be absolute)
      opts: {
        // Additional fetch() options like `credentials` or `headers`
        credentials: 'same-origin',
      },
    }),
  });
}
</code>```

and on the other side in my lib def I have:

```<code>declare module 'react-apollo' {
  declare module.exports: any;
}
</code>```

what should I type here(examples would be helpful) to have type checking?

答: Start from this detailed article.</p>

Body:
I know that some initial flow typing were merged in apollo-client.

How can I use it?

Should I declare my own lib definitions? (I use flow-typed currently).

Could you please share an example of such definitions (particularly for react-apollo)?

For example, If I have such code:

// @flow
import { ApolloClient, createNetworkInterface } from 'react-apollo';
import fetch from 'isomorphic-fetch';

let apolloClient = null;

// Polyfill fetch() on the server (used by apollo-client)
if (!process.browser) {
  global.fetch = fetch;
}

function create() {
  return new ApolloClient({
    ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once)
    networkInterface: createNetworkInterface({
      uri: 'https://api.graph.cool/simple/v1/cixmkt2ul01q00122mksg82pn', // Server URL (must be absolute)
      opts: {
        // Additional fetch() options like `credentials` or `headers`
        credentials: 'same-origin',
      },
    }),
  });
}

and on the other side in my lib def I have:

declare module 'react-apollo' {
  declare module.exports: any;
}

what should I type here(examples would be helpful) to have type checking?

Body: Start from this detailed article.


问:
Get response from API with jQuery
I'd like to type some stuff into an input field and then get a response from the API if the value exist or not.

The API will response with a true/ false value if the zipcode (12345) exist. http://192.168.100.100:8887/public?zipcode=12345

And here's my code so far:

```<code>$(function() {

    $('.positiveMessage, .negativeMessage').hide()
    $('#submitBtn').on('click', function() {
        var $zipcode = document.getElementById('searchZipCode').value
        $.getJSON({
            type: 'GET',
            url: 'http://192.168.100.100:8887/public?zipcode=' + $zipCode,
            success: result => {
                //Goes through the array
                $.each(result, function(i, info) {
                    $('body').append(info + '')
                })
            }
        })
    })
})
</code>```

As you can see I'd like to manipulate the API by adding a variable in the link.

答:
I added a simple if else statement and it worked out alright. Although I don't know if I should use this method or not:</p>

```<code>//Checks keys
if (result) {
    $('.positiveMessage').show()
} else {
    $('.negativeMessage').show()
}
</code>```

Title: Get response from API with jQuery

Body:
I'd like to type some stuff into an input field and then get a response from the API if the value exist or not.

The API will response with a true/ false value if the zipcode (12345) exist. http://192.168.100.100:8887/public?zipcode=12345

And here's my code so far:

$(function() {

    $('.positiveMessage, .negativeMessage').hide()
    $('#submitBtn').on('click', function() {
        var $zipcode = document.getElementById('searchZipCode').value
        $.getJSON({
            type: 'GET',
            url: 'http://192.168.100.100:8887/public?zipcode=' + $zipCode,
            success: result => {
                //Goes through the array
                $.each(result, function(i, info) {
                    $('body').append(info + '')
                })
            }
        })
    })
})

As you can see I'd like to manipulate the API by adding a variable in the link.

Body:
I added a simple if else statement and it worked out alright. Although I don't know if I should use this method or not:

//Checks keys
if (result) {
    $('.positiveMessage').show()
} else {
    $('.negativeMessage').show()
}


问:
How to get multiple select box values using jQuery?
How to get multiple select box values using jQuery?</p>

答:
Just use this</p>

```<code>$('#multipleSelect').change(function() {
    var selectedValues = $(this).val();
});
</code>```

Body:
Just use this

$('#multipleSelect').change(function() {
    var selectedValues = $(this).val();
});