问:
java.lang.UnsupportedOperationException: Reflective setAccessible(true) disabled
When I run my Ktor application with gradle run then I've got the following exception:

```<code>19:21:11.795 [main] DEBUG io.netty.util.internal.logging.InternalLoggerFactory - Using SLF4J as the default logging framework
19:21:11.810 [main] DEBUG io.netty.util.internal.PlatformDependent0 - -Dio.netty.noUnsafe: false
19:21:11.810 [main] DEBUG io.netty.util.internal.PlatformDependent0 - Java version: 11
19:21:11.811 [main] DEBUG io.netty.util.internal.PlatformDependent0 - sun.misc.Unsafe.theUnsafe: available
19:21:11.812 [main] DEBUG io.netty.util.internal.PlatformDependent0 - sun.misc.Unsafe.copyMemory: available
19:21:11.812 [main] DEBUG io.netty.util.internal.PlatformDependent0 - java.nio.Buffer.address: available
19:21:11.814 [main] DEBUG io.netty.util.internal.PlatformDependent0 - direct buffer constructor: unavailable
java.lang.UnsupportedOperationException: Reflective setAccessible(true) disabled
        at io.netty.util.internal.ReflectionUtil.trySetAccessible(ReflectionUtil.java:31)
        at io.netty.util.internal.PlatformDependent0$4.run(PlatformDependent0.java:225)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at io.netty.util.internal.PlatformDependent0.<clinit>(PlatformDependent0.java:219)
        at io.netty.util.internal.PlatformDependent.isAndroid(PlatformDependent.java:273)
        at io.netty.util.internal.PlatformDependent.<clinit>(PlatformDependent.java:92)
        at io.netty.channel.epoll.Native.loadNativeLibrary(Native.java:225)
        at io.netty.channel.epoll.Native.<clinit>(Native.java:57)
        at io.netty.channel.epoll.Epoll.<clinit>(Epoll.java:39)
        at io.ktor.server.netty.EventLoopGroupProxy$Companion.create(NettyApplicationEngine.kt:189)
        at io.ktor.server.netty.NettyApplicationEngine.<init>(NettyApplicationEngine.kt:74)
        at io.ktor.server.netty.EngineMain.main(EngineMain.kt:22)
19:21:11.814 [main] DEBUG io.netty.util.internal.PlatformDependent0 - java.nio.Bits.unaligned: available, true
19:21:11.815 [main] DEBUG io.netty.util.internal.PlatformDependent0 - jdk.internal.misc.Unsafe.allocateUninitializedArray(int): unavailable
java.lang.IllegalAccessException: class io.netty.util.internal.PlatformDependent0$6 cannot access class jdk.internal.misc.Unsafe (in module java.base) because module java.base does not export jdk.internal.misc to unnamed module @557caf28
        at java.base/jdk.internal.reflect.Reflection.newIllegalAccessException(Reflection.java:361)
        at java.base/java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:591)
        at java.base/java.lang.reflect.Method.invoke(Method.java:558)
        at io.netty.util.internal.PlatformDependent0$6.run(PlatformDependent0.java:335)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at io.netty.util.internal.PlatformDependent0.<clinit>(PlatformDependent0.java:326)
        at io.netty.util.internal.PlatformDependent.isAndroid(PlatformDependent.java:273)
        at io.netty.util.internal.PlatformDependent.<clinit>(PlatformDependent.java:92)
        at io.netty.channel.epoll.Native.loadNativeLibrary(Native.java:225)
        at io.netty.channel.epoll.Native.<clinit>(Native.java:57)
        at io.netty.channel.epoll.Epoll.<clinit>(Epoll.java:39)
        at io.ktor.server.netty.EventLoopGroupProxy$Companion.create(NettyApplicationEngine.kt:189)
        at io.ktor.server.netty.NettyApplicationEngine.<init>(NettyApplicationEngine.kt:74)
        at io.ktor.server.netty.EngineMain.main(EngineMain.kt:22)
</code>```

the content of build.gradle.kts file

```<code>plugins {
    application
    kotlin("jvm") version "1.3.61"
}

group = "io.flatmap"
version = "1.0-SNAPSHOT"

val ktor_version = "1.3.0"

repositories {
    mavenCentral()
    jcenter()
}

dependencies {
    implementation(kotlin("stdlib-jdk8"))
    compile("io.ktor:ktor-server-netty:$ktor_version")
    compile("io.ktor:ktor-server-core:$ktor_version")
    compile("ch.qos.logback:logback-classic:1.2.3")
    testCompile(group = "junit", name = "junit", version = "4.12")
}

tasks {
    compileKotlin {
        kotlinOptions.jvmTarget = "11"
    }
    compileTestKotlin {
        kotlinOptions.jvmTarget = "11"
    }
}

application {
    mainClassName = "io.ktor.server.netty.EngineMain"
}
</code>```

I am using Zulu OpenJDK 11:

```<code> java --version
openjdk 11.0.6 2020-01-14 LTS
OpenJDK Runtime Environment Zulu11.37+17-CA (build 11.0.6+10-LTS)
OpenJDK 64-Bit Server VM Zulu11.37+17-CA (build 11.0.6+10-LTS, mixed mode)
</code>```

What am I doing wrong?

答:
The access level of each object member cannot be increased anymore. The operation is not allowed anymore since Java 9 and has been hardly disabled in release 11.

You need to run this application with Java 8.

See https://www.oracle.com/technetwork/java/javase/9-relnote-issues-3704069.html (search for "setAccessible"). There is a new Object which must now be used to allow it again: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/reflect/AccessibleObject.html

Body:
When I run my Ktor application with gradle run then I've got the following exception:

19:21:11.795 [main] DEBUG io.netty.util.internal.logging.InternalLoggerFactory - Using SLF4J as the default logging framework
19:21:11.810 [main] DEBUG io.netty.util.internal.PlatformDependent0 - -Dio.netty.noUnsafe: false
19:21:11.810 [main] DEBUG io.netty.util.internal.PlatformDependent0 - Java version: 11
19:21:11.811 [main] DEBUG io.netty.util.internal.PlatformDependent0 - sun.misc.Unsafe.theUnsafe: available
19:21:11.812 [main] DEBUG io.netty.util.internal.PlatformDependent0 - sun.misc.Unsafe.copyMemory: available
19:21:11.812 [main] DEBUG io.netty.util.internal.PlatformDependent0 - java.nio.Buffer.address: available
19:21:11.814 [main] DEBUG io.netty.util.internal.PlatformDependent0 - direct buffer constructor: unavailable
java.lang.UnsupportedOperationException: Reflective setAccessible(true) disabled
        at io.netty.util.internal.ReflectionUtil.trySetAccessible(ReflectionUtil.java:31)
        at io.netty.util.internal.PlatformDependent0$4.run(PlatformDependent0.java:225)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at io.netty.util.internal.PlatformDependent0.<clinit>(PlatformDependent0.java:219)
        at io.netty.util.internal.PlatformDependent.isAndroid(PlatformDependent.java:273)
        at io.netty.util.internal.PlatformDependent.<clinit>(PlatformDependent.java:92)
        at io.netty.channel.epoll.Native.loadNativeLibrary(Native.java:225)
        at io.netty.channel.epoll.Native.<clinit>(Native.java:57)
        at io.netty.channel.epoll.Epoll.<clinit>(Epoll.java:39)
        at io.ktor.server.netty.EventLoopGroupProxy$Companion.create(NettyApplicationEngine.kt:189)
        at io.ktor.server.netty.NettyApplicationEngine.<init>(NettyApplicationEngine.kt:74)
        at io.ktor.server.netty.EngineMain.main(EngineMain.kt:22)
19:21:11.814 [main] DEBUG io.netty.util.internal.PlatformDependent0 - java.nio.Bits.unaligned: available, true
19:21:11.815 [main] DEBUG io.netty.util.internal.PlatformDependent0 - jdk.internal.misc.Unsafe.allocateUninitializedArray(int): unavailable
java.lang.IllegalAccessException: class io.netty.util.internal.PlatformDependent0$6 cannot access class jdk.internal.misc.Unsafe (in module java.base) because module java.base does not export jdk.internal.misc to unnamed module @557caf28
        at java.base/jdk.internal.reflect.Reflection.newIllegalAccessException(Reflection.java:361)
        at java.base/java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:591)
        at java.base/java.lang.reflect.Method.invoke(Method.java:558)
        at io.netty.util.internal.PlatformDependent0$6.run(PlatformDependent0.java:335)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at io.netty.util.internal.PlatformDependent0.<clinit>(PlatformDependent0.java:326)
        at io.netty.util.internal.PlatformDependent.isAndroid(PlatformDependent.java:273)
        at io.netty.util.internal.PlatformDependent.<clinit>(PlatformDependent.java:92)
        at io.netty.channel.epoll.Native.loadNativeLibrary(Native.java:225)
        at io.netty.channel.epoll.Native.<clinit>(Native.java:57)
        at io.netty.channel.epoll.Epoll.<clinit>(Epoll.java:39)
        at io.ktor.server.netty.EventLoopGroupProxy$Companion.create(NettyApplicationEngine.kt:189)
        at io.ktor.server.netty.NettyApplicationEngine.<init>(NettyApplicationEngine.kt:74)
        at io.ktor.server.netty.EngineMain.main(EngineMain.kt:22)

the content of build.gradle.kts file

plugins {
    application
    kotlin("jvm") version "1.3.61"
}

group = "io.flatmap"
version = "1.0-SNAPSHOT"

val ktor_version = "1.3.0"

repositories {
    mavenCentral()
    jcenter()
}

dependencies {
    implementation(kotlin("stdlib-jdk8"))
    compile("io.ktor:ktor-server-netty:$ktor_version")
    compile("io.ktor:ktor-server-core:$ktor_version")
    compile("ch.qos.logback:logback-classic:1.2.3")
    testCompile(group = "junit", name = "junit", version = "4.12")
}

