问:
Swift Switch case on enum with Classes
This is the first time I use this kind of enums, enum with associated value type, I need to make a switch statement depending on the object's type, I cannot managed to do it, this is the enum:

```<code>enum TypeEnum {
    case foo(FooClass)
    case doo(DooClass)
    case roo(RooClass)
}
</code>```

My object has a variable of type TypeEnum, now I need to check which kind of object is in the enum:

```<code>if let anObject = object as? TypeEnum {

  switch anObject {
  case .foo(???):
     return true
    ...
    default:
      return false
    }

 }
</code>```

I have no idea what to put instead of ???. Xcode tells me to put something, but I just want to switch on .foo.

Any ideas?

答:
You can use let to capture the associated values for that:

```<code>switch anObject {
case .foo(let fooObj):
    ...
}
</code>```

or nothing at all if you just don't care about them:

```<code>switch anObject {
case .foo:
    ...
}
</code>```

Please be sure to check the Swift Programming Language book for further details.

Title: Swift Switch case on enum with Classes

Body:
This is the first time I use this kind of enums, enum with associated value type, I need to make a switch statement depending on the object's type, I cannot managed to do it, this is the enum:

enum TypeEnum {
    case foo(FooClass)
    case doo(DooClass)
    case roo(RooClass)
}

My object has a variable of type TypeEnum, now I need to check which kind of object is in the enum:

if let anObject = object as? TypeEnum {

  switch anObject {
  case .foo(???):
     return true
    ...
    default:
      return false
    }

 }

I have no idea what to put instead of ???. Xcode tells me to put something, but I just want to switch on .foo.

Any ideas?

Body:
You can use let to capture the associated values for that:

switch anObject {
case .foo(let fooObj):
    ...
}

or nothing at all if you just don't care about them:

switch anObject {
case .foo:
    ...
}

Please be sure to check the Swift Programming Language book for further details.


来源: stackexchange

问:
Dependency Mismatch: Solution won't use anything newer than 4.0.0.0
When I try to run the solution, I'll get an error: Could not load file or assembly 'System.Net.Http, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

System.Net.Http version 4.0.0 is always in use. I have tried to update, downgrade and god knows what for hours now. Nothing I've tried works.

This is my project.json:

```<code>{
  "dependencies": {
    "Microsoft.AspNetCore.Mvc": "1.0.1",
    "Microsoft.AspNetCore.Routing": "1.0.1",
    "Microsoft.AspNetCore.Server.Kestrel": "1.1.2",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.1.2",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.1.2",
    "Microsoft.Extensions.Configuration.Json": "1.1.2",
    "Microsoft.Extensions.Configuration.UserSecrets": "1.1.2",
    "Microsoft.Extensions.Logging": "1.1.2",
    "Microsoft.Extensions.Logging.Console": "1.1.2",
    "Microsoft.Extensions.Logging.Debug": "1.1.2",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.1.2",
    "Microsoft.ServiceFabric": "5.6.220",
    "Microsoft.ServiceFabric.AspNetCore.WebListener": "2.6.220",
    "Microsoft.ServiceFabric.Data": "2.6.220",
    "Microsoft.ServiceFabric.Services": "2.6.220",
    "Microsoft.AspNetCore.Mvc.Formatters.Xml": "1.0.1",
    "Microsoft.AspNetCore.Authentication.Cookies": "1.1.1",
    "microsoft.aspnetcore.authentication.jwtbearer": "1.1.1",
    "System.Net.Http": "4.3.2"
  },

  "tools": {
  },

  "frameworks": {
    "net461": {}

  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "**/*.cshtml",
      "appsettings.json",
      "web.config"
    ]
  },

  "scripts": {
  }
}
</code>```

In there I have written "System.Net.Http": "4.3.2", but as you can see in this image, the reference version is 4.0.0:

What am I doing wrong and how can I fix it? I'm getting a bit confused. I declare 4.3.2, the reference is 4.0.0 and the error says 4.1.1? I have searched everywhere for version 4.1.1, but didn't find anything.

Edit:
I'm using VS 2015 on a windows 7 machine.

I have also tried to redirect to the correct assembly version in the config json file with no success.

答:
For whatever reason VS 2015 would fallback to v4.0.0 of System.Net.Http if multiple package versions were used. What you could do is:

Upgrade your .NET Core projects to v1.1 and use VS 2017.

Remove Microsoft.AspNetCore.Authentication.JwtBearer which has a dependency on System.Net.Http v4.0.0.

If Microsoft.AspNetCore.Authentication.JwtBearer is needed in your project, then #1 might be the only option.

ContentLicense: CC BY-SA 3.0

Body:
When I try to run the solution, I'll get an error: Could not load file or assembly 'System.Net.Http, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

System.Net.Http version 4.0.0 is always in use. I have tried to update, downgrade and god knows what for hours now. Nothing I've tried works.

This is my project.json:

{
  "dependencies": {
    "Microsoft.AspNetCore.Mvc": "1.0.1",
    "Microsoft.AspNetCore.Routing": "1.0.1",
    "Microsoft.AspNetCore.Server.Kestrel": "1.1.2",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.1.2",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.1.2",
    "Microsoft.Extensions.Configuration.Json": "1.1.2",
    "Microsoft.Extensions.Configuration.UserSecrets": "1.1.2",
    "Microsoft.Extensions.Logging": "1.1.2",
    "Microsoft.Extensions.Logging.Console": "1.1.2",
    "Microsoft.Extensions.Logging.Debug": "1.1.2",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.1.2",
    "Microsoft.ServiceFabric": "5.6.220",
    "Microsoft.ServiceFabric.AspNetCore.WebListener": "2.6.220",
    "Microsoft.ServiceFabric.Data": "2.6.220",
    "Microsoft.ServiceFabric.Services": "2.6.220",
    "Microsoft.AspNetCore.Mvc.Formatters.Xml": "1.0.1",
    "Microsoft.AspNetCore.Authentication.Cookies": "1.1.1",
    "microsoft.aspnetcore.authentication.jwtbearer": "1.1.1",
    "System.Net.Http": "4.3.2"
  },

  "tools": {
  },

  "frameworks": {
    "net461": {}

  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "**/*.cshtml",
      "appsettings.json",
      "web.config"
    ]
  },

  "scripts": {
  }
}

In there I have written "System.Net.Http": "4.3.2", but as you can see in this image, the reference version is 4.0.0:

What am I doing wrong and how can I fix it? I'm getting a bit confused. I declare 4.3.2, the reference is 4.0.0 and the error says 4.1.1? I have searched everywhere for version 4.1.1, but didn't find anything.

Edit:
I'm using VS 2015 on a windows 7 machine.

I have also tried to redirect to the correct assembly version in the config json file with no success.


问:
invalid conversion from 'DWORD (*)(void*)' to 'DWORD (*)(void*)'
invalid conversion from 'DWORD (*)(void*)' to 'DWORD (*)(void*)' .
cake==lie
1==0

I have no idea what this means ... I get it in this code

```<code>HANDLE CPlugin::CreateWinampThread()    ||
{                                  __VVVVVVVV__
    hWinampThreadHandle = (HANDLE)CreateThread(NULL, 0, StartWinampThread, (void*)this, 0, &dwWinampThreadID);
    if (!hWinampThreadHandle)
        return 0;

     CloseHandle(hWinampThreadHandle);
     return hWinampThreadHandle;
}

.

DWORD  WINAPI CPlugin::StartWinampThread(void* lpParam)[...]
</code>```

答:
See here: in-c-is-it-safe-portable-to-use-static-member-function-pointer-for-c-api-callb for why you need to use a extern "C"

The correct way would be somthing like this:

```<code>HANDLE CPlugin::CreateWinampThread()    ||
{                                  __VVVVVVVV__
    hWinampThreadHandle = (HANDLE)CreateThread(NULL, 0, ::StartWinampThread, (void*)this, 0, &dwWinampThreadID);
    if (!hWinampThreadHandle)
        return 0;

     CloseHandle(hWinampThreadHandle);
     return hWinampThreadHandle;
}

.

// A callback function for C code must have C linkage.
// That is not possable for C++ static member functions.
extern "C" DWORD  WINAPI StartWinampThread(void* lpParam)
{
    // You can always call your static member function here.
    CPlugin::StartWinampThread(lpParam)
}
</code>```

Body:
invalid conversion from 'DWORD (*)(void*)' to 'DWORD (*)(void*)' .
cake==lie
1==0

I have no idea what this means ... I get it in this code

HANDLE CPlugin::CreateWinampThread()    ||
{                                  __VVVVVVVV__
    hWinampThreadHandle = (HANDLE)CreateThread(NULL, 0, StartWinampThread, (void*)this, 0, &dwWinampThreadID);
    if (!hWinampThreadHandle)
        return 0;

     CloseHandle(hWinampThreadHandle);
     return hWinampThreadHandle;
}

.

DWORD  WINAPI CPlugin::StartWinampThread(void* lpParam)[...]

Body:
See here: in-c-is-it-safe-portable-to-use-static-member-function-pointer-for-c-api-callb for why you need to use a extern "C"

The correct way would be somthing like this:

HANDLE CPlugin::CreateWinampThread()    ||
{                                  __VVVVVVVV__
    hWinampThreadHandle = (HANDLE)CreateThread(NULL, 0, ::StartWinampThread, (void*)this, 0, &dwWinampThreadID);
    if (!hWinampThreadHandle)
        return 0;

     CloseHandle(hWinampThreadHandle);
     return hWinampThreadHandle;
}

.

// A callback function for C code must have C linkage.
// That is not possable for C++ static member functions.
extern "C" DWORD  WINAPI StartWinampThread(void* lpParam)
{
    // You can always call your static member function here.
    CPlugin::StartWinampThread(lpParam)
}

ContentLicense: CC BY-SA 2.5


问:
Case wise delete of values inside cor() in R
Consider the following survey data:

```<code>data <- replicate(10 ,sample(c(1,2,3,4), 1000, replace = TRUE)) %>%
  as.data.frame()
</code>```

V1:V9 are variables where 1 = "Good", 2 = "Okey" and 3 = "Not Good" and 4 = "Don't know" while V10 is an ordinal variable where 1 = "Good", 2 = "Not good", 3 = "Don't know" and 4 = "Don't want to answer".

I am interested in calculating a simple correlation matrix using cor() on these variables. However, I only want to calculate it between the values that actually mean something. That is, 1,2,3 for V1:V9 and 1,2 for V10.

In other words, I want a case wise delete of any value > 3 for V1:V9 and the same for any values > 2 for V10 within the cor() function.

This would be similar to the use argument?

The only way I have managed to solve this is by mutating these values as NA.

```<code>library("dplyr")
data_test <- data_test %>%
      mutate_each(funs(ifelse(. > 3, NA, .)), -V10) %>%
      mutate(ifelse(V10 > 2, NA, V10))

cor(data_test, use = "complete.obs")
</code>```

But is there a better way that does not necessarily rely on modifying the data.

PS. There are, of course, more adequate ways of calculating correlation between ordinal variables.

答:
The answer to this question was more simple than I thought.

As @zx8754 points out you should be careful when choosing correlation method for categorical variables.

Anyways, you just change use = "pairwise.complete.obs" in cor()

However, you still need to mutate 4 to NA.

Body:
Consider the following survey data:

data <- replicate(10 ,sample(c(1,2,3,4), 1000, replace = TRUE)) %>%
  as.data.frame()

V1:V9 are variables where 1 = "Good", 2 = "Okey" and 3 = "Not Good" and 4 = "Don't know" while V10 is an ordinal variable where 1 = "Good", 2 = "Not good", 3 = "Don't know" and 4 = "Don't want to answer".

I am interested in calculating a simple correlation matrix using cor() on these variables. However, I only want to calculate it between the values that actually mean something. That is, 1,2,3 for V1:V9 and 1,2 for V10.

In other words, I want a case wise delete of any value > 3 for V1:V9 and the same for any values > 2 for V10 within the cor() function.

This would be similar to the use argument?

The only way I have managed to solve this is by mutating these values as NA.

library("dplyr")
data_test <- data_test %>%
      mutate_each(funs(ifelse(. > 3, NA, .)), -V10) %>%
      mutate(ifelse(V10 > 2, NA, V10))

cor(data_test, use = "complete.obs")

But is there a better way that does not necessarily rely on modifying the data.

PS. There are, of course, more adequate ways of calculating correlation between ordinal variables.


问:
Using absolute path in Angular 2 + Electron
I started messing around with Angular 2 and Electron, and used this starter package. Everything seems to be going well, I'm even able to use the node fs package to read from a directory.

The problem I'm having is that I can't seem to be able to use an absolute path for the readdirSync() method. It only takes a relative path.

I did find this in the docs for fs that you can use the URL package to show an absolute path for readdirSync(), like so:

```<code>const fs = require('fs');
const { URL } = require('url');

// file:///C:/tmp/hello => C:\tmp\hello
fs.readFileSync(new URL('file:///C:/tmp/hello'));
</code>```

That looks great, but in my Angular 2/TypeScript/Electron world that doesn't seem to work. Mine looks like this:

```<code>import { Injectable } from "@angular/core";
import {readdirSync} from "fs";
import { URL } from "url";

@Injectable()
export class LinkDocRetrieverService {
    getFiles():Array<String> {

        // read through all the directories to get all the files and folder names

        let u = new URL("file:///C:/SAFE/MISC");
        let x = readdirSync(u);
        console.log("files retrieved="+ x.length);

        let files: Array<string> = [];
        x.forEach(f => {
            files.push(f);
        });
        return files;
    }
}
</code>```

Both intellisense and runtime both tell me that

[ts] Argument of type 'URL' is not assignable to parameter of type
  'string | Buffer'.   Type 'URL' is not assignable to type 'Buffer'.
      Property 'write' is missing in type 'URL'.

I would have expected the syntax to be the same, but no luck.

I have read a lot of posts stating that they can't run the fs package in Angular 2 + Typescript, but it works well for me, as long as I use a relative path. I just need help getting the absolute path to work. Thanks in advance.

答:
Documentation states that URL support was introduced in v7.6.0 and is experimental. Electron uses v7.4.0, thus you can not use URL with fs yet.

```<code>fs.readFileSync('C:/tmp/hello')
</code>```

Should work just fine.

Body:
I started messing around with Angular 2 and Electron, and used this starter package. Everything seems to be going well, I'm even able to use the node fs package to read from a directory.

The problem I'm having is that I can't seem to be able to use an absolute path for the readdirSync() method. It only takes a relative path.

I did find this in the docs for fs that you can use the URL package to show an absolute path for readdirSync(), like so:

const fs = require('fs');
const { URL } = require('url');

// file:///C:/tmp/hello => C:\tmp\hello
fs.readFileSync(new URL('file:///C:/tmp/hello'));

That looks great, but in my Angular 2/TypeScript/Electron world that doesn't seem to work. Mine looks like this:

import { Injectable } from "@angular/core";
import {readdirSync} from "fs";
import { URL } from "url";

@Injectable()
export class LinkDocRetrieverService {
    getFiles():Array<String> {

        // read through all the directories to get all the files and folder names

        let u = new URL("file:///C:/SAFE/MISC");
        let x = readdirSync(u);
        console.log("files retrieved="+ x.length);

        let files: Array<string> = [];
        x.forEach(f => {
            files.push(f);
        });
        return files;
    }
}

Both intellisense and runtime both tell me that

[ts] Argument of type 'URL' is not assignable to parameter of type
  'string | Buffer'.   Type 'URL' is not assignable to type 'Buffer'.
      Property 'write' is missing in type 'URL'.

I would have expected the syntax to be the same, but no luck.

I have read a lot of posts stating that they can't run the fs package in Angular 2 + Typescript, but it works well for me, as long as I use a relative path. I just need help getting the absolute path to work. Thanks in advance.

Body:
Documentation states that URL support was introduced in v7.6.0 and is experimental. Electron uses v7.4.0, thus you can not use URL with fs yet.

fs.readFileSync('C:/tmp/hello')

Should work just fine.


问:
PowerMockito Mocked final class gson.fromJson() Returns null
I have this code in main class  -

```<code>try {
    extraPlayer = gson.fromJson(jsonResponse, ExtraPlayer.class);// this returns null
} catch (Exception e) {
    e.printStacktrace();
}
</code>```

Here extraPlayer is coming as null
I have mocked @Mock Gson gsonMock;

Here ExtraPlayer is a static class.

I have written this test code  -

```<code>@Test
public void test() {
    String jsonResponse = "{\"status\":\"waiting\",\"no\":\"12\"}";
    when(playerHandlerMock.resetPlayer("someString", "someString", "1",true
         )).thenReturn(jsonResponse);
    Gson gsonMock = PowerMockito.mock(Gson.class);
    ExtraPlayer extraPlayer = new ExtraPlayer();
    extraPlayer.setNo("12");
    extraPlayer.setStatus("Waiting");

    PowerMockito.mockStatic(ResetModemResponse.class); // using this for static class but didn't work.

    PowerMockito.when(gsonMock.fromJson(jsonResponse, ExtraPlayer.class)).thenReturn(extraPlayer);

    playerMock.performWaiting();
}
</code>```

ExtraPlayer.java

```<code>public static class ExtraPlayer{

    String no;
    String status;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getNo() {
        return code;
    }

    public void setNo(String no) {
        this.no = no;
    }

}
</code>```

I have added these annotations to the test class -

```<code>@RunWith(PowerMockRunner.class)
@PrepareForTest(Gson.class)
</code>```

why extraPlayer is null ? please help/Suggest.

答:
If you were to use the standard @Mock and @InjectMocks annotation with mockito, then yes, the framework would take care of the injection of the mock into the class under test (regardless of the existence of the setters etc.).

Another thing is the playerMock, which i assume is the class under test.

Do not mock the class under test, create a normal instance and then inject the dependencies... the performWaiting method does not seem to accept the response String, so you would have to inject that also somehow (unless you left some parts out):

```<code>@Test
public void test() {
    // Arrange
    String jsonResponse = "{\"status\":\"waiting\",\"no\":\"12\"}";
    Gson gsonMock = PowerMockito.mock(Gson.class);
    ExtraPlayer extraPlayer = new ExtraPlayer();
    extraPlayer.setNo("12");
    extraPlayer.setStatus("Waiting");

    PowerMockito.when(gsonMock.fromJson(jsonResponse, ExtraPlayer.class)).thenReturn(extraPlayer);

    Player player = new Player();
    player.setGson(gsonMock);
    player.setResponse(jsonResponse);

    // Act
    player.performWaiting();

    // Assert ...
}
</code>```

Body:
I have this code in main class  -

try {
    extraPlayer = gson.fromJson(jsonResponse, ExtraPlayer.class);// this returns null
} catch (Exception e) {
    e.printStacktrace();
}

Here extraPlayer is coming as null
I have mocked @Mock Gson gsonMock;

Here ExtraPlayer is a static class.

I have written this test code  -

@Test
public void test() {
    String jsonResponse = "{\"status\":\"waiting\",\"no\":\"12\"}";
    when(playerHandlerMock.resetPlayer("someString", "someString", "1",true
         )).thenReturn(jsonResponse);
    Gson gsonMock = PowerMockito.mock(Gson.class);
    ExtraPlayer extraPlayer = new ExtraPlayer();
    extraPlayer.setNo("12");
    extraPlayer.setStatus("Waiting");

    PowerMockito.mockStatic(ResetModemResponse.class); // using this for static class but didn't work.

    PowerMockito.when(gsonMock.fromJson(jsonResponse, ExtraPlayer.class)).thenReturn(extraPlayer);

    playerMock.performWaiting();
}

ExtraPlayer.java

public static class ExtraPlayer{

    String no;
    String status;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getNo() {
        return code;
    }

    public void setNo(String no) {
        this.no = no;
    }

}

I have added these annotations to the test class -

@RunWith(PowerMockRunner.class)
@PrepareForTest(Gson.class)

why extraPlayer is null ? please help/Suggest.

Body:
If you were to use the standard @Mock and @InjectMocks annotation with mockito, then yes, the framework would take care of the injection of the mock into the class under test (regardless of the existence of the setters etc.).

Another thing is the playerMock, which i assume is the class under test.

Do not mock the class under test, create a normal instance and then inject the dependencies... the performWaiting method does not seem to accept the response String, so you would have to inject that also somehow (unless you left some parts out):

@Test
public void test() {
    // Arrange
    String jsonResponse = "{\"status\":\"waiting\",\"no\":\"12\"}";
    Gson gsonMock = PowerMockito.mock(Gson.class);
    ExtraPlayer extraPlayer = new ExtraPlayer();
    extraPlayer.setNo("12");
    extraPlayer.setStatus("Waiting");

    PowerMockito.when(gsonMock.fromJson(jsonResponse, ExtraPlayer.class)).thenReturn(extraPlayer);

    Player player = new Player();
    player.setGson(gsonMock);
    player.setResponse(jsonResponse);

    // Act
    player.performWaiting();

    // Assert ...
}


问:
Could you please suggest better design?
Following is the scenario.

I have something called as Domain which can have multiple States (Statekey-Statevalue pair) in it. The same StateKey can be present in multiple domains but with different StateValue.

e.g. StateKey named 'EconomicCapital' may be present in Domains like 'England', 'America' with values 'London', 'Washington' respectively.

Classes corresponding to these are in common library which can be consumed at client or service side as required.

I have a winform application in which I can select a specific domain. In any string, wherever I encounter any StateKey, I want to replace it by its StateValue for the selected domain.

I can think of following designs:

Establish composition relationship. Domain can be composed of the States. So when I want a StateValue of any StateKey, I can get the object of the required domain and can extract StateKey from the States collection composed in it.

But there can be large number of instances where StateKey would be used, I do not think this approach is quite good snce it requires finding Domain object from the collection of domains and iterating through its State collection to find particular key.

OR

Maintain a static collection which can hold all StateKeys in different domain. When I want particular StateKey I can simply lookup in this collection.

Could you please advice me which approach is more appropriate? Will there be any other approach/design?

(If the logic is implemented at service side; not just one winform application but many such applications can access it.)

答: Is this just a "thought project"/homework?  Domain > State > StateValue relationships have to do something to become a class and use design patterns. This appears to be just a set of lookup operations. You may be better of using LINQ or a database.

Title: Could you please suggest better design?


问:
Bizarre behavior of a query
I found this query from a developer:

```<code>DELETE FROM [MYDB].[dbo].[MYSIGN] where USERID in
(select USERID from [MYDB].[dbo].[MYUSER] where Surname = 'Rossi');
</code>```

This query deletes every record in table MYSIGN.

The field USERID does not exists in table MYUSER. If I run only the subquery:

```<code>select USERID from [MYDB].[dbo].[MYUSER] where Surname = 'Rossi'
</code>```

It throws the right error, because the missing column.

We corrected the query using the right column, but we didn't figure out:

Why the first query works?

Why it deletes every record?

Specs: database is on a SQL SERVER 2016 SP1, CU3.

答:
Apparently you have USERID in [MYDB].[dbo].[MYSIGN] so it's exactly how sql-server resolves unprefixed USERID in (select USERID from [MYDB].[dbo].[MYUSER] where Surname = 'Rossi') - it resolves it to [MYDB].[dbo].[MYSIGN].USERID

Use aliases and it will fail