tasks {
    compileKotlin {
        kotlinOptions.jvmTarget = "11"
    }
    compileTestKotlin {
        kotlinOptions.jvmTarget = "11"
    }
}

application {
    mainClassName = "io.ktor.server.netty.EngineMain"
}

I am using Zulu OpenJDK 11:

 java --version
openjdk 11.0.6 2020-01-14 LTS
OpenJDK Runtime Environment Zulu11.37+17-CA (build 11.0.6+10-LTS)
OpenJDK 64-Bit Server VM Zulu11.37+17-CA (build 11.0.6+10-LTS, mixed mode)

What am I doing wrong?


来源: stackexchange

问:
How to add new line in MemoEdit (DevExpress)
```<code>int maxLength = 90;
var sb = new StringBuilder();
DevExpress.XtraEditors.MemoEdit edit = sender as DevExpress.XtraEditors.MemoEdit;
foreach(string str in edit.Lines) {
   if(str.Length > maxLength) {
      e.Cancel = true;
      sb.AppendLine(memoShipMark.Text);
      return;
   }
}
</code>```

This not add new line it focus first line

答:
In C# \n is a new line syntax. It can use with built-in components in visual studio but can't use with devexpress's components.

After I search for a while, someone teach me I should use \r\n syntax and when I use. Oh! it's work with devexpress components.

Example

```<code>MemoEdit.Text = "data1: " + data1 + "\r\n" + "data2: " + data2;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
int maxLength = 90;
var sb = new StringBuilder();
DevExpress.XtraEditors.MemoEdit edit = sender as DevExpress.XtraEditors.MemoEdit;
foreach(string str in edit.Lines) {
   if(str.Length > maxLength) {
      e.Cancel = true;
      sb.AppendLine(memoShipMark.Text);
      return;
   }
}

This not add new line it focus first line

Body:
In C# \n is a new line syntax. It can use with built-in components in visual studio but can't use with devexpress's components.

After I search for a while, someone teach me I should use \r\n syntax and when I use. Oh! it's work with devexpress components.

Example

MemoEdit.Text = "data1: " + data1 + "\r\n" + "data2: " + data2;

ContentLicense: CC BY-SA 4.0


问:
MenuItem icon is not displaying correctly in RTL Layouts
In RTL, option menu item icon not displayed correctly!!
but in LTR, everything is displayed well and beautifully.

With the help of this command, I make the RTL program

```<code>getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
</code>```

My menu layout.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:gravity="start"
    android:layoutDirection="rtl"
    android:layout_gravity="start">
    <item
        android:id="@+id/action_more"
        android:icon="@drawable/ic_add_white_24dp"
        android:title=""
        app:showAsAction="always">
        <menu>
            <item
                android:id="@+id/action_settings"
                android:icon="@drawable/ic_wb_sunny_black_24dp"
                android:title="آیتم شماره 1"/>

            <item
                android:id="@+id/action_settings2"
                android:icon="@drawable/ic_star_black_24dp"
                android:title="آیتم شماره 2"/>

            <item
                android:id="@+id/action_settings3"
                android:icon="@drawable/ic_wb_sunny_black_24dp"
                android:title="آیتم شماره 3"/>
        </menu>
    </item>
</menu>
</code>```

Please help me to fix this.

Screenshot

答:
I faced the same problem in RTL layout, If you are using Support Library or AndroidX you can apply this easy fix:

In you project create new layout file in res -> layout with this name abc_list_menu_item_icon.xml.

Copy the code below to the file in step 1.

```<code><?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2007 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
           android:id="@+id/icon"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_gravity="center_vertical"
           android:layout_marginLeft="8dip"
           android:layout_marginRight="-8dip"
           android:layout_marginStart="8dip"
           android:layout_marginEnd="-8dip"
           android:layout_marginTop="8dip"
           android:layout_marginBottom="8dip"
           android:scaleType="centerInside"
           android:duplicateParentState="true"/>
</code>```

Body:
In RTL, option menu item icon not displayed correctly!!
but in LTR, everything is displayed well and beautifully.

With the help of this command, I make the RTL program

getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);

My menu layout.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:gravity="start"
    android:layoutDirection="rtl"
    android:layout_gravity="start">
    <item
        android:id="@+id/action_more"
        android:icon="@drawable/ic_add_white_24dp"
        android:title=""
        app:showAsAction="always">
        <menu>
            <item
                android:id="@+id/action_settings"
                android:icon="@drawable/ic_wb_sunny_black_24dp"
                android:title="آیتم شماره 1"/>

            <item
                android:id="@+id/action_settings2"
                android:icon="@drawable/ic_star_black_24dp"
                android:title="آیتم شماره 2"/>

            <item
                android:id="@+id/action_settings3"
                android:icon="@drawable/ic_wb_sunny_black_24dp"
                android:title="آیتم شماره 3"/>
        </menu>
    </item>
</menu>

Please help me to fix this.

Screenshot

Body:
I faced the same problem in RTL layout, If you are using Support Library or AndroidX you can apply this easy fix:

In you project create new layout file in res -> layout with this name abc_list_menu_item_icon.xml.

Copy the code below to the file in step 1.

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2007 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
           android:id="@+id/icon"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_gravity="center_vertical"
           android:layout_marginLeft="8dip"
           android:layout_marginRight="-8dip"
           android:layout_marginStart="8dip"
           android:layout_marginEnd="-8dip"
           android:layout_marginTop="8dip"
           android:layout_marginBottom="8dip"
           android:scaleType="centerInside"
           android:duplicateParentState="true"/>


问:
How do I package and run a simple command-line application with dependencies using maven?
I am brand new to both java and to maven, so this is likely very simple.

If I follow the maven2 hello world instructions here:

http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html

everything works OK.  If I then alter pom.xml to bring in a dependency from a remote repository, the files for this dependency get stored in ~/.m2/repository/new-dependency/.

Using the syntax in the hello world instructions to run the application requires that I add the absolute path to the dependency to my classpath (either by setting the environment variable or via the command line switch):

```<code>java -cp target/my-app-1.0-SNAPSHOT.jar:/.../.m2/.../new-dependency.jar com.mycompany.app.App
</code>```

This will obviously get unwieldy quickly :)

I suspect that this is not the usual way of running a java program and that I just need to read more about .jar files, but while I am doing so I would appreciate any tips on how to do this properly.

I am not using an IDE, btw.  vim from the command line.

Thanks!

Mike.

答:
You can use maven itself to run it, I believe it sets the classpath for you.

```<code>mvn compile
</code>```

will compile it
then you run:

```<code>mvn exec:java -Dexec.mainClass="com.mycompany.app.App"
</code>```

which will execute it.

You can see http://www.vineetmanohar.com/2009/11/3-ways-to-run-java-main-from-maven/ for some more info on ways to run (including passing command-line args to the thing you want to run)

Body:
I am brand new to both java and to maven, so this is likely very simple.

If I follow the maven2 hello world instructions here:

http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html

everything works OK.  If I then alter pom.xml to bring in a dependency from a remote repository, the files for this dependency get stored in ~/.m2/repository/new-dependency/.

Using the syntax in the hello world instructions to run the application requires that I add the absolute path to the dependency to my classpath (either by setting the environment variable or via the command line switch):

java -cp target/my-app-1.0-SNAPSHOT.jar:/.../.m2/.../new-dependency.jar com.mycompany.app.App

This will obviously get unwieldy quickly :)

I suspect that this is not the usual way of running a java program and that I just need to read more about .jar files, but while I am doing so I would appreciate any tips on how to do this properly.

I am not using an IDE, btw.  vim from the command line.

Thanks!

Mike.

Body:
You can use maven itself to run it, I believe it sets the classpath for you.

mvn compile

will compile it
then you run:

mvn exec:java -Dexec.mainClass="com.mycompany.app.App"

which will execute it.

You can see http://www.vineetmanohar.com/2009/11/3-ways-to-run-java-main-from-maven/ for some more info on ways to run (including passing command-line args to the thing you want to run)


问:
How to get POSTed JSON in Flask?
I'm trying to build a simple API using Flask, in which I now want to read some POSTed JSON. I do the POST with the Postman Chrome extension, and the JSON I POST is simply {"text":"lalala"}. I try to read the JSON using the following method:

```<code>@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
    content = request.json
    print content
    return uuid
</code>```