```<code>DELETE FROM [MYDB].[dbo].[MYSIGN] where USERID in
(select t.USERID from [MYDB].[dbo].[MYUSER] t where Surname = 'Rossi');
</code>```

It's something referred as "accidental correlated sub-query" as @NenadZivkovic named it, i like the term.

Title: Bizarre behavior of a query

Body:
I found this query from a developer:

DELETE FROM [MYDB].[dbo].[MYSIGN] where USERID in
(select USERID from [MYDB].[dbo].[MYUSER] where Surname = 'Rossi');

This query deletes every record in table MYSIGN.

The field USERID does not exists in table MYUSER. If I run only the subquery:

select USERID from [MYDB].[dbo].[MYUSER] where Surname = 'Rossi'

It throws the right error, because the missing column.

We corrected the query using the right column, but we didn't figure out:

Why the first query works?

Why it deletes every record?

Specs: database is on a SQL SERVER 2016 SP1, CU3.

Body:
Apparently you have USERID in [MYDB].[dbo].[MYSIGN] so it's exactly how sql-server resolves unprefixed USERID in (select USERID from [MYDB].[dbo].[MYUSER] where Surname = 'Rossi') - it resolves it to [MYDB].[dbo].[MYSIGN].USERID

Use aliases and it will fail

DELETE FROM [MYDB].[dbo].[MYSIGN] where USERID in
(select t.USERID from [MYDB].[dbo].[MYUSER] t where Surname = 'Rossi');

It's something referred as "accidental correlated sub-query" as @NenadZivkovic named it, i like the term.


问:
JQuery: Changing the DOM on dragstart event fires dragend immediately?
i came across a bug for Chrome and Opera and i would like to know if its known and if so, is there a solution?

If i change the DOM on the dragstart event it immediately fires the dragend event?! Is this a bug or is there some reason behind it? Only happens in Chrome and Opera. Firefox works.

I appreciate every answer.

$('body').on({
      dragstart: function(e) {

        dragProfilefieldSrcElformid = $(this).attr("data-profilefieldid-formid");
        e.dataTransfer = e.originalEvent.dataTransfer;
        e.dataTransfer.effectAllowed = 'move';
        e.dataTransfer.setData('text/html', $(this).attr("data-profilefieldid"));

        // Changing the DOM, fires the dragend Event in Chrome?
        $("#plugin_loginlogout_pfcontainer_" + dragProfilefieldSrcElformid).find(".plugin_loginlogout_pf_entryfield").addClass("highlight"); // This doesn't work in Chrome and Opera, but in Firefox
      },
      dragend: function() {
        console.log("dragend");
      }
      ".plugin_loginlogout_pf");```

Edit:

Putting the DOM Change in a setTimeout Function seems to solve the problem!

答:
I found the setTimeout() workaround to be very buggy in Firefox. For example, when you immediately release the mouse button after dragging, the context within the dragstart might be no longer accesible and the script can crash. Especially when used in combination with the dragend event.

I created the following procedure which gave much more reliability to my script:

```<code>$('html').on('dragstart', '.somelement', function(e){

    // Bind 'drag' event only once (gets triggered every 350ms)
    $('html').one('drag', function(){
         // modify DOM here
    });
});

$('html').on('dragend', '.somelement', function(e){

    // Edge might fire 'dragend' before executing the 'drag' event within 'dragstart'
    $('html').unbind('drag');

});
</code>```

Body:
i came across a bug for Chrome and Opera and i would like to know if its known and if so, is there a solution?

If i change the DOM on the dragstart event it immediately fires the dragend event?! Is this a bug or is there some reason behind it? Only happens in Chrome and Opera. Firefox works.

I appreciate every answer.

$('body').on({
      dragstart: function(e) {

        dragProfilefieldSrcElformid = $(this).attr("data-profilefieldid-formid");
        e.dataTransfer = e.originalEvent.dataTransfer;
        e.dataTransfer.effectAllowed = 'move';
        e.dataTransfer.setData('text/html', $(this).attr("data-profilefieldid"));

        // Changing the DOM, fires the dragend Event in Chrome?
        $("#plugin_loginlogout_pfcontainer_" + dragProfilefieldSrcElformid).find(".plugin_loginlogout_pf_entryfield").addClass("highlight"); // This doesn't work in Chrome and Opera, but in Firefox
      },
      dragend: function() {
        console.log("dragend");
      }
      ".plugin_loginlogout_pf");

Edit:

Putting the DOM Change in a setTimeout Function seems to solve the problem!

Body:
I found the setTimeout() workaround to be very buggy in Firefox. For example, when you immediately release the mouse button after dragging, the context within the dragstart might be no longer accesible and the script can crash. Especially when used in combination with the dragend event.

I created the following procedure which gave much more reliability to my script:

$('html').on('dragstart', '.somelement', function(e){

    // Bind 'drag' event only once (gets triggered every 350ms)
    $('html').one('drag', function(){
         // modify DOM here
    });
});

$('html').on('dragend', '.somelement', function(e){

    // Edge might fire 'dragend' before executing the 'drag' event within 'dragstart'
    $('html').unbind('drag');

});


问:
Refreshing Kendo grid in Angular 2
How do you refresh an Angular 2 Kendo grid when the data has been changed?</p>

```<code>private trash() {
  this.gridView.data.splice(index, 1);
  //I wish to refresh here
}
</code>```

答:
```<code>data.splice(index, 1);
this.gridView.data = data;
</code>```

Not working with paging option

Title: Refreshing Kendo grid in Angular 2

Body:
How do you refresh an Angular 2 Kendo grid when the data has been changed?

private trash() {
  this.gridView.data.splice(index, 1);
  //I wish to refresh here
}

Body:
data.splice(index, 1);
this.gridView.data = data;

Not working with paging option


问:
firebase asking for key id when activating for iOS app

What does the key id mean? Please help me, I don't know what to enter in there.

答:
If you want Push notification using FCM- Firebase Cloud messaging you need to provide either key or .p12 file. You can create in your developer account.Visit this link.

Also, its not compulsory if you are using firebase as a only database purpose. If you want push notification or cloud message then you need to provide this certificate or key things.

In your developer account you have to follow below steps

Step 1

Step 2

Step 3

Step 4


问:
Python: Is there a way to sort a string using only selected characters in the string?
For example, is there a way to sort the following:

```<code>model_1_depth/depth_w/read/_79__cf__79
model_2_depth/depth_w/read/_73__cf__73
model_3_depth/depth_w/read/_67__cf__67
model_4_depth/depth_w/read/_61__cf__61
model_5_depth/depth_w/read/_55__cf__55
model_6_depth/depth_w/read/_49__cf__49
model_7_depth/depth_w/read/_43__cf__43
model_8_depth/depth_w/read/_37__cf__37
model_9_depth/depth_w/read/_31__cf__31
model_10_depth/depth_w/read/_25__cf__25
model_11_depth/depth_w/read/_19__cf__19
model_12_depth/depth_w/read/_13__cf__13
model_13_depth/depth_w/read/_7__cf__7
model_13_point/weights/read/_4__cf__4
model_12_point/weights/read/_10__cf__10
model_11_point/weights/read/_16__cf__16
model_10_point/weights/read/_22__cf__22
model_9_point/weights/read/_28__cf__28
model_8_point/weights/read/_34__cf__34
model_7_point/weights/read/_40__cf__40
model_6_point/weights/read/_46__cf__46
model_5_point/weights/read/_52__cf__52
model_4_point/weights/read/_58__cf__58
model_3_point/weights/read/_64__cf__64
model_2_point/weights/read/_70__cf__70
model_1_point/weights/read/_76__cf__76
model_0/weights/read/_82__cf__82
</code>```

using only the integer that comes after "model"? I have tried to capture only these integers using re.sub("_", "", re.sub(r'[^\w]', '', key[6:8])) to get the integers to sort, but I'm unable to use the sorted result to locate back the original strings since there will be some duplicates, like '1' belongs to both model_1_point/weights/read/_76__cf__76 and model_1_depth/depth_w/read/_79__cf__79 and it won't be possible to distinguish the two.

Is there an elegant way to do this?

EDIT: To clarify, the following strings are in a dictionary, and I'm wanting to sort such that 1 is the smallest and 13 is the largest.

答:
Given this input:

```<code>my_text = '''model_1_depth/depth_w/read/_79__cf__79
model_2_depth/depth_w/read/_73__cf__73
model_3_depth/depth_w/read/_67__cf__67
model_4_depth/depth_w/read/_61__cf__61
model_5_depth/depth_w/read/_55__cf__55
model_6_depth/depth_w/read/_49__cf__49
model_7_depth/depth_w/read/_43__cf__43
model_8_depth/depth_w/read/_37__cf__37
model_9_depth/depth_w/read/_31__cf__31
model_10_depth/depth_w/read/_25__cf__25
model_11_depth/depth_w/read/_19__cf__19
model_12_depth/depth_w/read/_13__cf__13
model_13_depth/depth_w/read/_7__cf__7
model_13_point/weights/read/_4__cf__4
model_12_point/weights/read/_10__cf__10
model_11_point/weights/read/_16__cf__16
model_10_point/weights/read/_22__cf__22
model_9_point/weights/read/_28__cf__28
model_8_point/weights/read/_34__cf__34
model_7_point/weights/read/_40__cf__40
model_6_point/weights/read/_46__cf__46
model_5_point/weights/read/_52__cf__52
model_4_point/weights/read/_58__cf__58
model_3_point/weights/read/_64__cf__64
model_2_point/weights/read/_70__cf__70
model_1_point/weights/read/_76__cf__76
model_0/weights/read/_82__cf__82'''
</code>```

You can do the following:

```<code>my_text = my_text.split('\n')

b = sorted(my_text, key=lambda x: int(x.split('/')[0].split('_')[1]))
my_text_out = '\n'.join(b)
print(my_text_out)
</code>```

Which results in this:

```<code>model_0/weights/read/_82__cf__82
model_1_depth/depth_w/read/_79__cf__79
model_1_point/weights/read/_76__cf__76
model_2_depth/depth_w/read/_73__cf__73
model_2_point/weights/read/_70__cf__70
model_3_depth/depth_w/read/_67__cf__67
model_3_point/weights/read/_64__cf__64
model_4_depth/depth_w/read/_61__cf__61
model_4_point/weights/read/_58__cf__58
model_5_depth/depth_w/read/_55__cf__55
model_5_point/weights/read/_52__cf__52
model_6_depth/depth_w/read/_49__cf__49
model_6_point/weights/read/_46__cf__46
model_7_depth/depth_w/read/_43__cf__43
model_7_point/weights/read/_40__cf__40
model_8_depth/depth_w/read/_37__cf__37
model_8_point/weights/read/_34__cf__34
model_9_depth/depth_w/read/_31__cf__31
model_9_point/weights/read/_28__cf__28
model_10_depth/depth_w/read/_25__cf__25
model_10_point/weights/read/_22__cf__22
model_11_depth/depth_w/read/_19__cf__19
model_11_point/weights/read/_16__cf__16
model_12_depth/depth_w/read/_13__cf__13
model_12_point/weights/read/_10__cf__10
model_13_depth/depth_w/read/_7__cf__7
model_13_point/weights/read/_4__cf__4
</code>```

But as I said in the comments, a regex solution feels more appropriate here.

Body:
For example, is there a way to sort the following:

model_1_depth/depth_w/read/_79__cf__79
model_2_depth/depth_w/read/_73__cf__73
model_3_depth/depth_w/read/_67__cf__67
model_4_depth/depth_w/read/_61__cf__61
model_5_depth/depth_w/read/_55__cf__55
model_6_depth/depth_w/read/_49__cf__49
model_7_depth/depth_w/read/_43__cf__43
model_8_depth/depth_w/read/_37__cf__37
model_9_depth/depth_w/read/_31__cf__31
model_10_depth/depth_w/read/_25__cf__25
model_11_depth/depth_w/read/_19__cf__19
model_12_depth/depth_w/read/_13__cf__13
model_13_depth/depth_w/read/_7__cf__7
model_13_point/weights/read/_4__cf__4
model_12_point/weights/read/_10__cf__10
model_11_point/weights/read/_16__cf__16
model_10_point/weights/read/_22__cf__22
model_9_point/weights/read/_28__cf__28
model_8_point/weights/read/_34__cf__34
model_7_point/weights/read/_40__cf__40
model_6_point/weights/read/_46__cf__46
model_5_point/weights/read/_52__cf__52
model_4_point/weights/read/_58__cf__58
model_3_point/weights/read/_64__cf__64
model_2_point/weights/read/_70__cf__70
model_1_point/weights/read/_76__cf__76
model_0/weights/read/_82__cf__82

using only the integer that comes after "model"? I have tried to capture only these integers using re.sub("_", "", re.sub(r'[^\w]', '', key[6:8])) to get the integers to sort, but I'm unable to use the sorted result to locate back the original strings since there will be some duplicates, like '1' belongs to both model_1_point/weights/read/_76__cf__76 and model_1_depth/depth_w/read/_79__cf__79 and it won't be possible to distinguish the two.

Is there an elegant way to do this?

EDIT: To clarify, the following strings are in a dictionary, and I'm wanting to sort such that 1 is the smallest and 13 is the largest.

Body:
Given this input:

my_text = '''model_1_depth/depth_w/read/_79__cf__79
model_2_depth/depth_w/read/_73__cf__73
model_3_depth/depth_w/read/_67__cf__67
model_4_depth/depth_w/read/_61__cf__61
model_5_depth/depth_w/read/_55__cf__55
model_6_depth/depth_w/read/_49__cf__49
model_7_depth/depth_w/read/_43__cf__43
model_8_depth/depth_w/read/_37__cf__37
model_9_depth/depth_w/read/_31__cf__31
model_10_depth/depth_w/read/_25__cf__25
model_11_depth/depth_w/read/_19__cf__19
model_12_depth/depth_w/read/_13__cf__13
model_13_depth/depth_w/read/_7__cf__7
model_13_point/weights/read/_4__cf__4
model_12_point/weights/read/_10__cf__10
model_11_point/weights/read/_16__cf__16
model_10_point/weights/read/_22__cf__22
model_9_point/weights/read/_28__cf__28
model_8_point/weights/read/_34__cf__34
model_7_point/weights/read/_40__cf__40
model_6_point/weights/read/_46__cf__46
model_5_point/weights/read/_52__cf__52
model_4_point/weights/read/_58__cf__58
model_3_point/weights/read/_64__cf__64
model_2_point/weights/read/_70__cf__70
model_1_point/weights/read/_76__cf__76
model_0/weights/read/_82__cf__82'''

You can do the following:

my_text = my_text.split('\n')

b = sorted(my_text, key=lambda x: int(x.split('/')[0].split('_')[1]))
my_text_out = '\n'.join(b)
print(my_text_out)

Which results in this:

model_0/weights/read/_82__cf__82
model_1_depth/depth_w/read/_79__cf__79
model_1_point/weights/read/_76__cf__76
model_2_depth/depth_w/read/_73__cf__73
model_2_point/weights/read/_70__cf__70
model_3_depth/depth_w/read/_67__cf__67
model_3_point/weights/read/_64__cf__64
model_4_depth/depth_w/read/_61__cf__61
model_4_point/weights/read/_58__cf__58
model_5_depth/depth_w/read/_55__cf__55
model_5_point/weights/read/_52__cf__52
model_6_depth/depth_w/read/_49__cf__49
model_6_point/weights/read/_46__cf__46
model_7_depth/depth_w/read/_43__cf__43
model_7_point/weights/read/_40__cf__40
model_8_depth/depth_w/read/_37__cf__37
model_8_point/weights/read/_34__cf__34
model_9_depth/depth_w/read/_31__cf__31
model_9_point/weights/read/_28__cf__28
model_10_depth/depth_w/read/_25__cf__25
model_10_point/weights/read/_22__cf__22
model_11_depth/depth_w/read/_19__cf__19
model_11_point/weights/read/_16__cf__16
model_12_depth/depth_w/read/_13__cf__13
model_12_point/weights/read/_10__cf__10
model_13_depth/depth_w/read/_7__cf__7
model_13_point/weights/read/_4__cf__4

But as I said in the comments, a regex solution feels more appropriate here.


问:
Filtering columns in data table by vector of names
I am learning data.table and trying to filter certain columns by using a vector containing a set of column names.

```<code>> dt <- data.table(A=1:5, B=2:6, C=3:7)
> dt
   A B C
1: 1 2 3
2: 2 3 4
3: 3 4 5
4: 4 5 6
5: 5 6 7
>
> list <- c("A", "B")
> dt[ ,list, with=FALSE]
   A B
1: 1 2
2: 2 3
3: 3 4
4: 4 5
5: 5 6
>
</code>```

This works fine and filter columns.
However, the "missing" item in the list will return an error:

```<code>> list <- c("A", "B", "D")
> dt[ ,list, with=FALSE]
Error in `[.data.table`(dt, , list, with = FALSE) :
  column(s) not found: D
</code>```

How can I ignore the missing column name from the list and return just existing columns from the dt data.table?

答:
```<code>dt[ ,colnames(dt) %in% list, with=FALSE]
</code>```

Body:
I am learning data.table and trying to filter certain columns by using a vector containing a set of column names.

> dt <- data.table(A=1:5, B=2:6, C=3:7)
> dt
   A B C
1: 1 2 3
2: 2 3 4
3: 3 4 5
4: 4 5 6
5: 5 6 7
>
> list <- c("A", "B")
> dt[ ,list, with=FALSE]
   A B
1: 1 2
2: 2 3
3: 3 4
4: 4 5
5: 5 6
>

This works fine and filter columns.
However, the "missing" item in the list will return an error:

> list <- c("A", "B", "D")
> dt[ ,list, with=FALSE]
Error in `[.data.table`(dt, , list, with = FALSE) :
  column(s) not found: D

How can I ignore the missing column name from the list and return just existing columns from the dt data.table?


问:
Replacing all subsequent characters of a string, after matching a substring
I try to replace a character and all it's following characters within a string with another character.

This is my code so far.

```<code>String name = "Peter Pan";
name = name.replace("er", "abc");
Log.d("Name", name)
</code>```

the result should be: "Petabc"

I would highly appreciate any help on this matter!

答:
A way to achive your goal:

search the string for the first appearance of the sequnce you want to replace

use that index and cut the string using String#substring

add your replace sequence to the end of the substring you just created

fin.

Good luck.

EDIT

In code it might look like this (not tested)

```<code>public static String customReplace(String input, String replace)
{
int index = input.indexOf(replace);

if(index >= 0)
{
    return input.substring(index) + replace; //cutting string down to the required part and adding the replace
}
else
    return null; //String 'input' doesn't contain String 'replace'
}
</code>```

Body:
I try to replace a character and all it's following characters within a string with another character.

This is my code so far.

String name = "Peter Pan";
name = name.replace("er", "abc");
Log.d("Name", name)

the result should be: "Petabc"

I would highly appreciate any help on this matter!

Body:
A way to achive your goal:

search the string for the first appearance of the sequnce you want to replace

use that index and cut the string using String#substring

add your replace sequence to the end of the substring you just created

fin.

Good luck.

EDIT

In code it might look like this (not tested)

public static String customReplace(String input, String replace)
{
int index = input.indexOf(replace);

if(index >= 0)
{
    return input.substring(index) + replace; //cutting string down to the required part and adding the replace
}
else
    return null; //String 'input' doesn't contain String 'replace'
}


问:
Hide Button in unity3d
I'm a begginer in unity3d and I work on a simple game , there are some buttons and I want to hide them when I click on one of them.
Can anyone help me to do that in C# code?
Thanks</p>

答:
```<code>using UnityEngine.UI;

public class Example : MonoBehaviour{
    public Button Examplebtn;
}

public void onClickExampleEvent{
   Examplebtn.interactable=false;
}
</code>```

Title: Hide Button in unity3d


问:
Using lapply with more than one item that differs between function calls
I have a frequency cross-tabulation dataset, so columns A01-A04 in the example are counts of CAGs e.g. A01 has 6485 counts of 13 CAGs, 35 counts of 14 CAGs. Each column is a sample. The mode of each sample is the CAG value for which the count is the highest (e.g. 13 for A01).

With the help of stack overflow I've written a function with lapply ('prop') that sums the values in each column above and below the mode, and works out the proportion that are greater than the mode.

However, each sample has a control, as defined in 'settings' e.g. the control for A02 is A01. I would now like to adapt 'prop' so that for each sample it uses its control mode, rather than the sample's own mode. For this it will need to look up which sample it should use in 'settings', then look up the control sample's mode in 'sample mode', then use that value in 'prop'. Unfortunately I believe only one item can vary in each iteration of lapply. I'd be very grateful for help in adapting.

```<code>#Data set
data <- data.frame(CAG = c(13, 14, 15, 17),
               A01 = c(6485,35,132, 12),
               A02 = c(0,42,56, 4),
               A03 = c(33,5014,2221, 18),
               A04 = c(106,89,436, 11))

#Define controls for each sample
settings <- data.frame(samples = c('A01', 'A02', 'A03', 'A04'),
                   control = c('A01', 'A01', 'A03', 'A03'))

#Mode
samplemode <- data.frame(samples = c('A01', 'A02', 'A03', 'A04'),
                     samplemode = (data[sapply(data[2:ncol(data)], which.max), ]$CAG))

#Proportion of values > mode ##I NEED TO ADAPT THIS FUNCTION TO CALCULATE     'ctrlprop' USING THE CONTROL MODE OF EACH SAMPLE RATHER THAN 'mod'##
prop <- lapply(data[, 2:ncol(data)], function(x) {
  mod <- data$CAG[which.max(x)] #Calculate mode for each column
  B <- sum(x[data$CAG >= mod]) #Sum heights > mode
  A <- sum(x[data$CAG <= mod]) #Sum heights < mode
  B/(A+B)
})

prop <- as.data.frame(prop) #Convert output from list to data frame
prop <- t(prop) #Transpose so samples in rows and result in columnrm
results <- prop

#Expected results
expected <- data.frame(samples = settings$samples,
                   prop = c(0.5068066, 0.3797468, 0.5896748, 0.4146568),
                   ctrlprop = c(0.5068066, 1.0000000, 0.58967480, 0.73324213))
</code>```

答:
settings2 <- data.frame(samples = settings$Sample file name, control = settings$Control sample)
    res <- lapply(names(height[,7:ncol(height)]), function(x){
    mod_cntrl <- mode[mode$sample == as.character(settings2[settings2$samples == x,2]),2]
    B <- sum(height[,x][height$CAG >= mod_cntrl]) #Sum heights > mode
    A <- sum(height[,x][height$CAG <= mod_cntrl]) #Sum heights < mode
    mod_smpl <- height$CAG[which.max(height[,x])]
    C <- sum(height[,x][height$CAG >= mod_smpl])
    D <- sum(height[,x][height$CAG <= mod_smpl])

```<code>data.frame(sample=x,prop = C/(C+D),ctrlprop = B/(A+B))
})
</code>```

test <- do.call(rbind,res)

Body:
I have a frequency cross-tabulation dataset, so columns A01-A04 in the example are counts of CAGs e.g. A01 has 6485 counts of 13 CAGs, 35 counts of 14 CAGs. Each column is a sample. The mode of each sample is the CAG value for which the count is the highest (e.g. 13 for A01).

With the help of stack overflow I've written a function with lapply ('prop') that sums the values in each column above and below the mode, and works out the proportion that are greater than the mode.

However, each sample has a control, as defined in 'settings' e.g. the control for A02 is A01. I would now like to adapt 'prop' so that for each sample it uses its control mode, rather than the sample's own mode. For this it will need to look up which sample it should use in 'settings', then look up the control sample's mode in 'sample mode', then use that value in 'prop'. Unfortunately I believe only one item can vary in each iteration of lapply. I'd be very grateful for help in adapting.

#Data set
data <- data.frame(CAG = c(13, 14, 15, 17),
               A01 = c(6485,35,132, 12),
               A02 = c(0,42,56, 4),
               A03 = c(33,5014,2221, 18),
               A04 = c(106,89,436, 11))

#Define controls for each sample
settings <- data.frame(samples = c('A01', 'A02', 'A03', 'A04'),
                   control = c('A01', 'A01', 'A03', 'A03'))

#Mode
samplemode <- data.frame(samples = c('A01', 'A02', 'A03', 'A04'),
                     samplemode = (data[sapply(data[2:ncol(data)], which.max), ]$CAG))

#Proportion of values > mode ##I NEED TO ADAPT THIS FUNCTION TO CALCULATE     'ctrlprop' USING THE CONTROL MODE OF EACH SAMPLE RATHER THAN 'mod'##
prop <- lapply(data[, 2:ncol(data)], function(x) {
  mod <- data$CAG[which.max(x)] #Calculate mode for each column
  B <- sum(x[data$CAG >= mod]) #Sum heights > mode
  A <- sum(x[data$CAG <= mod]) #Sum heights < mode
  B/(A+B)
})

prop <- as.data.frame(prop) #Convert output from list to data frame
prop <- t(prop) #Transpose so samples in rows and result in columnrm
results <- prop

#Expected results
expected <- data.frame(samples = settings$samples,
                   prop = c(0.5068066, 0.3797468, 0.5896748, 0.4146568),
                   ctrlprop = c(0.5068066, 1.0000000, 0.58967480, 0.73324213))

Body:
    settings2 <- data.frame(samples = settings$Sample file name, control = settings$Control sample)
    res <- lapply(names(height[,7:ncol(height)]), function(x){
    mod_cntrl <- mode[mode$sample == as.character(settings2[settings2$samples == x,2]),2]
    B <- sum(height[,x][height$CAG >= mod_cntrl]) #Sum heights > mode
    A <- sum(height[,x][height$CAG <= mod_cntrl]) #Sum heights < mode
    mod_smpl <- height$CAG[which.max(height[,x])]
    C <- sum(height[,x][height$CAG >= mod_smpl])
    D <- sum(height[,x][height$CAG <= mod_smpl])

data.frame(sample=x,prop = C/(C+D),ctrlprop = B/(A+B))
})

test <- do.call(rbind,res)


问:
SQLIte how to insert unique data on change of column value
I am using SQLite Database for my application. I have 4 columns-  Student_Name,Student_Enroll, Student_Mob, Student_Address in my database. Now I can add new record if and only if one of four column value is different or all values are different. If all column values are same then no new record should be generated.
Can you please guide me to solve this issue?</p>

答:
Solution 1: (Simple)

Define all columns as unique:

```<code>create table TableName (id  integer primary key autoincrement,
Student_Name text not null unique,
Student_Enroll text not null unique,
Student_Mob text not null unique);
</code>```

You can add Student_Address as well, if you need to

Solution 2: (bit complex)

Use AND Operator with WHERE clause

```<code>INSERT INTO TableName (Student_Name, Student_Enroll, Student_Mob)
SELECT varStudentName, varStudentEnroll, varStudentMob
WHERE NOT EXISTS(SELECT 1 FROM TableName WHERE Student_Name = varStudentName OR Student_Enroll = varStudentEnroll OR Student_Mob = varStudentMob );