On the browser it correctly returns the UUID I put in the GET, but on the console, it just prints out None (where I expect it to print out the {"text":"lalala"}. Does anybody know how I can get the posted JSON from within the Flask method?

答:
Assuming that you have posted valid JSON,</p>

```<code>@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
    content = request.json
    print content['uuid']
    # Return data as JSON
    return jsonify(content)
</code>```

Title: How to get POSTed JSON in Flask?

Body:
I'm trying to build a simple API using Flask, in which I now want to read some POSTed JSON. I do the POST with the Postman Chrome extension, and the JSON I POST is simply {"text":"lalala"}. I try to read the JSON using the following method:

@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
    content = request.json
    print content
    return uuid

On the browser it correctly returns the UUID I put in the GET, but on the console, it just prints out None (where I expect it to print out the {"text":"lalala"}. Does anybody know how I can get the posted JSON from within the Flask method?

Body:
Assuming that you have posted valid JSON,

@app.route('/api/add_message/<uuid>', methods=['GET', 'POST'])
def add_message(uuid):
    content = request.json
    print content['uuid']
    # Return data as JSON
    return jsonify(content)


问:
Jquery show/hide not working until refresh
I have a checkout page that has three fieldsets:
fieldset id="1", fieldset id="2", fieldset id="3".  When the page loads, I need it to hide fieldsets 2 and 3 and only show fieldset 1.  This is what my jquery looks like:  </p>

```<code>$(document).ready(function(){
  $("#1").show();
  $("#2").hide();
  $("#3").hide();
  $("#4").hide();
});
</code>```

<p>When I load the page I can see fieldset 1 and fieldset 2.  If I refresh the page, it looks perfect, but upon first load, it's weird.  Any suggestions? </p>

答:
Notwithstanding other issues, your IDs are invalid, which will always cause unpredictable results.  Ids MUST begin with a letter.

Beyond that, it is difficult to answer your question without further insight into the code.

```<code>$(document).ready(function(){
  $("#el_1").show();
  $("#el_2, #el_3, #el_4").hide();
});
</code>```

Should all be valid jQuery, assuming that there is no ID collision (you can only use an ID once per page).

Body:
I have a checkout page that has three fieldsets:
fieldset id="1", fieldset id="2", fieldset id="3".  When the page loads, I need it to hide fieldsets 2 and 3 and only show fieldset 1.  This is what my jquery looks like:

$(document).ready(function(){
  $("#1").show();
  $("#2").hide();
  $("#3").hide();
  $("#4").hide();
});

When I load the page I can see fieldset 1 and fieldset 2.  If I refresh the page, it looks perfect, but upon first load, it's weird.  Any suggestions?

Body:
Notwithstanding other issues, your IDs are invalid, which will always cause unpredictable results.  Ids MUST begin with a letter.

Beyond that, it is difficult to answer your question without further insight into the code.

$(document).ready(function(){
  $("#el_1").show();
  $("#el_2, #el_3, #el_4").hide();
});

Should all be valid jQuery, assuming that there is no ID collision (you can only use an ID once per page).


问:
Switch statement throws error in TypeScript when attempting to handle enum values
I'm using the following while and switch-case loops. I'm trying to handle all the different enum values in the constants.Sides enum.

// EDIT Constants is imported at the top of the file.

import * as constants from '../constants'

// ... other code not included

let crossedSide: constants.Sides | undefined;
let loopGuard = 0;

while ((crossedSide = this.hasCrossedBorder()) && loopGuard < 2) {
  loopGuard += 1;

  switch (crossedSide) {
    case constants.Sides.TOP: { // THE ERROR HAPPENS HERE
      this.velocity.y = -this.velocity.y;
      break;
    }
    case constants.Sides.RIGHT: {
      this.velocity.x = -this.velocity.x;
      break;
    }
    case constants.Sides.BOTTOM: {
      this.velocity.y = -this.velocity.y;
      break;
    }
    case constants.Sides.LEFT: {
      this.velocity.x = -this.velocity.x;
      break;
    }
    default:
      break;
  }
}
```

<p>The enum is defined in <code>constants/index.ts</code> as follows:</p>

<pre class="lang-js prettyprint-override"><code>export enum Sides {
  TOP,
  RIGHT,
  BOTTOM,
  LEFT,
}
</code>```

However, an error is thrown at the constants.Sides.TOP switch-case option:

Type 'Sides.TOP' is not comparable to type 'Sides.RIGHT | Sides.BOTTOM | Sides.LEFT'.

答:
The problem lies in TypeScript handling the first enum value, i.e. TOP, as 0 i.e. falsy. This is why the while condition returns only the remaining three truthy enum values: RIGHT, BOTTOM and LEFT.

The issue is fixed by adding another value to the enumeration like so:

export enum Sides {
  NONE = 0,
  TOP,
  RIGHT,
  BOTTOM,
  LEFT,
}
```

This way also the TOP value will be truthy.

Body:
I'm using the following while and switch-case loops. I'm trying to handle all the different enum values in the constants.Sides enum.

// EDIT Constants is imported at the top of the file.

import * as constants from '../constants'

// ... other code not included

let crossedSide: constants.Sides | undefined;
let loopGuard = 0;

while ((crossedSide = this.hasCrossedBorder()) && loopGuard < 2) {
  loopGuard += 1;

  switch (crossedSide) {
    case constants.Sides.TOP: { // THE ERROR HAPPENS HERE
      this.velocity.y = -this.velocity.y;
      break;
    }
    case constants.Sides.RIGHT: {
      this.velocity.x = -this.velocity.x;
      break;
    }
    case constants.Sides.BOTTOM: {
      this.velocity.y = -this.velocity.y;
      break;
    }
    case constants.Sides.LEFT: {
      this.velocity.x = -this.velocity.x;
      break;
    }
    default:
      break;
  }
}

The enum is defined in constants/index.ts as follows:

export enum Sides {
  TOP,
  RIGHT,
  BOTTOM,
  LEFT,
}

However, an error is thrown at the constants.Sides.TOP switch-case option:

Type 'Sides.TOP' is not comparable to type 'Sides.RIGHT | Sides.BOTTOM | Sides.LEFT'.

Body:
The problem lies in TypeScript handling the first enum value, i.e. TOP, as 0 i.e. falsy. This is why the while condition returns only the remaining three truthy enum values: RIGHT, BOTTOM and LEFT.

The issue is fixed by adding another value to the enumeration like so:

export enum Sides {
  NONE = 0,
  TOP,
  RIGHT,
  BOTTOM,
  LEFT,
}

This way also the TOP value will be truthy.


问:
How I can select rows from a dataframe that do not match BUT group by id?
I'm trying to identify the values in a data frame that do not match based on id, but can't figure out how to do this.

```<code>a_id <- c(1,1,1,2,2,2,3,3,3)
a_no <- c(1,2,3,1,2,3,1,2,3)
a <- data.frame(a_id,a_no)
b_id <- c(1,1,1,2,2,3,3)
b_no <- c(1,2,3,1,3,2,3)
b <- data.frame(b_id,b_no)
</code>```

Looking for dataframe similar to this

```<code>output_id <- c(2,3)
output_no <- c(2,1)
output <- data.frame(output_id,output_no)
</code>```

I've tried to adjust the code here, but no luck: How I can select rows from a dataframe that do not match?

答:
We could use anti_join

```<code>library(dplyr)
anti_join(a, b, by = c("a_id" = "b_id", "a_no" = "b_no"))
#    a_id a_no
#1    2    2
#2    3    1
</code>```

Or with data.table

```<code>library(data.table)
setDT(a)[!b, on = .(a_id = b_id, a_no = b_no)]
</code>```

Body:
I'm trying to identify the values in a data frame that do not match based on id, but can't figure out how to do this.

a_id <- c(1,1,1,2,2,2,3,3,3)
a_no <- c(1,2,3,1,2,3,1,2,3)
a <- data.frame(a_id,a_no)
b_id <- c(1,1,1,2,2,3,3)
b_no <- c(1,2,3,1,3,2,3)
b <- data.frame(b_id,b_no)

Looking for dataframe similar to this

output_id <- c(2,3)
output_no <- c(2,1)
output <- data.frame(output_id,output_no)

I've tried to adjust the code here, but no luck: How I can select rows from a dataframe that do not match?

Body:
We could use anti_join

library(dplyr)
anti_join(a, b, by = c("a_id" = "b_id", "a_no" = "b_no"))
#    a_id a_no
#1    2    2
#2    3    1

Or with data.table

library(data.table)
setDT(a)[!b, on = .(a_id = b_id, a_no = b_no)]


问:
Why is there no decent sql parser?
I'm currently doing some oracle sql analysis and often encounter valid sql statement that can not be properly parsed by various sql parsers. Either they fail parsing it, or their abstract syntax tree generated is somehow messed up. It seems that the only parser that can really handle oracle sql is their own one that is not publicly available and cannot be obtained as a stand-alone parser.

I'm aware that there are different sql grammars and complying to all may not be possible.
But even parsers that claim to be Oracle SQL parsers do not succeed in all cases.

What do you think are the main reasons that make it hard to implement sql parsers in general or oracle sql parsers in particular?

Best,
Will

答:
When a manufacturer claims to support a language X, he means "something like the X standard" but not the standard.   Manufacturers for historical reasons implement language X before the standard was as standard, so they start on the wrong foot; trying to make their version match the standard usually breaks their large base of user code; and they always want to add their own goodies to lock in their users.

This is true for SQL, C, C++... the only languages I know of where people try really hard to match the standard is Ada, and even it comes in multiple dialects.  (Look what browsers accept!).

So you can't expect a off-the-shelf generic SQL parser to parse PLSQL.  You really have to have a PLSQL parser.  And these are hard to build as the documentation is poor, Oracle has no reason to fix it, and certainly has no motivation to help the grammar builder.

My company (Semantic Designs) has a PLSQL parser that covers 10g pretty well (Oracle's documentation is poor...we keep finding variations from the reference docuements) and does most of 11g.  We've run it across millions of line of PLSQL code.

Title: Why is there no decent sql parser?


问:
Create special binary search tree using C++
I want to create a Binary search tree which has special Nodes. There should be three classes of Nodes, Internal Node, External Node and Root node, each inheriting a common parent Node and each type of node will have some unique function. Is it possible to create such a BST. The problem I am facing is suppose the first node I insert into the tree becomes the root node. The next node I insert will become External Node. Now if I insert another node then the external node has to become a internal node and the new node will become the external node. Also I cannot find a way to navigate through the tree from one node to another as the nodes will be of different types. Can a tree of this type be created. If yes then give me some suggestions of how this can be done.</p>

答:
If I understand correctly, you're worried about how objects in one class - External - need to become objects of another class - Internal. This, when C++ is a statically-typed language: Types (including the classes of objects) are determined at compile-time. Right?

Well, you can achieve this in at least one of two ways:

When an External node becomes Internal, delete the External node and replace it with an Internal node, properly initialized (e.g. to point at the new External node).

Give up on External and Internal being discrete types, and just check for children and parents to determine the node type dynamically.

Some more relevant reading material on these matters:

(Programming language) type systems in this Wikipedia page.

This SO question: What is duck typing?

The Circle-vs-Eclipse problem, and specifically the desire to stretch circles into ellipses.


问:
How do I define a static variable in base class that can be called in generic methods?
I have an extremely complicated relational database, which is causing me to use the same code over and over again. I'm trying to clean it up using a fairly sophisticated TableRow class, however I've came across one major problem. The best way I can explain what I'm trying to do is by some example code:

```<code>public abstract class TableRow
{
    public abstract string TableName { get; }
    public abstract string PrimaryKey { get; }

    //there's a lot of these sort of methods for multi-to-multi links, links by two columns, etc
    protected T GetLinkedRow<T>() where T : TableRow
    {
        //here I need to get TableName and PrimaryKey (without creating a new instance of T)
    }
 }

 public class Person : TableRow
 {
    public override string TableName { get { return "People"; } }
    public override string PrimaryKey { get { return "PersonID"; } }
 }

 public class Dog : TableRow
 {
    public override string TableName { get { return "Dogs"; } }
    public override string PrimaryKey { get { return "DogID"; } }

    public Person GetOwner() { return GetLinkedRow<Person>(); }
 }
</code>```

Now I realise this is not the way to go about what I'm trying to achieve, because I COULD make a class that has a variable value for TableName or PrimaryKey, but I'm not going to. I'd like to be able to override a static property, but I know this is not possible. I did previously have a class per table, but that meant there was 70 fairly useless classes and that's what I'm trying to avoid. What would be a better way to go around this sort of issue?

Update:

I eventually went with creating a new instance of T to get the TableName, as I will be initialising the new instance anyway. Although SLaks' solution is much better than this, it doesn't guarantee that the derived class has the TableName and PrimaryKey attributes. For the majority of people, SLaks' solution will be more appropriate, so I will mark that as the accepted answer.

```<code>protected T GetLinkedRow<T>() where T : TableRow, new()
{
    T row = new T();
    DbDataReader reader = ExecuteReader("SELECT * FROM [" + row.TableName + "] WHERE [" + this.PrimaryKey + "] = " + this.ID);
    if(!reader.Read())
        throw new Exception("No linked row found");
    row.Load(reader);
    return row;
}

//here's the reason I didn't really want to do this in the first place. Many-to-many relationship. quite messy
protected IEnumerable<T> GetLinkedRows<T>(string junctionTable) where T : TableRow, new()
{
    T row = new T();
    DbDataReader reader = ExecuteReader("SELECT * FROM [" + row.TableName + "] INNER JOIN [" + junctionTable + "] ON [" + row.TableName + "].[" + row.PrimaryKey + "] = [" + junctionTable + "].[" + row.PrimaryKey + "] WHERE [" + junctionTable + "].[" + this.PrimaryKey + "] = " + this.ID;
    while(reader.Read()) {
        row.Load(reader);
        yield return row;
        if(reader.HasRows)
            row = new T();
    }
}
</code>```

答:
It is completely impossible to call a virtual method (get_TableName) without an instance.

Instead, you can use an attribute on the class, and call typeof(T).GetCustomAttributes(typeof(YourAttribute), false)

Body:
I have an extremely complicated relational database, which is causing me to use the same code over and over again. I'm trying to clean it up using a fairly sophisticated TableRow class, however I've came across one major problem. The best way I can explain what I'm trying to do is by some example code:

public abstract class TableRow
{
    public abstract string TableName { get; }
    public abstract string PrimaryKey { get; }

    //there's a lot of these sort of methods for multi-to-multi links, links by two columns, etc
    protected T GetLinkedRow<T>() where T : TableRow
    {
        //here I need to get TableName and PrimaryKey (without creating a new instance of T)
    }
 }

 public class Person : TableRow
 {
    public override string TableName { get { return "People"; } }
    public override string PrimaryKey { get { return "PersonID"; } }
 }

 public class Dog : TableRow
 {
    public override string TableName { get { return "Dogs"; } }
    public override string PrimaryKey { get { return "DogID"; } }

    public Person GetOwner() { return GetLinkedRow<Person>(); }
 }

Now I realise this is not the way to go about what I'm trying to achieve, because I COULD make a class that has a variable value for TableName or PrimaryKey, but I'm not going to. I'd like to be able to override a static property, but I know this is not possible. I did previously have a class per table, but that meant there was 70 fairly useless classes and that's what I'm trying to avoid. What would be a better way to go around this sort of issue?

Update:

I eventually went with creating a new instance of T to get the TableName, as I will be initialising the new instance anyway. Although SLaks' solution is much better than this, it doesn't guarantee that the derived class has the TableName and PrimaryKey attributes. For the majority of people, SLaks' solution will be more appropriate, so I will mark that as the accepted answer.

protected T GetLinkedRow<T>() where T : TableRow, new()
{
    T row = new T();
    DbDataReader reader = ExecuteReader("SELECT * FROM [" + row.TableName + "] WHERE [" + this.PrimaryKey + "] = " + this.ID);
    if(!reader.Read())
        throw new Exception("No linked row found");
    row.Load(reader);
    return row;
}

//here's the reason I didn't really want to do this in the first place. Many-to-many relationship. quite messy
protected IEnumerable<T> GetLinkedRows<T>(string junctionTable) where T : TableRow, new()
{
    T row = new T();
    DbDataReader reader = ExecuteReader("SELECT * FROM [" + row.TableName + "] INNER JOIN [" + junctionTable + "] ON [" + row.TableName + "].[" + row.PrimaryKey + "] = [" + junctionTable + "].[" + row.PrimaryKey + "] WHERE [" + junctionTable + "].[" + this.PrimaryKey + "] = " + this.ID;
    while(reader.Read()) {
        row.Load(reader);
        yield return row;
        if(reader.HasRows)
            row = new T();
    }
}


问:
Unnecessary NullReferenceException?
Why do I get a NullReferenceException in the following code?

```<code>private string FileR ( string name )
{
    string[] content = ReadSite(name, Protocol.read, url);
    Request_Template newCon;
    string[] final = new string[content.Length];

    for (int i = 0; i < content.Length; i++)
    {
        if (content[i].Equals(null))
        {
            return "content [" + i + "] returns null";
        }
        newCon = JsonSerializer.Deserialize<Request_Template>(content[i]);

        if (newCon.Sender.Contains(myAccount.Username))
        {
            newCon.Sender = "Me";
        }

        string sender = newCon.Sender;
        string message = newCon.Message;
        final[i] = sender + ":\t" + message;
    }

    string nFinal = string.Concat(final);

    Thread.Sleep(10);
    return nFinal;
}

string[] ReadSite(string filename, Protocol p, string uri)
{
    Read_Template temp = new Read_Template
    {
        Chat = filename,
        Code = key1
    };
    string myUrl = JsonSerializer.Serialize(temp);

    WebClient web = new WebClient();
    Stream stream = web.OpenRead(uri + "/" + myUrl);

    int length = 0;
    while (new StreamReader(stream).ReadLine() != null)
    {
        length++;
    }
    string[] content = new string[length];

    using (StreamReader reader = new StreamReader(stream))
    {
        for (int i = 0; i < length; i++)
        {
            content[i] = reader.ReadLine();
        }
    }

    return content;
}
</code>```

I've tried using the debugging tools with no avail.  When I ran the code, it said that the error came from string [] final = new string [content.Length];
 and for (int i = 0; i < content.Length; i++).That lead me to assume that content was null. But when I used the watch window and it said that the variable content cannot be determined. How do I fix this?

答:
I strongly suspect that the problem is actually here:

if (content[i].Equals(null))
```

<p>If <code>content[i]</code> is genuinely null, then calling <code>content[i].Equals</code> will throw a <code>NullReferenceException</code>. That test should be written as:</p>

<pre class="lang-cs prettyprint-override"><code>if (content[i] is null)`
</code>```

Or (for C# 6 or older):

if (content[i] == null)`
```

<p>Now if <code>ReadSite</code> didn't have a bug in, you shouldn't need that check at all - because <code>ReadSite</code> should return an array of non-null string references. However, the way that you're populating the array is broken. You're currently:</p>

<ul>
<li>Creating a <code>StreamReader</code> around the stream</li>
<li>Reading from the reader until you run out of data</li>
<li>Creating a new array of the "right" length</li>
<li>Creating another <code>StreamReader</code> around the same stream - which is by now at the end</li>
<li>Reading from the reader however many times you read a line originally</li>
</ul>

<p>Because the stream is already at the end, <code>ReadLine()</code> is going to return <code>null</code> on every iteration.</p>

<p>Instead, you should just read <em>once</em>, populating a list as you go, like this:</p>

<pre class="lang-cs prettyprint-override"><code>List<string> content = new List<string>();
using (var stream = web.OpenRead(uri + "/" + myUrl))
{
    using (var reader = new StreamReader(stream))
    {
        string line;
        while ((line = reader.ReadLine()) is object)
        {
            content.Add(line);
        }
    }
}
return content;
</code>```

That's returning a List<string>, so you'd want to change your ReadSite return type to List<string> or perhaps IReadOnlyList<string>. If you really need it to return an array, you could return content.ToArray() instead.

(Ideally, move to using HttpClient as well, but that's a different story.)

Title: Unnecessary NullReferenceException?

Body:
Why do I get a NullReferenceException in the following code?

private string FileR ( string name )
{
    string[] content = ReadSite(name, Protocol.read, url);
    Request_Template newCon;
    string[] final = new string[content.Length];

    for (int i = 0; i < content.Length; i++)
    {
        if (content[i].Equals(null))
        {
            return "content [" + i + "] returns null";
        }
        newCon = JsonSerializer.Deserialize<Request_Template>(content[i]);

        if (newCon.Sender.Contains(myAccount.Username))
        {
            newCon.Sender = "Me";
        }

        string sender = newCon.Sender;
        string message = newCon.Message;
        final[i] = sender + ":\t" + message;
    }

    string nFinal = string.Concat(final);

    Thread.Sleep(10);
    return nFinal;
}

string[] ReadSite(string filename, Protocol p, string uri)
{
    Read_Template temp = new Read_Template
    {
        Chat = filename,
        Code = key1
    };
    string myUrl = JsonSerializer.Serialize(temp);

    WebClient web = new WebClient();
    Stream stream = web.OpenRead(uri + "/" + myUrl);

    int length = 0;
    while (new StreamReader(stream).ReadLine() != null)
    {
        length++;
    }
    string[] content = new string[length];

    using (StreamReader reader = new StreamReader(stream))
    {
        for (int i = 0; i < length; i++)
        {
            content[i] = reader.ReadLine();
        }
    }

    return content;
}

I've tried using the debugging tools with no avail.  When I ran the code, it said that the error came from string [] final = new string [content.Length];
 and for (int i = 0; i < content.Length; i++).That lead me to assume that content was null. But when I used the watch window and it said that the variable content cannot be determined. How do I fix this?

Body:
I strongly suspect that the problem is actually here:

if (content[i].Equals(null))

If content[i] is genuinely null, then calling content[i].Equals will throw a NullReferenceException. That test should be written as:

if (content[i] is null)`

Or (for C# 6 or older):

if (content[i] == null)`

Now if ReadSite didn't have a bug in, you shouldn't need that check at all - because ReadSite should return an array of non-null string references. However, the way that you're populating the array is broken. You're currently:

Creating a StreamReader around the stream

Reading from the reader until you run out of data

Creating a new array of the "right" length

Creating another StreamReader around the same stream - which is by now at the end

Reading from the reader however many times you read a line originally

Because the stream is already at the end, ReadLine() is going to return null on every iteration.

Instead, you should just read once, populating a list as you go, like this:

List<string> content = new List<string>();
using (var stream = web.OpenRead(uri + "/" + myUrl))
{
    using (var reader = new StreamReader(stream))
    {
        string line;
        while ((line = reader.ReadLine()) is object)
        {
            content.Add(line);
        }
    }
}
return content;

That's returning a List<string>, so you'd want to change your ReadSite return type to List<string> or perhaps IReadOnlyList<string>. If you really need it to return an array, you could return content.ToArray() instead.

(Ideally, move to using HttpClient as well, but that's a different story.)


问:
No qualifying bean of type 'com.netflix.client.config.IClientConfig' available:expected at least 1 bean which qualifies as autowire candidate

I'm creating a loadbalancer using Netflix round ribbon but i am not able to
  auto wire IClientConfig this object.

I tried this also
@SpringBootApplication(scanBasePackages{"com.netflix.client.confg.IClientConfig"})

but this is also not working for me.

I'm getting this exception

org.spring framework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.netflix.client.config.IClientConfig' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

答:
I suspect your dependencies are not configured correctly.
Is ribbon-core added as compile dependency in build.gradle or pom.xml?

please check if you have

```<code>runtime group: 'com.netflix.ribbon', name: 'ribbon-core', version: '2.7.17'
</code>```

or

```<code><dependency>
    <groupId>com.netflix.ribbon</groupId>
    <artifactId>ribbon-core</artifactId>
    <version>2.7.17</version>
    <scope>runtime</scope>
</dependency>
</code>```

Body:
I suspect your dependencies are not configured correctly.
Is ribbon-core added as compile dependency in build.gradle or pom.xml?

please check if you have

runtime group: 'com.netflix.ribbon', name: 'ribbon-core', version: '2.7.17'

or

<dependency>
    <groupId>com.netflix.ribbon</groupId>
    <artifactId>ribbon-core</artifactId>
    <version>2.7.17</version>
    <scope>runtime</scope>
</dependency>


问:
How to use other html file if consumer is on mobile?
So I have a problem idk how to let my consumer see my mobile html i used:
But for some reason it doesnt want to work do you have nay suggestions?</p>

```<code>    if (screen.width <= 500) {
    document.location = "webapp.html";
    }
    </script> ```

</code>```

答:
Have you tried using window.location.href = "webapp.html" instead of what you are using?

Also you can try that thing before the page loads. If you are using PHP with CodeIgniter you could use the User Agent class and detect what device is entering the page and after that redirect to the according page.

Body:
So I have a problem idk how to let my consumer see my mobile html i used:
But for some reason it doesnt want to work do you have nay suggestions?

    if (screen.width <= 500) {
    document.location = "webapp.html";
    }
    </script> ```


问:
px unit width resolution problem in screen
In this setup

```<code><div class="a">

</div>
</code>```

```<code>.a {
   width: 400px;
   height: 600px;
}

</code>```

if the screen resolution is 1600*1200, will the div's width be 25% of the screen in the browser ?

if the screen resolution is 4000*2400, will the div's width be 10% of the screen in the browser ?

I want to be always 25%.

If I use percent to set the width, div will shrink automatically when browser is not in full screen.

答:
Try this out use % instead of px. % are more responsive and will adjust to any screen resolution

```<code>.a{
  width: 40%;
  height: 60%;
}
</code>```

Body:
In this setup

.a {
   width: 400px;
   height: 600px;
}

if the screen resolution is 1600*1200, will the div's width be 25% of the screen in the browser ?

if the screen resolution is 4000*2400, will the div's width be 10% of the screen in the browser ?

I want to be always 25%.

If I use percent to set the width, div will shrink automatically when browser is not in full screen.

Body:
Try this out use % instead of px. % are more responsive and will adjust to any screen resolution

.a{
  width: 40%;
  height: 60%;
}


问:
Set MySQL timestamp to random time within past 24 hours
I have a timestamp column in my MySQL table.

I'm wanting to set this timestamp to a random time within the past 24 hours for all rows in the table.

I know I can update all the rows doing this:

```<code>UPDATE table SET timestamp =
</code>```

But I can't find if there's a way to set a random timestamp that's occurred within the past 24 hours so that each row has a different time.

答:
You can use:</p>

```<code>UPDATE table
    SET timestamp = now() - interval floor((24*60*60)*rand()) second;
</code>```

Body:
I have a timestamp column in my MySQL table.

I'm wanting to set this timestamp to a random time within the past 24 hours for all rows in the table.

I know I can update all the rows doing this:

UPDATE table SET timestamp =

But I can't find if there's a way to set a random timestamp that's occurred within the past 24 hours so that each row has a different time.

Body:
You can use:

UPDATE table
    SET timestamp = now() - interval floor((24*60*60)*rand()) second;


问:
How do I implement a HTML cache for a PHP site?
What is the best way of implementing a cache for a PHP site? Obviously, there are some things that shouldn't be cached (for example search queries), but I want to find a good solution that will make sure that I avoid the 'digg effect'.

I know there is WP-Cache for WordPress, but I'm writing a custom solution that isn't built on WP. I'm interested in either writing my own cache (if it's simple enough), or you could point me to a nice, light framework. I don't know much Apache though, so if it was a PHP framework then it would be a better fit.

Thanks.

答:
Project Gazelle (an open source torrent site) provides a step by step guide on setting up Memcached on the site which you can easily use on any other website you might want to set up which will handle a lot of traffic.

Grab down the source and read the documentation.

OwnerDisplayName: different

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: different

OwnerDisplayName: chrisntr


问:
javascript regular expression
How do you write a JS regular expression to extract the first "2" from "/?page=2&promo_id=1234". (ie page number 2)

Thanks!

答:
```<code>var extractPageNumber = function(s) {
  var r=/page=(\d+)/, m=(""+s).match(r);
  return (m) ? Number(m[1]) : undefined;
};
extractPageNumber("/?page=2&promo_id=1234"); // => 2
extractPageNumber("/?page=321&promo_id=1234"); // => 321
extractPageNumber("foobar"); // => undefined
</code>```

Title: javascript regular expression


问:
Dynamic name dataframe R for loop
I am trying to produce 16 dataframes each with the name of the 16 different proteins, the code I have tried doesn't work</p>

```<code>for (i in seq(1,len_TSPAN)){
  temp_TSPAN <- TSPANS$V1[i]
  print(temp_TSPAN)
  paste(temp_TSPAN) <- data.frame(Lum_A_Q1_means = rep(NA, 67), Lum_A_Q2_means = rep(NA,67),
                            Lum_A_Q3_means = rep(NA, 67), Lum_A_Q4_means = rep(NA,67),
                            Lum_B_Q1_means = rep(NA, 67), Lum_B_Q2_means = rep(NA,67),
                            Lum_B_Q3_means = rep(NA, 67), Lum_B_Q4_means = rep(NA,67),
                            Her_2_Q1_means = rep(NA, 67), Her_2_Q2_means = rep(NA,67),
                            Her_2_Q3_means = rep(NA, 67), Her_2_Q4_means = rep(NA,67),
                            Basal_Q1_means = rep(NA, 67), Basal_Q2_means = rep(NA,67),
                            Basal_Q3_means = rep(NA, 67), Basal_Q4_means = rep(NA,67),
                            Normal_Q1_means = rep(NA, 67), Normal_Q2_means = rep(NA,67),
                            Normal_Q3_means = rep(NA, 67), Normal_Q4_means = rep(NA,67))
}
</code>```

答:
paste on the lhs of <- shouldd be replaced by assign if we want to create multiple objects in the global env (not recommended though)

```<code>for (i in seq(1,len_TSPAN)){
  temp_TSPAN <- TSPANS$V1[i]
    print(temp_TSPAN)
    assign(as.character(temp_TSPAN), value = data.frame(Lum_A_Q1_means = rep(NA, 67), Lum_A_Q2_means = rep(NA,67),
                            Lum_A_Q3_means = rep(NA, 67), Lum_A_Q4_means = rep(NA,67),
                            Lum_B_Q1_means = rep(NA, 67), Lum_B_Q2_means = rep(NA,67),
                            Lum_B_Q3_means = rep(NA, 67), Lum_B_Q4_means = rep(NA,67),
                            Her_2_Q1_means = rep(NA, 67), Her_2_Q2_means = rep(NA,67),
                            Her_2_Q3_means = rep(NA, 67), Her_2_Q4_means = rep(NA,67),
                            Basal_Q1_means = rep(NA, 67), Basal_Q2_means = rep(NA,67),
                            Basal_Q3_means = rep(NA, 67), Basal_Q4_means = rep(NA,67),
                            Normal_Q1_means = rep(NA, 67), Normal_Q2_means = rep(NA,67),
                            Normal_Q3_means = rep(NA, 67), Normal_Q4_means = rep(NA,67))
                            )
}
</code>```

It seems that we are creating the same 'data.frame' object in each loop.  It may be easier with replicate and store in a list

```<code>lst1 <- replicate(len_TSPAN),
           data.frame(Lum_A_Q1_means = rep(NA, 67), Lum_A_Q2_means = rep(NA,67),
                            Lum_A_Q3_means = rep(NA, 67), Lum_A_Q4_means = rep(NA,67),
                            Lum_B_Q1_means = rep(NA, 67), Lum_B_Q2_means = rep(NA,67),
                            Lum_B_Q3_means = rep(NA, 67), Lum_B_Q4_means = rep(NA,67),
                            Her_2_Q1_means = rep(NA, 67), Her_2_Q2_means = rep(NA,67),
                            Her_2_Q3_means = rep(NA, 67), Her_2_Q4_means = rep(NA,67),
                            Basal_Q1_means = rep(NA, 67), Basal_Q2_means = rep(NA,67),
                            Basal_Q3_means = rep(NA, 67), Basal_Q4_means = rep(NA,67),
                            Normal_Q1_means = rep(NA, 67), Normal_Q2_means = rep(NA,67),
                            Normal_Q3_means = rep(NA, 67), Normal_Q4_means = rep(NA,67)), simplify = FALSE)
</code>```

Title: Dynamic name dataframe R for loop

Body:
I am trying to produce 16 dataframes each with the name of the 16 different proteins, the code I have tried doesn't work

for (i in seq(1,len_TSPAN)){
  temp_TSPAN <- TSPANS$V1[i]
  print(temp_TSPAN)
  paste(temp_TSPAN) <- data.frame(Lum_A_Q1_means = rep(NA, 67), Lum_A_Q2_means = rep(NA,67),
                            Lum_A_Q3_means = rep(NA, 67), Lum_A_Q4_means = rep(NA,67),
                            Lum_B_Q1_means = rep(NA, 67), Lum_B_Q2_means = rep(NA,67),
                            Lum_B_Q3_means = rep(NA, 67), Lum_B_Q4_means = rep(NA,67),
                            Her_2_Q1_means = rep(NA, 67), Her_2_Q2_means = rep(NA,67),
                            Her_2_Q3_means = rep(NA, 67), Her_2_Q4_means = rep(NA,67),
                            Basal_Q1_means = rep(NA, 67), Basal_Q2_means = rep(NA,67),
                            Basal_Q3_means = rep(NA, 67), Basal_Q4_means = rep(NA,67),
                            Normal_Q1_means = rep(NA, 67), Normal_Q2_means = rep(NA,67),
                            Normal_Q3_means = rep(NA, 67), Normal_Q4_means = rep(NA,67))
}

Body:
paste on the lhs of <- shouldd be replaced by assign if we want to create multiple objects in the global env (not recommended though)

for (i in seq(1,len_TSPAN)){
  temp_TSPAN <- TSPANS$V1[i]
    print(temp_TSPAN)
    assign(as.character(temp_TSPAN), value = data.frame(Lum_A_Q1_means = rep(NA, 67), Lum_A_Q2_means = rep(NA,67),
                            Lum_A_Q3_means = rep(NA, 67), Lum_A_Q4_means = rep(NA,67),
                            Lum_B_Q1_means = rep(NA, 67), Lum_B_Q2_means = rep(NA,67),
                            Lum_B_Q3_means = rep(NA, 67), Lum_B_Q4_means = rep(NA,67),
                            Her_2_Q1_means = rep(NA, 67), Her_2_Q2_means = rep(NA,67),
                            Her_2_Q3_means = rep(NA, 67), Her_2_Q4_means = rep(NA,67),
                            Basal_Q1_means = rep(NA, 67), Basal_Q2_means = rep(NA,67),
                            Basal_Q3_means = rep(NA, 67), Basal_Q4_means = rep(NA,67),
                            Normal_Q1_means = rep(NA, 67), Normal_Q2_means = rep(NA,67),
                            Normal_Q3_means = rep(NA, 67), Normal_Q4_means = rep(NA,67))
                            )
}

It seems that we are creating the same 'data.frame' object in each loop.  It may be easier with replicate and store in a list

lst1 <- replicate(len_TSPAN),
           data.frame(Lum_A_Q1_means = rep(NA, 67), Lum_A_Q2_means = rep(NA,67),
                            Lum_A_Q3_means = rep(NA, 67), Lum_A_Q4_means = rep(NA,67),
                            Lum_B_Q1_means = rep(NA, 67), Lum_B_Q2_means = rep(NA,67),
                            Lum_B_Q3_means = rep(NA, 67), Lum_B_Q4_means = rep(NA,67),
                            Her_2_Q1_means = rep(NA, 67), Her_2_Q2_means = rep(NA,67),
                            Her_2_Q3_means = rep(NA, 67), Her_2_Q4_means = rep(NA,67),
                            Basal_Q1_means = rep(NA, 67), Basal_Q2_means = rep(NA,67),
                            Basal_Q3_means = rep(NA, 67), Basal_Q4_means = rep(NA,67),
                            Normal_Q1_means = rep(NA, 67), Normal_Q2_means = rep(NA,67),
                            Normal_Q3_means = rep(NA, 67), Normal_Q4_means = rep(NA,67)), simplify = FALSE)


问:
Getting unresolved identifier error while building firebase login
I am getting unresolved identifier error for the email and password variables. Here is the code for the view controller, I think it's an issue with the curly brackets and where they are placed but have messed with it for a little while and can't figure it out. I am trying to get it so when the user enters their email/password it sends the string to the database so they can use it to log in in the future.</p>

```<code>import UIKit
import FirebaseAuth
import Firebase

class SignUpViewController: UIViewController {

    @IBOutlet weak var FirstNameTextField: UITextField!
    @IBOutlet weak var LastNameTextField: UITextField!
    @IBOutlet weak var EmailTextField: UITextField!
    @IBOutlet weak var PasswordTextField: UITextField!
    @IBOutlet weak var SignUpButton: UIButton!
    @IBOutlet weak var ErrorLabel: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()

         setUpElements()
        // Do any additional setup after loading the view.
    }

    func setUpElements() {

        //Hide error label
        ErrorLabel.alpha = 0

        //Style the elements
        Utilities.styleTextField(FirstNameTextField)

        Utilities.styleTextField(LastNameTextField)

        Utilities.styleTextField(EmailTextField)

        Utilities.styleTextField(PasswordTextField)

        Utilities.styleFilledButton(SignUpButton)

    }

    func Validatefields () -> String? {
        //Check that all fields are filled in
        if FirstNameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
           LastNameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
           EmailTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
           PasswordTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" {

            return "Please fill in all fields."
        }

        //Check if the password is secure
        let cleanedPassword = PasswordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)

        if Utilities.isPasswordValid(cleanedPassword) == false {

            //password isn't secure enough
            return "Please make sure your password is at least 8 characters, contains a special character and a number."

        }

        return nil
    }

    @IBAction func SignUpTapped(_ sender: Any) {
        //Validate Fields
        let error = Validatefields()

        if error != nil {
            //something wrong with fields
           showError(error!)

        }

        else {

            //Create User
            Auth.auth().createUser(withEmail: email, password: password) { (result, err) in
                //Check for errors
                if err != nil {

                    //there was an error
                    self.showError("Error Creating User")

                }
                else {
                    // Create cleaned (No white spaces) version of data
                    let Firstname = FirstNameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
                    let LastName = LastNameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
                    let email2 = EmailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
                    let password2 = PasswordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)

                    //User was successfully created
                    let db = Firestore.firestore()

                    db.collection("users").addDocument(data: ["Firstname":firstName,"LastName":lastName, "uid": result!.user.uid ])  {(error) in

                        if error != nil {
                            //Show error message
                            self.showError("User FirstName and Lastname couldn't be saved, You should still be able to log in.")

                        }

                    }
                    //Transition to home screen
                    func Transitiontohome () {

                let homeViewController = storyboard?.instantiateViewController(identifier:Constants.Storyboard.homeViewController) as?
                    HomeViewController

                        view.window?.rootViewController = homeViewController
                        view.window?.makeKeyAndVisible()
                    }

            }

        }

    }

    }
    func showError (_ message:String) {
    ErrorLabel.text = message
    ErrorLabel.alpha = 1
}
}
</code>```

答:
You have to replace email with self.EmailTextField.text and password with self.PasswordTextField.text, so updated code

```<code>Auth.auth().createUser(withEmail: self.EmailTextField.text, password: self.PasswordTextField.text) { (result, err) in
</code>```

Body:
I am getting unresolved identifier error for the email and password variables. Here is the code for the view controller, I think it's an issue with the curly brackets and where they are placed but have messed with it for a little while and can't figure it out. I am trying to get it so when the user enters their email/password it sends the string to the database so they can use it to log in in the future.

import UIKit
import FirebaseAuth
import Firebase

class SignUpViewController: UIViewController {

    @IBOutlet weak var FirstNameTextField: UITextField!
    @IBOutlet weak var LastNameTextField: UITextField!
    @IBOutlet weak var EmailTextField: UITextField!
    @IBOutlet weak var PasswordTextField: UITextField!
    @IBOutlet weak var SignUpButton: UIButton!
    @IBOutlet weak var ErrorLabel: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()

         setUpElements()
        // Do any additional setup after loading the view.
    }

    func setUpElements() {

        //Hide error label
        ErrorLabel.alpha = 0

        //Style the elements
        Utilities.styleTextField(FirstNameTextField)

        Utilities.styleTextField(LastNameTextField)

        Utilities.styleTextField(EmailTextField)

        Utilities.styleTextField(PasswordTextField)

        Utilities.styleFilledButton(SignUpButton)

    }

    func Validatefields () -> String? {
        //Check that all fields are filled in
        if FirstNameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
           LastNameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
           EmailTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
           PasswordTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" {

            return "Please fill in all fields."
        }

        //Check if the password is secure
        let cleanedPassword = PasswordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)

        if Utilities.isPasswordValid(cleanedPassword) == false {

            //password isn't secure enough
            return "Please make sure your password is at least 8 characters, contains a special character and a number."

        }

        return nil
    }

    @IBAction func SignUpTapped(_ sender: Any) {
        //Validate Fields
        let error = Validatefields()

        if error != nil {
            //something wrong with fields
           showError(error!)

        }

        else {

            //Create User
            Auth.auth().createUser(withEmail: email, password: password) { (result, err) in
                //Check for errors
                if err != nil {

                    //there was an error
                    self.showError("Error Creating User")

                }
                else {
                    // Create cleaned (No white spaces) version of data
                    let Firstname = FirstNameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
                    let LastName = LastNameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
                    let email2 = EmailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
                    let password2 = PasswordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)

                    //User was successfully created
                    let db = Firestore.firestore()

                    db.collection("users").addDocument(data: ["Firstname":firstName,"LastName":lastName, "uid": result!.user.uid ])  {(error) in

                        if error != nil {
                            //Show error message
                            self.showError("User FirstName and Lastname couldn't be saved, You should still be able to log in.")

                        }

                    }
                    //Transition to home screen
                    func Transitiontohome () {

                let homeViewController = storyboard?.instantiateViewController(identifier:Constants.Storyboard.homeViewController) as?
                    HomeViewController

                        view.window?.rootViewController = homeViewController
                        view.window?.makeKeyAndVisible()
                    }

            }

        }

    }

    }
    func showError (_ message:String) {
    ErrorLabel.text = message
    ErrorLabel.alpha = 1
}
}

Body:
You have to replace email with self.EmailTextField.text and password with self.PasswordTextField.text, so updated code

Auth.auth().createUser(withEmail: self.EmailTextField.text, password: self.PasswordTextField.text) { (result, err) in


问:
How to read a file, line by line, also the content in every line is separated with a blank space and write it in a new file
For example, i read a file with:

```<code>Cat Dog Monkey 1234
A,A #$%&  No
</code>```

And i need save every word in another (yes another) file like:

```<code>word 1: cat
word 2: Dog
word 3: Money
word 4: 1234

word 1: A,A
word 2: #$%&
word 3:
word 4: No
</code>```

I just have the basic code of ofstream from examples so if anyone can help me with that, would be great. Also there is a way to save these words and compare if start with A number, letter, symbol or have comas? (,).
I know is a long request so every piece of info will be appreciated (>n<)

答:
The solution is rather straigthtforward.

First, we open the files and check, if that worked. The we read the source file line by line in a for-loop and use std::getline to extract a complete line.

For easier processing and usage of the std::istream_iterator, we then put the line into a std::istringstream.

For transforming the data from the source format to the destination format, we will use the (for this purpose dedicated function std::transform.

That's basically it,

Please see the below simple and short example:

```<code>#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <sstream>
#include <algorithm>

const std::string sourceFileName{ "source.txt" };
const std::string resultFileName{ "result.txt" };

int main() {

    // Open source file and check, if it could be opened
    if (std::ifstream sourceStream(sourceFileName); sourceStream) {

        // open destination file and check, if it could be opened
        if (std::ofstream resultStream(resultFileName); resultStream) {

            // Read the source file line by line
            for (std::string line{}; std::getline(sourceStream, line); ) {

                // Put the just read file into a istringstream for easier processing
                std::istringstream iss(line);

                // Read every sub-string in the istringstream and convert it to the expected result, using a stateful Lambda
                std::transform(std::istream_iterator<std::string>(iss), {}, std::ostream_iterator<std::string>(resultStream, "\n"),
                    [i = 1U](const std::string& s) mutable { return "word " + std::to_string(i) + " " + s; });
                resultStream << std::endl;
            }
        }
        else std::cerr << "\n*** Error: Could not open source file '" << sourceFileName << "'\n\n";
    }
    else std::cerr << "\n*** Error: Could not open result file '" << resultFileName << "'\n\n";

    return 0;
}
</code>```

Edit

I just noted that you want to split 2 consecutive spaces as well. For that I created a split function. The function will then look like this

```<code>#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <sstream>
#include <algorithm>
#include <vector>

const std::string sourceFileName{ "r:\\source.txt" };
const std::string resultFileName{ "r:\\result.txt" };

std::vector<std::string> split(std::string& s) {

    // Result as vector of string
    std::vector<std::string> splitted;

    // Start searching at the beginning
    size_t startPos{ 0U };

    // Search all spaces
    for  (size_t foundPos{ 0U }; (foundPos = s.find(' ', startPos)) != std::string::npos; ) {

        // And store the sub string before the found space
        splitted.push_back(s.substr(startPos, foundPos - startPos));
        startPos = foundPos+1;
    }
    // At the end of the string there is no space. So add last sub-string
    splitted.push_back(s.substr(startPos));
    return splitted;
}

int main() {

    // Open source file and check, if it could be opened
    if (std::ifstream sourceStream(sourceFileName); sourceStream) {

        // open destination file and check, if it could be opened
        if (std::ofstream resultStream(resultFileName); resultStream) {

            // Read the source file line by line
            for (std::string line{}; std::getline(sourceStream, line); ) {

                std::vector vs = split(line);

                // Read every sub-string  and convert it to the expected result, using a stateful Lambda
                std::transform(vs.begin(), vs.end(), std::ostream_iterator<std::string>(resultStream, "\n"),
                    [i = 1U](const std::string& s) mutable { return "word " + std::to_string(i) + " " + s; });
                resultStream << std::endl;
            }
        }
        else std::cerr << "\n*** Error: Could not open source file '" << sourceFileName << "'\n\n";
    }
    else std::cerr << "\n*** Error: Could not open result file '" << resultFileName << "'\n\n";

    return 0;
}
</code>```

And if you want to go in the direction of hardcore C++, you may use a regex and the std::sregex_token_iterator. This thing has been made for splitting strings and could be used as well.

This leads to an elegant C++ solution:

```<code>#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <sstream>
#include <algorithm>
#include <vector>
#include <regex>

const std::string sourceFileName{ "r:\\source.txt" };
const std::string resultFileName{ "r:\\result.txt" };

const std::regex re{R"([ ]{1})"};

int main() {

    // Open source file and check, if it could be opened
    if (std::ifstream sourceStream(sourceFileName); sourceStream) {

        // open destination file and check, if it could be opened
        if (std::ofstream resultStream(resultFileName); resultStream) {

            // Read the source file line by line
            for (std::string line{}; std::getline(sourceStream, line); ) {

                // Read every sub-string  and convert it to the expected result, using a stateful Lambda
                std::transform(std::sregex_token_iterator(line.begin(), line.end(), re, -1), {}, std::ostream_iterator<std::string>(resultStream, "\n"),
                    [i = 1U](const std::string& s) mutable { return "word " + std::to_string(i) + " " + s; });

                resultStream << std::endl;
            }
        }
        else std::cerr << "\n*** Error: Could not open source file '" << sourceFileName << "'\n\n";
    }
    else std::cerr << "\n*** Error: Could not open result file '" << resultFileName << "'\n\n";

    return 0;
}
</code>```

Body:
For example, i read a file with:

Cat Dog Monkey 1234
A,A #$%&  No

And i need save every word in another (yes another) file like:

word 1: cat
word 2: Dog
word 3: Money
word 4: 1234

word 1: A,A
word 2: #$%&
word 3:
word 4: No

I just have the basic code of ofstream from examples so if anyone can help me with that, would be great. Also there is a way to save these words and compare if start with A number, letter, symbol or have comas? (,).
I know is a long request so every piece of info will be appreciated (>n<)

Body:
The solution is rather straigthtforward.

First, we open the files and check, if that worked. The we read the source file line by line in a for-loop and use std::getline to extract a complete line.

For easier processing and usage of the std::istream_iterator, we then put the line into a std::istringstream.

For transforming the data from the source format to the destination format, we will use the (for this purpose dedicated function std::transform.

That's basically it,

Please see the below simple and short example:

#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <sstream>
#include <algorithm>

const std::string sourceFileName{ "source.txt" };
const std::string resultFileName{ "result.txt" };

int main() {

    // Open source file and check, if it could be opened
    if (std::ifstream sourceStream(sourceFileName); sourceStream) {

        // open destination file and check, if it could be opened
        if (std::ofstream resultStream(resultFileName); resultStream) {

            // Read the source file line by line
            for (std::string line{}; std::getline(sourceStream, line); ) {

                // Put the just read file into a istringstream for easier processing
                std::istringstream iss(line);

                // Read every sub-string in the istringstream and convert it to the expected result, using a stateful Lambda
                std::transform(std::istream_iterator<std::string>(iss), {}, std::ostream_iterator<std::string>(resultStream, "\n"),
                    [i = 1U](const std::string& s) mutable { return "word " + std::to_string(i) + " " + s; });
                resultStream << std::endl;
            }
        }
        else std::cerr << "\n*** Error: Could not open source file '" << sourceFileName << "'\n\n";
    }
    else std::cerr << "\n*** Error: Could not open result file '" << resultFileName << "'\n\n";

    return 0;
}

Edit

I just noted that you want to split 2 consecutive spaces as well. For that I created a split function. The function will then look like this

#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <sstream>
#include <algorithm>
#include <vector>

const std::string sourceFileName{ "r:\\source.txt" };
const std::string resultFileName{ "r:\\result.txt" };

std::vector<std::string> split(std::string& s) {

    // Result as vector of string
    std::vector<std::string> splitted;

    // Start searching at the beginning
    size_t startPos{ 0U };

    // Search all spaces
    for  (size_t foundPos{ 0U }; (foundPos = s.find(' ', startPos)) != std::string::npos; ) {

        // And store the sub string before the found space
        splitted.push_back(s.substr(startPos, foundPos - startPos));
        startPos = foundPos+1;
    }
    // At the end of the string there is no space. So add last sub-string
    splitted.push_back(s.substr(startPos));
    return splitted;
}

int main() {

    // Open source file and check, if it could be opened
    if (std::ifstream sourceStream(sourceFileName); sourceStream) {

        // open destination file and check, if it could be opened
        if (std::ofstream resultStream(resultFileName); resultStream) {

            // Read the source file line by line
            for (std::string line{}; std::getline(sourceStream, line); ) {

                std::vector vs = split(line);

                // Read every sub-string  and convert it to the expected result, using a stateful Lambda
                std::transform(vs.begin(), vs.end(), std::ostream_iterator<std::string>(resultStream, "\n"),
                    [i = 1U](const std::string& s) mutable { return "word " + std::to_string(i) + " " + s; });
                resultStream << std::endl;
            }
        }
        else std::cerr << "\n*** Error: Could not open source file '" << sourceFileName << "'\n\n";
    }
    else std::cerr << "\n*** Error: Could not open result file '" << resultFileName << "'\n\n";

    return 0;
}

And if you want to go in the direction of hardcore C++, you may use a regex and the std::sregex_token_iterator. This thing has been made for splitting strings and could be used as well.

This leads to an elegant C++ solution:

#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <sstream>
#include <algorithm>
#include <vector>
#include <regex>

const std::string sourceFileName{ "r:\\source.txt" };
const std::string resultFileName{ "r:\\result.txt" };

const std::regex re{R"([ ]{1})"};

int main() {

    // Open source file and check, if it could be opened
    if (std::ifstream sourceStream(sourceFileName); sourceStream) {

        // open destination file and check, if it could be opened
        if (std::ofstream resultStream(resultFileName); resultStream) {

            // Read the source file line by line
            for (std::string line{}; std::getline(sourceStream, line); ) {

                // Read every sub-string  and convert it to the expected result, using a stateful Lambda
                std::transform(std::sregex_token_iterator(line.begin(), line.end(), re, -1), {}, std::ostream_iterator<std::string>(resultStream, "\n"),
                    [i = 1U](const std::string& s) mutable { return "word " + std::to_string(i) + " " + s; });

                resultStream << std::endl;
            }
        }
        else std::cerr << "\n*** Error: Could not open source file '" << sourceFileName << "'\n\n";
    }
    else std::cerr << "\n*** Error: Could not open result file '" << resultFileName << "'\n\n";

    return 0;
}


问:
How do I package and run a simple command-line application with dependencies using maven?
I am brand new to both java and to maven, so this is likely very simple.

If I follow the maven2 hello world instructions here:

http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html

everything works OK.  If I then alter pom.xml to bring in a dependency from a remote repository, the files for this dependency get stored in ~/.m2/repository/new-dependency/.

Using the syntax in the hello world instructions to run the application requires that I add the absolute path to the dependency to my classpath (either by setting the environment variable or via the command line switch):

```<code>java -cp target/my-app-1.0-SNAPSHOT.jar:/.../.m2/.../new-dependency.jar com.mycompany.app.App
</code>```

This will obviously get unwieldy quickly :)

I suspect that this is not the usual way of running a java program and that I just need to read more about .jar files, but while I am doing so I would appreciate any tips on how to do this properly.

I am not using an IDE, btw.  vim from the command line.

Thanks!

Mike.

答: If you want it simple for you and others, then you can generate a jar with all dependencies in it, using the maven-assembly-plugin. Example is here: http://maven.apache.org/plugins/maven-assembly-plugin/usage.html, section Execution: Building an Assembly</p>

Body:
I am brand new to both java and to maven, so this is likely very simple.

If I follow the maven2 hello world instructions here:

http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html

everything works OK.  If I then alter pom.xml to bring in a dependency from a remote repository, the files for this dependency get stored in ~/.m2/repository/new-dependency/.

Using the syntax in the hello world instructions to run the application requires that I add the absolute path to the dependency to my classpath (either by setting the environment variable or via the command line switch):

java -cp target/my-app-1.0-SNAPSHOT.jar:/.../.m2/.../new-dependency.jar com.mycompany.app.App

This will obviously get unwieldy quickly :)

I suspect that this is not the usual way of running a java program and that I just need to read more about .jar files, but while I am doing so I would appreciate any tips on how to do this properly.

I am not using an IDE, btw.  vim from the command line.

Thanks!

Mike.


问:
How to echo an array into columns in php
Ok so I have an array full of values and I want to echo them in a specific way.

This is my code so far:

```<code><?php foreach( $names as $i ) {
  echo $i."<br>";
}?>
</code>```

So at the moment I am stacking each value under one another. But I want to change it into columns.

I want it to display like this:

Name 1            Name 2

Name 3 Name 4

And so on...
How can I achieve this?

答:
Iterate through your array and build a HTML form from it. Since you'd like 2 rows, here is an example:

```<code><?php if($names) :
    echo '<table>';
    $counter = 1;
    foreach($names as $i) :
        if($counter%2 !== 0) {
            // Start new row
            echo '<tr>';
        }
        echo '<td>' . $i . '</td>';
        if($counter%2 == 0) {
            // End row
            echo '</tr>';
        }
        $counter++;
    endforeach;
    if($counter%2 == 0) {
        // Last empty cell
        echo '<td></td></tr>';
    }
    echo '</table>';
endif;
?>
</code>```

Demo:
https://3v4l.org/knGae

Body:
Ok so I have an array full of values and I want to echo them in a specific way.

This is my code so far:

<?php foreach( $names as $i ) {
  echo $i."
";
}?>

So at the moment I am stacking each value under one another. But I want to change it into columns.

I want it to display like this:

Name 1            Name 2

Name 3 Name 4

And so on...
How can I achieve this?

Body:
Iterate through your array and build a HTML form from it. Since you'd like 2 rows, here is an example:

<?php if($names) :
    echo '<table>';
    $counter = 1;
    foreach($names as $i) :
        if($counter%2 !== 0) {
            // Start new row
            echo '<tr>';
        }
        echo '<td>' . $i . '</td>';
        if($counter%2 == 0) {
            // End row
            echo '</tr>';
        }
        $counter++;
    endforeach;
    if($counter%2 == 0) {
        // Last empty cell
        echo '<td></td></tr>';
    }
    echo '</table>';
endif;
?>

Demo:
https://3v4l.org/knGae


问:
Merge two c# object(json) lists as parent child
I have a json string which looks as below:

```<code>[
  {
     "id": 1,
    "title": "Hello"
  },
  {
    "id": 2,
    "title": "test"
  }
]

[
  {
     "id": 1,
    "parentId": 1,
    "prop1": "sdsdsdt",
    "prop1l": "3dsdsd",
    "v": "fsssd sd"
  },
   {
     "id": 2,
    "parentId": 1,
    "prop1": "sdsdsdt",
    "prop1l": "3dsdsd",
    "v": "fsssd sd"
  },
    {
     "id": 3,
    "parentId": 2,
    "prop1": "sdsdsdt",
    "prop2": "3dsdsd",
    "prop3": "fsssd sd"
  }
]
</code>```

I can serialize it into two classes (list) as below:

```<code>public class Parent
{
    public int id { get; set; }
    public string title { get; set; }
}

public class Child
{
    public int id { get; set; }
    public int parentId { get; set; }
    public string prop1 { get; set; }
    public string prop2 { get; set; }
    public string prop3 { get; set; }
}
</code>```

Now I want to create third collection where I can merge children under parent object. I know I can do with for loop in parent and look for children for parentId in Child. I wonder if there is a better way? So I can get these as below list:

```<code>public class Merged
{
    public int id { get; set; }
    public string title { get; set; }
    public list<Child> children{get;set;}
}
</code>```

答:
You can do it with LINQ just with Select method:

```<code>var mergedList = parentList
.Select(p=> new Merged
{
  id = p.Id,
  title = p.title,
  children = childList.Where(c=>c.parentId == p.id).ToList()
});

</code>```

Body:
I have a json string which looks as below:

[
  {
     "id": 1,
    "title": "Hello"
  },
  {
    "id": 2,
    "title": "test"
  }
]

[
  {
     "id": 1,
    "parentId": 1,
    "prop1": "sdsdsdt",
    "prop1l": "3dsdsd",
    "v": "fsssd sd"
  },
   {
     "id": 2,
    "parentId": 1,
    "prop1": "sdsdsdt",
    "prop1l": "3dsdsd",
    "v": "fsssd sd"
  },
    {
     "id": 3,
    "parentId": 2,
    "prop1": "sdsdsdt",
    "prop2": "3dsdsd",
    "prop3": "fsssd sd"
  }
]

I can serialize it into two classes (list) as below:

public class Parent
{
    public int id { get; set; }
    public string title { get; set; }
}

public class Child
{
    public int id { get; set; }
    public int parentId { get; set; }
    public string prop1 { get; set; }
    public string prop2 { get; set; }
    public string prop3 { get; set; }
}

Now I want to create third collection where I can merge children under parent object. I know I can do with for loop in parent and look for children for parentId in Child. I wonder if there is a better way? So I can get these as below list:

public class Merged
{
    public int id { get; set; }
    public string title { get; set; }
    public list<Child> children{get;set;}
}

Body:
You can do it with LINQ just with Select method:

var mergedList = parentList
.Select(p=> new Merged
{
  id = p.Id,
  title = p.title,
  children = childList.Where(c=>c.parentId == p.id).ToList()
});