//If a record already contains a row, then the insert operation will be ignored.
</code>```

You can find more information at the sqlite manual.

Live Example:

Open SQLite Online

Paste following code:

```<code>INSERT INTO demo (id,name,hint)
SELECT 4, 'jQuery', 'is a cross-platform JavaScript library designed to simplify the client-side scripting of HTML'
WHERE NOT EXISTS(SELECT 1 FROM demo WHERE name = 'jQuery' OR hint = 'is a cross-platform JavaScript library designed to simplify the client-side scripting of HTML' );

SELECT * from demo
</code>```

Hit RUN

This won't insert 4th record and if you modify both values of WHERE clause then record will be inserted.

Body:
Solution 1: (Simple)

Define all columns as unique:

create table TableName (id  integer primary key autoincrement,
Student_Name text not null unique,
Student_Enroll text not null unique,
Student_Mob text not null unique);

You can add Student_Address as well, if you need to

Solution 2: (bit complex)

Use AND Operator with WHERE clause

INSERT INTO TableName (Student_Name, Student_Enroll, Student_Mob)
SELECT varStudentName, varStudentEnroll, varStudentMob
WHERE NOT EXISTS(SELECT 1 FROM TableName WHERE Student_Name = varStudentName OR Student_Enroll = varStudentEnroll OR Student_Mob = varStudentMob );

//If a record already contains a row, then the insert operation will be ignored.

You can find more information at the sqlite manual.

Live Example:

Open SQLite Online

Paste following code:

INSERT INTO demo (id,name,hint)
SELECT 4, 'jQuery', 'is a cross-platform JavaScript library designed to simplify the client-side scripting of HTML'
WHERE NOT EXISTS(SELECT 1 FROM demo WHERE name = 'jQuery' OR hint = 'is a cross-platform JavaScript library designed to simplify the client-side scripting of HTML' );

SELECT * from demo

Hit RUN

This won't insert 4th record and if you modify both values of WHERE clause then record will be inserted.


答:
Despite of set your column as UNIQUE you also need to resolve the conflict created on each column when you try to insert new data.

To do so, define the behavior to solve the conflict:

```<code>"CREATE TABLE table (your columns here...(UNIQUE unique colums here...) ON CONFLICT REPLACE);"
</code>```

Title: SQLIte how to insert unique data on change of column value

Body:
I am using SQLite Database for my application. I have 4 columns-  Student_Name,Student_Enroll, Student_Mob, Student_Address in my database. Now I can add new record if and only if one of four column value is different or all values are different. If all column values are same then no new record should be generated.
Can you please guide me to solve this issue?

Body:
Despite of set your column as UNIQUE you also need to resolve the conflict created on each column when you try to insert new data.

To do so, define the behavior to solve the conflict:

"CREATE TABLE table (your columns here...(UNIQUE unique colums here...) ON CONFLICT REPLACE);"


问:
Generating a QueryTable succeeds in ColdFusion but fails in Java
I have the Java code snippet:

```<code>import coldfusion.runtime.Struct;
import java.sql.ResultSet;
import java.sql.SQLException;
import oracle.jdbc.OracleCallableStatement;

public class CursorTest {
  public static Struct getCursor() throws SQLException {
    OracleCallableStatement statement = null;
    Struct variables = new Struct();
    // prepare statement with a cursor out parameter
    ResultSet results = statement.getCursor( 1 );
    variables.put ( "cursor", results );
    return variables;
  }
}
</code>```

Including the cfusion.jar and the hotfix jars from the ColdFusion lib directoy and Oracle's ojdbc6.jar in the build path.

I can run it in ColdFusion:

```<code><cfscript>
  vars   = createObject( 'java', 'CursorTest' ).getCursor();
  cursor = createObject( 'java', 'coldfusion.sql.QueryTable' )
             .init( vars.cursor )
             .firstTable();
  WriteDump( cursor );
  // close the statement and connection.
</cfscript>
</code>```

This works and the QueryTable is created.

However, trying to move the generation of the QueryTable into the Java code:

```<code>import coldfusion.runtime.Struct;
import coldfusion.sql.QueryTable;
import coldfusion.sql.Table;
import java.sql.ResultSet;
import java.sql.SQLException;
import oracle.jdbc.OracleCallableStatement;

public class CursorTest {
  public static Struct getCursor() throws SQLException {
    OracleCallableStatement statement = null;
    Struct variables = new Struct();
    // prepare statement with a cursor out parameter
    ResultSet results = statement.getCursor( 1 );
    Table table = new QueryTable( results ).firstTable();
    variables.put ( "cursor", table );
    return variables;
  }
}
</code>```

Fails to build with:

```<code>error: cannot access QueryTableWrapper
      Table table = new QueryTable( results ).firstTable();
                    ^
  class file for coldfusion.runtime.QueryTableWrapper not found
</code>```

Now, the error is self explanatory and unpacking the Jar files shows that that file is not there ... however, I cannot find it in any of the other Jar files that are in the ColdFusion lib directory, ColdFusion's JRE directory or other Jars that might be on ColdFusion's class path.

Does anyone know where this file is located so I can include it on the build path or, alternatively, how ColdFusion manages to generate the QueryTable using createObject without that wrapper?

答:
coldFusion.sql.QueryTable has multiple constructors:

QueryTable()

QueryTable( Query cfx )

QueryTable( QueryTable rs )

QueryTable( QueryTableWrapper qtWrapper )

QueryTable( ResultSet rs )

QueryTable( int rows )

QueryTable( QueryTable rs, int maxrows )

QueryTable( int rows, String collist )

QueryTable( int rows, String[] cols )

QueryTable( int rows, String[] cols, String[] sqlColTypeNames )

QueryTable( int rows, String[] cols, String[] sqlColTypeNames, int[] sqlColTypes )

The first 7 constructors listed there all use, somewhere under the surface, QueryTableWrapper and fail in Java as the class cannot be found.

However, QueryTable( int rows, String[] cols, String[] sqlColTypeNames, int[] sqlColTypes ) does not use this wrapper.

So, while you cannot pass in a ResultSet, Query or an existing QueryTable and have it automatically parsed by the constructor, you can generate an empty QueryTable and then parse the ResultSet and add it row-by-row to the QueryTable like this:

```<code>final OracleResultSet results    = statement.getCursor( 1 );
final ResultSetMetaData metadata = results.getMetadata();
final int columns                = metadata.getColumnCount();
final String[] colNames          = new String[ columns ];
final String[] sqlColTypeNames   = new String[ columns ];
final int[] sqlColTypes          = new int[ columns ];
final boolean[] caseSensitive    = new boolean[ columns ];

for ( int i = 1; i <= columns; i++ )
{
  colNames[i-1]        = metadata.getColumnName( i );
  sqlColTypeNames[i-1] = metadata.getColumnTypeName( i );
  sqlColTypes[i-1]     = metadata.getColumnType( i );
  caseSensitive[i-1]   = metadata.isCaseSensitive( i );
}
final QueryTable table = new QueryTable(
  0,
  colNames,
  sqlColTypeNames,
  sqlColTypes
);
table.getMeta().setColumnCase( caseSensitive );

int rows = 0;
while ( results.next() )
{
  table.addRows( 1 );
  ++rows;
  for ( int c = 1; c <= columns; ++c )
  {
    Object value = null;
    switch( sqlColTypes[c-1] )
    {
      case OracleTypes.ARRAY:   value = results.getARRAY( c ).getArray();
                                break;
      case OracleTypes.VARCHAR: value = results.getString( c );
                                break;
      case OracleTypes.DATE:    value = results.getDate( c );
                                break;
      case OracleTypes.NUMERIC: value = results.getBigDecimal( c );
                                break;
      // Add other types
      default:                throw new UnsupportedOperationException( "Unable to handle: " + sqlColTypes[c-1] );
    }
    if ( results.wasNull() )
    {
      value = null;
    }
    table.setField( rows, c, value );
  }
}
</code>```

The QueryTable.firstTable() can then be returned back to ColdFusion and used as if it was a query result generated by any of the built-in ColdFusion functions.

Body:
I have the Java code snippet:

import coldfusion.runtime.Struct;
import java.sql.ResultSet;
import java.sql.SQLException;
import oracle.jdbc.OracleCallableStatement;

public class CursorTest {
  public static Struct getCursor() throws SQLException {
    OracleCallableStatement statement = null;
    Struct variables = new Struct();
    // prepare statement with a cursor out parameter
    ResultSet results = statement.getCursor( 1 );
    variables.put ( "cursor", results );
    return variables;
  }
}

Including the cfusion.jar and the hotfix jars from the ColdFusion lib directoy and Oracle's ojdbc6.jar in the build path.

I can run it in ColdFusion:

<cfscript>
  vars   = createObject( 'java', 'CursorTest' ).getCursor();
  cursor = createObject( 'java', 'coldfusion.sql.QueryTable' )
             .init( vars.cursor )
             .firstTable();
  WriteDump( cursor );
  // close the statement and connection.
</cfscript>

This works and the QueryTable is created.

However, trying to move the generation of the QueryTable into the Java code:

import coldfusion.runtime.Struct;
import coldfusion.sql.QueryTable;
import coldfusion.sql.Table;
import java.sql.ResultSet;
import java.sql.SQLException;
import oracle.jdbc.OracleCallableStatement;

public class CursorTest {
  public static Struct getCursor() throws SQLException {
    OracleCallableStatement statement = null;
    Struct variables = new Struct();
    // prepare statement with a cursor out parameter
    ResultSet results = statement.getCursor( 1 );
    Table table = new QueryTable( results ).firstTable();
    variables.put ( "cursor", table );
    return variables;
  }
}

Fails to build with:

error: cannot access QueryTableWrapper
      Table table = new QueryTable( results ).firstTable();
                    ^
  class file for coldfusion.runtime.QueryTableWrapper not found

Now, the error is self explanatory and unpacking the Jar files shows that that file is not there ... however, I cannot find it in any of the other Jar files that are in the ColdFusion lib directory, ColdFusion's JRE directory or other Jars that might be on ColdFusion's class path.

Does anyone know where this file is located so I can include it on the build path or, alternatively, how ColdFusion manages to generate the QueryTable using createObject without that wrapper?

Body:
coldFusion.sql.QueryTable has multiple constructors:

QueryTable()

QueryTable( Query cfx )

QueryTable( QueryTable rs )

QueryTable( QueryTableWrapper qtWrapper )

QueryTable( ResultSet rs )

QueryTable( int rows )

QueryTable( QueryTable rs, int maxrows )

QueryTable( int rows, String collist )

QueryTable( int rows, String[] cols )

QueryTable( int rows, String[] cols, String[] sqlColTypeNames )

QueryTable( int rows, String[] cols, String[] sqlColTypeNames, int[] sqlColTypes )

The first 7 constructors listed there all use, somewhere under the surface, QueryTableWrapper and fail in Java as the class cannot be found.

However, QueryTable( int rows, String[] cols, String[] sqlColTypeNames, int[] sqlColTypes ) does not use this wrapper.

So, while you cannot pass in a ResultSet, Query or an existing QueryTable and have it automatically parsed by the constructor, you can generate an empty QueryTable and then parse the ResultSet and add it row-by-row to the QueryTable like this:

final OracleResultSet results    = statement.getCursor( 1 );
final ResultSetMetaData metadata = results.getMetadata();
final int columns                = metadata.getColumnCount();
final String[] colNames          = new String[ columns ];
final String[] sqlColTypeNames   = new String[ columns ];
final int[] sqlColTypes          = new int[ columns ];
final boolean[] caseSensitive    = new boolean[ columns ];

for ( int i = 1; i <= columns; i++ )
{
  colNames[i-1]        = metadata.getColumnName( i );
  sqlColTypeNames[i-1] = metadata.getColumnTypeName( i );
  sqlColTypes[i-1]     = metadata.getColumnType( i );
  caseSensitive[i-1]   = metadata.isCaseSensitive( i );
}
final QueryTable table = new QueryTable(
  0,
  colNames,
  sqlColTypeNames,
  sqlColTypes
);
table.getMeta().setColumnCase( caseSensitive );

int rows = 0;
while ( results.next() )
{
  table.addRows( 1 );
  ++rows;
  for ( int c = 1; c <= columns; ++c )
  {
    Object value = null;
    switch( sqlColTypes[c-1] )
    {
      case OracleTypes.ARRAY:   value = results.getARRAY( c ).getArray();
                                break;
      case OracleTypes.VARCHAR: value = results.getString( c );
                                break;
      case OracleTypes.DATE:    value = results.getDate( c );
                                break;
      case OracleTypes.NUMERIC: value = results.getBigDecimal( c );
                                break;
      // Add other types
      default:                throw new UnsupportedOperationException( "Unable to handle: " + sqlColTypes[c-1] );
    }
    if ( results.wasNull() )
    {
      value = null;
    }
    table.setField( rows, c, value );
  }
}

The QueryTable.firstTable() can then be returned back to ColdFusion and used as if it was a query result generated by any of the built-in ColdFusion functions.


问:
How can I convert this native SQL to HQL/JPQL or a Criteria Query using Hibernate?
```<code>SELECT T1.ORGANIZATIONID, T1.CODE, T1.RFQCATEGORYID, T1.OWNERID,
T1.PARTCOUNT, T1.DESCRIPTION,T1.STATUSCODE, T1."COMMENT", T1.CREATEID,
T1.CREATEDATE, T1.UPDATEID, T1.UPDATEDATE, T2.CODE, T2.DESCRIPTION,
T3.ORGANIZATIONNAME, T3.ORGANIZATIONURL, T4.SALUTATION, T4.FIRSTNAME,
T4.LASTNAME, T4.EMAIL,T4.FINANCIAL_LIMIT, T5.ORGANIZATIONNAME
USR_ORGNAME,T5.ORGANIZATIONURL USR_ORGURL, T6.STARTDATE, T6.ENDDATE,
T6.OPENDATE, T6.RFQID, T6.PARTNUMBER,
T7.RFQTYPEID,T1.CURRENCYID,T1.MINQUOTECOUNT,T1.ISMATCHING,T1.ISMULTICURR,
T1.ESTIMATEDVALUE,T1.RAENABLED,T1.PAYMENTENABLED,T1.ISPRICEACPTINRA,
T8.DESCRIPTION AS RFQTYPEDESC , T1.FOREIGNCURRONLY , T1.DELEGATE ,
T1.LOCATIONID ,T6.INITIATERAID ,T10.AUTHENTICATIONCODE
,T6.DOCUMENTSALEENDDATE,T1.OWNER_DIGITAL_CERT_ID , T1.ANNUALVALUE ,
CASE WHEN (SELECT COUNT(1) FROM EPS.ORGLOCATION WHERE LOCATION_ID =
T1.LOCATIONID AND ORGID = T1.ORGANIZATIONID ) >0 THEN  (SELECT
DESCRIPTION FROM EPS.ORGLOCATION WHERE LOCATION_ID = T1.LOCATIONID AND
ORGID = T1.ORGANIZATIONID) ELSE '' END AS LOCATIONDESC,
T1.MATIHINGVALUE,T1.SKIPQUOTE,T1.WCENABLED,T1.LOADTYPE,T6.DISALLOWBIDREV,T6.UPDATEDATE
AS RFQDATE_UPDATEDATE,T1.SIGNED,T1.ENCRYPTED,T1.OLDCODE
,T1.IMPACTBIDFLAG,T1.LOADING_EVALUATED,T1.ENCKEYENABLED,T1.VALUEFLAG,od.code
as designation, (SELECT MIN(UPDATEDATE) FROM EPS.HRFQ WHERE RFQID =
T1.RFQ_ID AND STATUSCODE= 'A' ) PUBLISH_DATE,LCNCMATCHING, T1.BOQ,
B.DESCRIPTION AS BOQDESC, T6.PHYSICALDOCSUBENDDATE, T1.AUCTIONSTYLE,
T1.AUCTIONTYPE, T1.AUCTIONSTATUS, T1.AUCTIONFILENAME,
T1.AUCTIONCOMMENT,T1.ITEMSUBMITBY, T1.AUCTIONWINNER  FROM EPS.RFQ T1
LEFT JOIN EPS.BOQ B ON T1.BOQ=B.BOQ_ID left outer join (select * from
EPS.RFQDATE where partnumber=?) T6 on t6.RFQID=t1.RFQ_ID left outer
join EPS.RFQRFQTYPE T7 on t7.RFQID=t1.RFQ_ID,EPS.RFQCAT T2,
EPS.ORGANIZATION T3,EPS."USER" T4 left outer join eps.orgdesignation
od on od.designation_id=t4.designationid, EPS.ORGANIZATION T5,
EPS.AUTHENTICATION T10, EPS.RFQTYPE T8 WHERE T1.RFQCATEGORYID =
T2.RFQCAT_ID AND T1.ORGANIZATIONID = T3.ORGANIZATION_ID AND T1.OWNERID
= T4.USER_ID AND T4.ORGANIZATIONID = T5.ORGANIZATION_ID AND T10.USERID = T4.USER_ID AND T4.ORGANIZATIONID = T10.ORGANIZATIONID AND T1.RFQ_ID = ?  AND T8.RFQTYPE_ID = T7.RFQTYPEID
</code>```

I want to convert it into hibernate. How can I do this?

答:
You have two choices here.

If you want to use your SQL as-is, you use createNativeQuery in order to supply a potentially database dependent SQL.  You can supply compliant SQL that will run across all of your potential database vendors to avoid any database dependence issues, but this is definitely an option, particularly when you need to make use of certain database features.

Use JPQL/HQL or Criteria API.  This is essentially an abstraction atop of SQL itself allowing you to write your query in a language or way that is agnostic to the database as Hibernate will translate it for you to your database platform's syntax where applicable.

Your native query is somewhat complex so my suggestion if you want to use option (2) would be to decompose it into simpler parts and build upon each step iteratively until you have what you need.

The first thing to note is your base query is against a table named RFQ by ID.  If you don't have an entity that represents your RFQ table, create one and expose the basic string and numeric attributes which you're trying to return from this base table.  Then in order to query against this you would write

```<code>List<Rfq> rfqs = session
  .createQuery( "SELECT r FROM Rfq r WHERE r.id = :id", Rfq.class )
  .setParameter( "id", rfqId )
  .getResultList();
</code>```

From this point its a matter of building additional entities and relationships between your RFQ table and the joined tables, the attributes in each one, and then returning them as a part of the select clause as desired.

Body:
SELECT T1.ORGANIZATIONID, T1.CODE, T1.RFQCATEGORYID, T1.OWNERID,
T1.PARTCOUNT, T1.DESCRIPTION,T1.STATUSCODE, T1."COMMENT", T1.CREATEID,
T1.CREATEDATE, T1.UPDATEID, T1.UPDATEDATE, T2.CODE, T2.DESCRIPTION,
T3.ORGANIZATIONNAME, T3.ORGANIZATIONURL, T4.SALUTATION, T4.FIRSTNAME,
T4.LASTNAME, T4.EMAIL,T4.FINANCIAL_LIMIT, T5.ORGANIZATIONNAME
USR_ORGNAME,T5.ORGANIZATIONURL USR_ORGURL, T6.STARTDATE, T6.ENDDATE,
T6.OPENDATE, T6.RFQID, T6.PARTNUMBER,
T7.RFQTYPEID,T1.CURRENCYID,T1.MINQUOTECOUNT,T1.ISMATCHING,T1.ISMULTICURR,
T1.ESTIMATEDVALUE,T1.RAENABLED,T1.PAYMENTENABLED,T1.ISPRICEACPTINRA,
T8.DESCRIPTION AS RFQTYPEDESC , T1.FOREIGNCURRONLY , T1.DELEGATE ,
T1.LOCATIONID ,T6.INITIATERAID ,T10.AUTHENTICATIONCODE
,T6.DOCUMENTSALEENDDATE,T1.OWNER_DIGITAL_CERT_ID , T1.ANNUALVALUE ,
CASE WHEN (SELECT COUNT(1) FROM EPS.ORGLOCATION WHERE LOCATION_ID =
T1.LOCATIONID AND ORGID = T1.ORGANIZATIONID ) >0 THEN  (SELECT
DESCRIPTION FROM EPS.ORGLOCATION WHERE LOCATION_ID = T1.LOCATIONID AND
ORGID = T1.ORGANIZATIONID) ELSE '' END AS LOCATIONDESC,
T1.MATIHINGVALUE,T1.SKIPQUOTE,T1.WCENABLED,T1.LOADTYPE,T6.DISALLOWBIDREV,T6.UPDATEDATE
AS RFQDATE_UPDATEDATE,T1.SIGNED,T1.ENCRYPTED,T1.OLDCODE
,T1.IMPACTBIDFLAG,T1.LOADING_EVALUATED,T1.ENCKEYENABLED,T1.VALUEFLAG,od.code
as designation, (SELECT MIN(UPDATEDATE) FROM EPS.HRFQ WHERE RFQID =
T1.RFQ_ID AND STATUSCODE= 'A' ) PUBLISH_DATE,LCNCMATCHING, T1.BOQ,
B.DESCRIPTION AS BOQDESC, T6.PHYSICALDOCSUBENDDATE, T1.AUCTIONSTYLE,
T1.AUCTIONTYPE, T1.AUCTIONSTATUS, T1.AUCTIONFILENAME,
T1.AUCTIONCOMMENT,T1.ITEMSUBMITBY, T1.AUCTIONWINNER  FROM EPS.RFQ T1
LEFT JOIN EPS.BOQ B ON T1.BOQ=B.BOQ_ID left outer join (select * from
EPS.RFQDATE where partnumber=?) T6 on t6.RFQID=t1.RFQ_ID left outer
join EPS.RFQRFQTYPE T7 on t7.RFQID=t1.RFQ_ID,EPS.RFQCAT T2,
EPS.ORGANIZATION T3,EPS."USER" T4 left outer join eps.orgdesignation
od on od.designation_id=t4.designationid, EPS.ORGANIZATION T5,
EPS.AUTHENTICATION T10, EPS.RFQTYPE T8 WHERE T1.RFQCATEGORYID =
T2.RFQCAT_ID AND T1.ORGANIZATIONID = T3.ORGANIZATION_ID AND T1.OWNERID
= T4.USER_ID AND T4.ORGANIZATIONID = T5.ORGANIZATION_ID AND T10.USERID = T4.USER_ID AND T4.ORGANIZATIONID = T10.ORGANIZATIONID AND T1.RFQ_ID = ?  AND T8.RFQTYPE_ID = T7.RFQTYPEID

I want to convert it into hibernate. How can I do this?

Body:
You have two choices here.

If you want to use your SQL as-is, you use createNativeQuery in order to supply a potentially database dependent SQL.  You can supply compliant SQL that will run across all of your potential database vendors to avoid any database dependence issues, but this is definitely an option, particularly when you need to make use of certain database features.

Use JPQL/HQL or Criteria API.  This is essentially an abstraction atop of SQL itself allowing you to write your query in a language or way that is agnostic to the database as Hibernate will translate it for you to your database platform's syntax where applicable.

Your native query is somewhat complex so my suggestion if you want to use option (2) would be to decompose it into simpler parts and build upon each step iteratively until you have what you need.

The first thing to note is your base query is against a table named RFQ by ID.  If you don't have an entity that represents your RFQ table, create one and expose the basic string and numeric attributes which you're trying to return from this base table.  Then in order to query against this you would write

List<Rfq> rfqs = session
  .createQuery( "SELECT r FROM Rfq r WHERE r.id = :id", Rfq.class )
  .setParameter( "id", rfqId )
  .getResultList();

From this point its a matter of building additional entities and relationships between your RFQ table and the joined tables, the attributes in each one, and then returning them as a part of the select clause as desired.


问:
Spring Integration - TCP Outbound Channel adds unwanted CRLF at the end of each line
I am reading large files using the following code and sending the file content over a TCP connection buffer by buffer. At the end of each send the TCP channel adds a CRLF character. I don't want this to appear in the results unless I add it.

```<code>        final int BUFFER_SIZE = 65536;
    long bytesToSkip = 0;
    byte[] buffer = new byte[BUFFER_SIZE];

    try (RandomAccessFile rand = new RandomAccessFile(new File(requestModel.getFilePath()), "r");
    ) {

        rand.seek(bytesToSkip);
        while ((read = rand.read(buffer)) != -1) {

            MessageBuilder mb = MessageBuilder.withPayload(buffer).setHeaderIfAbsent(IpHeaders.CONNECTION_ID, connectionId);
            outMsgChannel.send(mb.build())

            buffer = new byte[BUFFER_SIZE];
        }
    }
    catch(Exceptions ..............
</code>```

Sample output where new line is added. (Both the buffers are huge. I have mentioned only the lines causing problems at the end of each buffer)

Buffer One contained

A quick brown fox jumps over the lazy dog

A quick brown fox jumps over
  the lazy dog

A quick brown fox jumps over the

Buffer Two Contains

lazy dog

If there is no unwanted CRLF then I will not get the issue of single line splitting in to two in output.. I want to have new lines only where the file has.

答:
See the documentation.

TCP is a streaming protocol; this means that some structure has to be provided to data transported over TCP, so the receiver can demarcate the data into discrete messages. Connection factories are configured to use (de)serializers to convert between the message payload and the bits that are sent over TCP. This is accomplished by providing a deserializer and serializer for inbound and outbound messages respectively. A number of standard (de)serializers are provided.

The ByteArrayCrlfSerializer, converts a byte array to a stream of bytes followed by carriage return and linefeed characters (\r\n). This is the default (de)serializer and can be used with telnet as a client, for example.

...

You need some way to know when the message is complete - the underlying network might packetize your message so it is received in chunks.

The ByteArrayRawSerializer adds no characters to the message; it might satisfy your needs. When used on the reading side, it uses the socket EOF to indicate the message is complete.

Body:
I am reading large files using the following code and sending the file content over a TCP connection buffer by buffer. At the end of each send the TCP channel adds a CRLF character. I don't want this to appear in the results unless I add it.

        final int BUFFER_SIZE = 65536;
    long bytesToSkip = 0;
    byte[] buffer = new byte[BUFFER_SIZE];

    try (RandomAccessFile rand = new RandomAccessFile(new File(requestModel.getFilePath()), "r");
    ) {

        rand.seek(bytesToSkip);
        while ((read = rand.read(buffer)) != -1) {

            MessageBuilder mb = MessageBuilder.withPayload(buffer).setHeaderIfAbsent(IpHeaders.CONNECTION_ID, connectionId);
            outMsgChannel.send(mb.build())

            buffer = new byte[BUFFER_SIZE];
        }
    }
    catch(Exceptions ..............

Sample output where new line is added. (Both the buffers are huge. I have mentioned only the lines causing problems at the end of each buffer)

Buffer One contained

A quick brown fox jumps over the lazy dog

A quick brown fox jumps over
  the lazy dog

A quick brown fox jumps over the

Buffer Two Contains

lazy dog

If there is no unwanted CRLF then I will not get the issue of single line splitting in to two in output.. I want to have new lines only where the file has.


问:
Angular Lazy loading from node_modules
I split my project between multiple Git Repos and now I have problem with Lazy loading

If I Copy the sourceCode from child repo to main repo, with use of the following syntax

```<code>{
    path: 'child-app',
    loadChildren: './shared/child/src/app/child-app.module#ChildAppModule'
},
</code>```

I can build and serve my project without any problem
But if I change the Route to point to node_modules like below

```<code>{
    path: 'child-app',
    loadChildren: '@mine/child/src/app/child-app.module#ChildAppModule'
},
</code>```

OR

```<code>{
    path: 'child-app',
    loadChildren: '../../node_modules/@mine/child/src/app/child-app.module#ChildAppModule'
},
</code>```

It will raise this error :

```<code>ERROR in ./src/$$_gendir lazy
Module not found: Error: Can't resolve '/Users/myuser/Projects/web-app
/src/node_modules/@mine/child/src/app/child-app.module.module.ngfact
ory.ts' in '/Users/myuser/Projects/web-app/src/$$_gendir'
 @ ./src/$$_gendir lazy
 @ ./~/@angular/core/@angular/core.es5.js
 @ ./src/main.browser.ts
 @ multi ./src/main.browser.ts webpack-hot-middleware/client?path=/__webpa
ck_hmr&timeout=2000&reload=true&noInfo=true
</code>```

I am using webpack 2 and ngtools/webpack to compiling my project

答:
Lazy loading module from node_modules with JIT is working fine but Lazy loading with AOT is not working

github.com/angular/angular-cli/issues/5986

the best solution that I found is creating a symlink from src/app/something to node_modules/something

```<code>ln -s source destination
</code>```

and it is working fine :)

Title: Angular Lazy loading from node_modules

Body:
I split my project between multiple Git Repos and now I have problem with Lazy loading

If I Copy the sourceCode from child repo to main repo, with use of the following syntax

{
    path: 'child-app',
    loadChildren: './shared/child/src/app/child-app.module#ChildAppModule'
},

I can build and serve my project without any problem
But if I change the Route to point to node_modules like below

{
    path: 'child-app',
    loadChildren: '@mine/child/src/app/child-app.module#ChildAppModule'
},

OR

{
    path: 'child-app',
    loadChildren: '../../node_modules/@mine/child/src/app/child-app.module#ChildAppModule'
},

It will raise this error :

ERROR in ./src/$$_gendir lazy
Module not found: Error: Can't resolve '/Users/myuser/Projects/web-app
/src/node_modules/@mine/child/src/app/child-app.module.module.ngfact
ory.ts' in '/Users/myuser/Projects/web-app/src/$$_gendir'
 @ ./src/$$_gendir lazy
 @ ./~/@angular/core/@angular/core.es5.js
 @ ./src/main.browser.ts
 @ multi ./src/main.browser.ts webpack-hot-middleware/client?path=/__webpa
ck_hmr&timeout=2000&reload=true&noInfo=true

I am using webpack 2 and ngtools/webpack to compiling my project

Body:
Lazy loading module from node_modules with JIT is working fine but Lazy loading with AOT is not working

github.com/angular/angular-cli/issues/5986

the best solution that I found is creating a symlink from src/app/something to node_modules/something

ln -s source destination

and it is working fine :)


问:
Oracle data not loading after POSITION(10)
i have been trying to load some data from a csv file based on certain conditions and i am restricted by the use of "OR" control in when clause (Oracle ctl)
the data loads for the first 11 conditions but does not loads any data after the first 11 condition

following is the code sample

```<code>     create table t1 (
     c1 varchar(10),
     c2 varchar(10),
     c3 varchar(10)
     )
</code>```

----------dataloader-----------

```<code>     options(errors=20000)
     LOAD DATA
     INFILE 'D:\Scripts\abc.csv'
     BADFILE 'D:\Scripts\abc.BAD'
     DISCARDFILE 'D:\Scripts\abc.DIS'
     DISCARDMAX 20000
     insert
     INTO TABLE t1

     when c1='James'

     FIELDS TERMINATED BY "," optionally enclosed by '"'

     Trailing NULLCOLS
     (
     c1,

     c2,

     c3
     )

     INTO TABLE t1

     when c1='John'

     FIELDS TERMINATED BY "," optionally enclosed by '"'

     Trailing NULLCOLS
     (
     c1 POSITION(1),

     c2,

     c3
     )

     INTO TABLE t1

     when c1='Sam'

     FIELDS TERMINATED BY "," optionally enclosed by '"'

     Trailing NULLCOLS
     (
     c1 POSITION(2),

     c2,

     c3
     )
     .
     .
     .
     INTO TABLE t1

     when c1='Mark'

     FIELDS TERMINATED BY "," optionally enclosed by '"'
     Trailing NULLCOLS
     (
     c1 POSITION(12),

     c2,

     c3

     )
</code>```

--------------dataloader execution-----

```<code>     sqlldr scott/tiger direct=true control='filepath'
</code>```

答: for executing each and every condition we need to place POSITION(1) till POSITION(9) tag for each and every condition. otherwise the ctl file doesnot reads the tagging and ignores the condition</p>

Body:
i have been trying to load some data from a csv file based on certain conditions and i am restricted by the use of "OR" control in when clause (Oracle ctl)
the data loads for the first 11 conditions but does not loads any data after the first 11 condition

following is the code sample

     create table t1 (
     c1 varchar(10),
     c2 varchar(10),
     c3 varchar(10)
     )

----------dataloader-----------

     options(errors=20000)
     LOAD DATA
     INFILE 'D:\Scripts\abc.csv'
     BADFILE 'D:\Scripts\abc.BAD'
     DISCARDFILE 'D:\Scripts\abc.DIS'
     DISCARDMAX 20000
     insert
     INTO TABLE t1

     when c1='James'

     FIELDS TERMINATED BY "," optionally enclosed by '"'

     Trailing NULLCOLS
     (
     c1,

     c2,

     c3
     )

     INTO TABLE t1

     when c1='John'

     FIELDS TERMINATED BY "," optionally enclosed by '"'

     Trailing NULLCOLS
     (
     c1 POSITION(1),

     c2,

     c3
     )

     INTO TABLE t1

     when c1='Sam'

     FIELDS TERMINATED BY "," optionally enclosed by '"'

     Trailing NULLCOLS
     (
     c1 POSITION(2),

     c2,

     c3
     )
     .
     .
     .
     INTO TABLE t1

     when c1='Mark'

     FIELDS TERMINATED BY "," optionally enclosed by '"'
     Trailing NULLCOLS
     (
     c1 POSITION(12),

     c2,

     c3

     )

--------------dataloader execution-----

     sqlldr scott/tiger direct=true control='filepath'


问:
Joomla "online-order" component for Joomla
Somebody can help me in finding an "online - ordering" component for joomla .
That can contain the following function :

Possibility of  creating  Form with pages  like RS!Form

Uploading  Files

Supporting Payment Gateways like  PayPal , MasterCard , WebMoney , YandexMoney ,Money Bookers , Google Checkout ... more )

Saving data in database. A friendly control panel  where admin can check statistics , income and expenditure, including offline transactions, and report on the data .   A good example , for what I'm looking , is this component http://www.nbill.co.uk/ , but is to expensive and complicated .

I'll be happy fore some links or advices :) .
Thank a Lot ! for all who are trying to help me ! And sorry for my bad English :-)

答: I would use virtue mart for a fully customizable component solution that's open and has lots of support. However you could just use a form that will post the url/title to the page when processing the other data as a non-payment solution (I think chrono forms does this and is free). I use breezing form for an online ordering system that does not require payment, just ordering. </p>


问:
Use of sizeof operator in C
I wrote a code to print size of different data types in C .

```<code>#include<stdio.h>
int main()
{
     printf("%d", sizeof(int));//size of integer
     printf("%d", sizeof(float));
     printf("%d", sizeof(double));
     printf("%d", sizeof(char));
}
</code>```

This does not work , but if I replace %d with %ld, it works. I did not understand why I have to take long int to print a small range number.

答:
sizeof has the return type size_t.  From the Standard,

6.5.3.4  The sizeof and _Alignof operators
```

5 The  value  of  the  result  of  both  operators  is
  implementation-deﬁned,  and  its  type  (an unsigned integer type) is
  size_t, deﬁned in <stddef.h> (and other headers).

size_t is implementation-defined.  In my linux, size_t is defined as __SIZE_TYPE__. On this topic, one can find details here.

In your case, it happens that size_t is implemented as a long , longer than int.

Title: Use of sizeof operator in C

Body:
I wrote a code to print size of different data types in C .

#include<stdio.h>
int main()
{
     printf("%d", sizeof(int));//size of integer
     printf("%d", sizeof(float));
     printf("%d", sizeof(double));
     printf("%d", sizeof(char));
}

This does not work , but if I replace %d with %ld, it works. I did not understand why I have to take long int to print a small range number.

Body:
sizeof has the return type size_t.  From the Standard,

6.5.3.4  The sizeof and _Alignof operators

5 The  value  of  the  result  of  both  operators  is
  implementation-deﬁned,  and  its  type  (an unsigned integer type) is
  size_t, deﬁned in <stddef.h> (and other headers).

size_t is implementation-defined.  In my linux, size_t is defined as __SIZE_TYPE__. On this topic, one can find details here.

In your case, it happens that size_t is implemented as a long , longer than int.


问:
How to send data from Arduino-uno using Bluetooth module HC-05 and read it in Android?
I am able to send data from my Android phone to my Arduino Uno using the HC-05 module. I also want to send data from the Arduino to my Android phone and I'm unable to do that.

Question: I will send a number from 0-9 using my android app to my Arduino Uno, the Arduino will send back the same number to my app, in words. For now, I am able to send numbers/letters to my Arduino from my app. I want help with the second part of the problem.

This is, in fact, a perfect duplicate of this question Android - receive bluetooth data from Arduino, but, unfortunately, this remains unanswered.

答:
Seems that you got the connection working fine:

In Arduino you need to use btSerial.readStringUntil('#')

You can change # with any character you want.

Then in Android append '#' to any string you're sending.

Also replace btSerial with your Bluetooth serial object


问:
Why does the original list change?
Running this:

```<code>a = [[1], [2]]
for i in a:
    i *= 2
print(a)
</code>```

Gives

```<code>[[1, 1], [2, 2]]
</code>```

I would expect to get the original list, as happens here:

```<code>a = [1, 2]
for i in a:
    i *= 2
print(a)
</code>```

Which gives:

```<code>[1, 2]
</code>```

Why is the list in the first example being modified?

答:
You are using augmented assignment statements. These operate on the object named on the left-hand side, giving that object the opportunity to update in-place:

An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once. Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.

(bold emphasis mine).

This is achieved by letting objects implement __i[op]__ methods, for =* that's the __imul__ hook:

These methods are called to implement the augmented arithmetic assignments (+=, -=, *=, @=, /=, //=, %=, **=, <<=, >>=, &=, ^=, |=). These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self).

Using *= on a list multiplies that list object and returns the same list object (self) to be 'assigned' back to the same name.

Integers on the other hand are immutable objects. Arithmetic operations on integers return new integer objects, so int objects do not even implement the __imul__ hook; Python has to fall back to executing i = i * 3 in that case.

So for the first example, the code:

```<code>a = [[1], [2]]
for i in a:
    i *= 2
</code>```

really does this (with the loop unrolled for illustration purposes):

```<code>a = [[1], [2]]
i = a[0].__imul__(2)  # a[0] is altered in-place
i = a[1].__imul__(2)  # a[1] is altered in-place
</code>```

where the list.__imul__ method applies the change to the list object itself, and returns the reference to the list object.

For integers, this is executed instead:

```<code>a = [1, 2]
i = a[0] * 2  # a[0] is not affected
i = a[1] * 2  # a[1] is not affected
</code>```

So now the new integer objects are assigned to i, which is independent from a.

Title: Why does the original list change?

Body:
Running this:

a = [[1], [2]]
for i in a:
    i *= 2
print(a)

Gives

[[1, 1], [2, 2]]

I would expect to get the original list, as happens here:

a = [1, 2]
for i in a:
    i *= 2
print(a)

Which gives:

[1, 2]

Why is the list in the first example being modified?

Body:
You are using augmented assignment statements. These operate on the object named on the left-hand side, giving that object the opportunity to update in-place:

An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once. Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.

(bold emphasis mine).

This is achieved by letting objects implement __i[op]__ methods, for =* that's the __imul__ hook:

These methods are called to implement the augmented arithmetic assignments (+=, -=, *=, @=, /=, //=, %=, **=, <<=, >>=, &=, ^=, |=). These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self).

Using *= on a list multiplies that list object and returns the same list object (self) to be 'assigned' back to the same name.

Integers on the other hand are immutable objects. Arithmetic operations on integers return new integer objects, so int objects do not even implement the __imul__ hook; Python has to fall back to executing i = i * 3 in that case.

So for the first example, the code:

a = [[1], [2]]
for i in a:
    i *= 2

really does this (with the loop unrolled for illustration purposes):

a = [[1], [2]]
i = a[0].__imul__(2)  # a[0] is altered in-place
i = a[1].__imul__(2)  # a[1] is altered in-place

where the list.__imul__ method applies the change to the list object itself, and returns the reference to the list object.

For integers, this is executed instead:

a = [1, 2]
i = a[0] * 2  # a[0] is not affected
i = a[1] * 2  # a[1] is not affected

So now the new integer objects are assigned to i, which is independent from a.


问:
java synchronized on object vs synchronized on this
i want to write own simple semaphore and done it as follows:

```<code>class Semaphore {
    private boolean done;
    private final Object lock = new Object();

    public Semaphore(boolean done){ this.done = done;}

    public void acquire() throws InterruptedException {
        synchronized (lock) {
            while (!done)
                lock.wait();

            done = false;
        }
    }

    public void release() {
        synchronized (lock) {
            done = true;
            lock.notify();
        }
    }
}
</code>```

it works fine. But if i replace synchronized (lock) with synchronize (this) it begins to throw IllegalMonitorStateException. Why so?

答:
As @Alexei Kaigorodov mentioned in comment, when you replace synchronized (lock) with synchronize (this). Then, you need to also replace lock to this in your code.

As this indicate to current object which is different than lock object.

Now, you replaced synchronized (lock) with synchronize (this) which means now you are trying to acquire lock on current object but you were waiting on object of Object class.

This works absolutely fine :

```<code>public void acquire() throws InterruptedException {
    synchronized (this) {
        while (!done)
            this.wait();

        done = false;
    }
}

public void release() {
    synchronized (this) {
        done = true;
        this.notify();
    }
}
</code>```

Body:
i want to write own simple semaphore and done it as follows:

class Semaphore {
    private boolean done;
    private final Object lock = new Object();

    public Semaphore(boolean done){ this.done = done;}

    public void acquire() throws InterruptedException {
        synchronized (lock) {
            while (!done)
                lock.wait();

            done = false;
        }
    }

    public void release() {
        synchronized (lock) {
            done = true;
            lock.notify();
        }
    }
}

it works fine. But if i replace synchronized (lock) with synchronize (this) it begins to throw IllegalMonitorStateException. Why so?

Body:
As @Alexei Kaigorodov mentioned in comment, when you replace synchronized (lock) with synchronize (this). Then, you need to also replace lock to this in your code.

As this indicate to current object which is different than lock object.

Now, you replaced synchronized (lock) with synchronize (this) which means now you are trying to acquire lock on current object but you were waiting on object of Object class.

This works absolutely fine :

public void acquire() throws InterruptedException {
    synchronized (this) {
        while (!done)
            this.wait();

        done = false;
    }
}

public void release() {
    synchronized (this) {
        done = true;
        this.notify();
    }
}