问:
how to get only the first name of a list in alphabetical order?
I have a list with students and want to get only the first student from the alphabet.

My following Code gives me all current students in alphabetical order, but I only want the first one.

```<code>for (char letter = 'A'; letter <= 'Z'; letter++)
{
    Console.WriteLine(letter);

    foreach (var studentName in _students)
    {
        if (studentName)
        {
            Console.WriteLine(studentName.Lastname + " " + studentName.Firstname);
        }
    }
}
</code>```

答:
If you _students is a List<String>, this will return the first one in the sorted list.

```<code>student1 = _students.sort()[0]
</code>```

If you want to sort by property List<Student> (Sort by FirstName):

```<code>List<Student> sortedList = _students.OrderBy(s=>s.FirstName).ToList();
</code>```

Now ypu can get the first one by _sortedList[0].

You don´t need alphabetical loop anymore.
This snippet will print all students in alphabetical order:

```<code>_students = _students.OrderBy(s=>s.FirstName).ToList();  // sorting and saving
_students.ForEach(s => Console.WriteLine(s.FirstName + " " + s.LastName)); // printing each element
</code>```

If you want the first Student for each letter you can filter like this:

```<code>_students.Where(s => searchList.Any(s=>s.StartsWith(letter)))[0];
</code>```

Write this into your letter-loop and every first one gets returned. Be careful null or Exception can be thrown if there is no result for [0].

Body:
I have a list with students and want to get only the first student from the alphabet.

My following Code gives me all current students in alphabetical order, but I only want the first one.

for (char letter = 'A'; letter <= 'Z'; letter++)
{
    Console.WriteLine(letter);

    foreach (var studentName in _students)
    {
        if (studentName)
        {
            Console.WriteLine(studentName.Lastname + " " + studentName.Firstname);
        }
    }
}

Body:
If you _students is a List<String>, this will return the first one in the sorted list.

student1 = _students.sort()[0]

If you want to sort by property List<Student> (Sort by FirstName):

List<Student> sortedList = _students.OrderBy(s=>s.FirstName).ToList();

Now ypu can get the first one by _sortedList[0].

You don´t need alphabetical loop anymore.
This snippet will print all students in alphabetical order:

_students = _students.OrderBy(s=>s.FirstName).ToList();  // sorting and saving
_students.ForEach(s => Console.WriteLine(s.FirstName + " " + s.LastName)); // printing each element

If you want the first Student for each letter you can filter like this:

_students.Where(s => searchList.Any(s=>s.StartsWith(letter)))[0];

Write this into your letter-loop and every first one gets returned. Be careful null or Exception can be thrown if there is no result for [0].


来源: stackexchange

问:
Rollback under condition in MariaDB
I have a transaction which reduces the variable with amount of money in loop, if the variable with money is below 0, the money amount should return to the value before transaction. How can I appropriately use rollback in MariaDB in this case?

---edit

I have something like that, and it doesn't work, check out the lines in if(budget<0) because if the money is below 0 and some, but not all of them, iterations were made and saved to the temp table, the table shows them

```<code>BEGIN
    DECLARE temppesel text;
    DECLARE tempsalary int;
    DECLARE budget int DEFAULT cash;
    DECLARE done bool DEFAULT false;
    DECLARE occ CURSOR FOR (SELECT pesel, pensja FROM pracownicy where zawod=occupation);
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = true;

    START TRANSACTION;
        DROP TABLE IF EXISTS temp;
        CREATE TABLE temp ( Result text );
        OPEN occ;
            occ : LOOP
                FETCH occ INTO temppesel, tempsalary;
                SET budget = budget - tempsalary;

                IF(done) THEN
                    LEAVE occ;
                END IF;

                IF(budget<0) THEN
                    ROLLBACK;
                    LEAVE occ;
                END IF;

                INSERT INTO temp VALUES (concat('********',substr(temppesel,9,3), ', wyplacono'));
            END LOOP;
        CLOSE occ;

        SELECT * FROM temp;
        DROP TABLE temp;
    COMMIT;
END
</code>```

答:
I believe that the CREATE TABLE statements are causing the transaction to be committed. Here is a list of commands that cause an implicit COMMIT.

As the aforementioned link describes, you can either move the START TRANSACTION statement after the DROP and CREATE commands or use the CREATE TEMPORARY TABLE syntax to create a temporary table:

```<code>CREATE TEMPORARY TABLE temp ( Result text );
</code>```

ContentLicense: CC BY-SA 3.0

Title: Rollback under condition in MariaDB

Body:
I have a transaction which reduces the variable with amount of money in loop, if the variable with money is below 0, the money amount should return to the value before transaction. How can I appropriately use rollback in MariaDB in this case?

---edit

I have something like that, and it doesn't work, check out the lines in if(budget<0) because if the money is below 0 and some, but not all of them, iterations were made and saved to the temp table, the table shows them

BEGIN
    DECLARE temppesel text;
    DECLARE tempsalary int;
    DECLARE budget int DEFAULT cash;
    DECLARE done bool DEFAULT false;
    DECLARE occ CURSOR FOR (SELECT pesel, pensja FROM pracownicy where zawod=occupation);
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = true;

    START TRANSACTION;
        DROP TABLE IF EXISTS temp;
        CREATE TABLE temp ( Result text );
        OPEN occ;
            occ : LOOP
                FETCH occ INTO temppesel, tempsalary;
                SET budget = budget - tempsalary;

                IF(done) THEN
                    LEAVE occ;
                END IF;

                IF(budget<0) THEN
                    ROLLBACK;
                    LEAVE occ;
                END IF;

                INSERT INTO temp VALUES (concat('********',substr(temppesel,9,3), ', wyplacono'));
            END LOOP;
        CLOSE occ;

        SELECT * FROM temp;
        DROP TABLE temp;
    COMMIT;
END

Body:
I believe that the CREATE TABLE statements are causing the transaction to be committed. Here is a list of commands that cause an implicit COMMIT.

As the aforementioned link describes, you can either move the START TRANSACTION statement after the DROP and CREATE commands or use the CREATE TEMPORARY TABLE syntax to create a temporary table:

CREATE TEMPORARY TABLE temp ( Result text );


问:
the magic of assigning URL to a.href
On Chrome Developer console, I typed the following codes:

```<code>> a = document.createElement('a');
> a.href = "http://localhost:4200/setting?q=123&b=aa";
</code>```

Then other properties of this element also owned the according value, for example:

```<code>> a.search
"?q=123&b=aa"
> a.hostname
"localhost"
> a.port
"4200"
</code>```

I was confused with the results. I just assigned url to href propety.

Why other properties could have their values at the same time?

What's the magic behind the phenomenon?

Could anyone explain this for me?

答:
What's the magic behind the phenomenon?

No “magic”, but simple specification.

https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement:

[HTMLAnchorElement] inherits properties from its parent, HTMLElement, and implements those from HTMLHyperlinkElementUtils.

The HTMLHyperlinkElementUtils mixin defines utility methods and properties to work with HTMLAnchorElement and HTMLAreaElement. These utilities allow to deal with common features like URLs.

Title: the magic of assigning URL to a.href

Body:
On Chrome Developer console, I typed the following codes:

> a = document.createElement('a');
> a.href = "http://localhost:4200/setting?q=123&b=aa";

Then other properties of this element also owned the according value, for example:

> a.search
"?q=123&b=aa"
> a.hostname
"localhost"
> a.port
"4200"

I was confused with the results. I just assigned url to href propety.

Why other properties could have their values at the same time?

What's the magic behind the phenomenon?

Could anyone explain this for me?


问:
Error when I try to install npm on Ubuntu 17.04
I'm trying to install npm on Ubuntu 17.04 but I'm not getting it. I've installed nodejs and nodejs-legacy and when I try to install npm, a message appears saying that npm depends on node-gyp (>= 0.10.9) and won't be installed. If a try to install node-gyp, another dependency appears and successively. Does anybody know how to fix it?</p>

答:
if you use apt-get for install nodejs you can switch version easily:

```<code>$ sudo apt-get install npm # install npm
$ sudo npm install -g  n  # install n nodejs version switcher as global package.
$ sudo n stable # install latest stable version.
</code>```

install more version: [exmp: 9.1.0]

```<code>$ sudo n 9.1.0
</code>```

reference

Body:
if you use apt-get for install nodejs you can switch version easily:

$ sudo apt-get install npm # install npm
$ sudo npm install -g  n  # install n nodejs version switcher as global package.
$ sudo n stable # install latest stable version.

install more version: [exmp: 9.1.0]

$ sudo n 9.1.0

reference


问:
android - Execution failed for task ':app:compileDebugJavaWithJavac'
New to Android Studio + Gradle.

I'm trying to run my app from the command line using:

```<code>gradlew installDebug
</code>```

The app gets installed on my device only when I execute that command when Studio just got opened and do that initial syncing/building thing.

Whenever I modified my code, and try to run that command again, the build fails and shows this error:

```<code>Execution failed for task ':app:compileDebugJavaWithJavac'
> Could not find tools.jar
</code>```

How do I solve this problem? Thanks in advance.

答: I faced the same issue.I was looking for several hours on stack overflow and tried all of the way they said but was not able to solve the problem.Then I found that problem was in my project folder name.I just rename the folder name and everything worked fine.

Body:
New to Android Studio + Gradle.

I'm trying to run my app from the command line using:

gradlew installDebug

The app gets installed on my device only when I execute that command when Studio just got opened and do that initial syncing/building thing.

Whenever I modified my code, and try to run that command again, the build fails and shows this error:

Execution failed for task ':app:compileDebugJavaWithJavac'
> Could not find tools.jar

How do I solve this problem? Thanks in advance.


问:
Visual Studio 2008 Cut and Paste Won't Overwrite
When I paste over selected text, the contents of the clipboard are appended to the existing text instead of overwriting it. I can't seem to find the setting to change this behavior!</p>

答:
If you go to Tools -> Options -> Keyboard (under Environment) is your mapping scheme set to emacs?

If it is, see here.

ContentLicense: CC BY-SA 2.5


问:
Elixir/Phoenix change livereload endpoint
I am serving an app behind nginx proxy, and want to preserve phoenix live reload features. The issue is with:

```<code><iframe src="/phoenix/live_reload/frame" style="display: none;"></iframe>
</code>```

That is added to the main html. I need to change it to:

```<code><iframe src="/new_url/phoenix/live_reload/frame" style="display: none;"></iframe>
</code>```

I have checked endpoint, and tried to change like this:

```<code>if code_reloading? do
  socket "/new_url/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
  plug Phoenix.LiveReloader
  plug Phoenix.CodeReloader
end
</code>```

But it doesn't seem to change the iframe url. Then I found livereloader.ex in my deps, which I guess allows to set the url with config.

Can someone show how should I set the url for it? Thanks in advance.

Updated the config/dev.exs, yet doesn't seem to work.As pointed out by @PatNowak,the url seems to set host and port, but not the url.

Last:
I believe that setting url, as suggested below, changes the socket url, but not actually the iframe src. I'll remove proxy for now to keep the live reload.

答: You found a place where config[:url] is set, but you missed a comment in the live_reloader.ex. Please check that line. There's presented how this url should looks like.

Body:
I am serving an app behind nginx proxy, and want to preserve phoenix live reload features. The issue is with:

That is added to the main html. I need to change it to:

I have checked endpoint, and tried to change like this:

if code_reloading? do
  socket "/new_url/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
  plug Phoenix.LiveReloader
  plug Phoenix.CodeReloader
end

But it doesn't seem to change the iframe url. Then I found livereloader.ex in my deps, which I guess allows to set the url with config.

Can someone show how should I set the url for it? Thanks in advance.

Updated the config/dev.exs, yet doesn't seem to work.As pointed out by @PatNowak,the url seems to set host and port, but not the url.

Last:
I believe that setting url, as suggested below, changes the socket url, but not actually the iframe src. I'll remove proxy for now to keep the live reload.


答:
You can use Linq to create a sorted enumerable:

```<code>var sortedStudents = _students.OrderBy(s => s.LastName, StringComparer.InvariantCultureIgnoreCase).ThenBy(s => s.FirstName, StringComparer.InvariantCultureIgnoreCase);
</code>```

This will sort the students A-Z ignoring diacritics.

Then you can simply iterate through it to print all:

```<code>foreach (var student in sortedStudents)
{
    Console.WriteLine(student.LastName + " " + student.FirstName);
}
</code>```

Or just take the first one:

```<code>var firstStudent = sortedStudents.FirstOrDefault(); // returns the first student or null.
</code>```

And finally, all in one statement:

```<code>var firstStudent  = _students.OrderBy(s => s.LastName, StringComparer.InvariantCultureIgnoreCase).ThenBy(s => s.FirstName, StringComparer.InvariantCultureIgnoreCase).FirstOrDefault();
</code>```

Title: how to get only the first name of a list in alphabetical order?

Body:
You can use Linq to create a sorted enumerable:

var sortedStudents = _students.OrderBy(s => s.LastName, StringComparer.InvariantCultureIgnoreCase).ThenBy(s => s.FirstName, StringComparer.InvariantCultureIgnoreCase);

This will sort the students A-Z ignoring diacritics.

Then you can simply iterate through it to print all:

foreach (var student in sortedStudents)
{
    Console.WriteLine(student.LastName + " " + student.FirstName);
}

Or just take the first one:

var firstStudent = sortedStudents.FirstOrDefault(); // returns the first student or null.

And finally, all in one statement:

var firstStudent  = _students.OrderBy(s => s.LastName, StringComparer.InvariantCultureIgnoreCase).ThenBy(s => s.FirstName, StringComparer.InvariantCultureIgnoreCase).FirstOrDefault();


问:
How to append element with angular material2 style?
I'm making a template that if button is clicked then append elements that I want to.
I could append it exactly with following codes but I couldn't add style, angular-material2.
If you have any idea, leave your tip, please.

make-template.component.ts

```<code>@ViewChild('tContent') content: ElementRef;

  addTbody() {
    let content = document.getElementById('tContent');
    console.log(this.content.nativeElement);
    this.renderer.invokeElementMethod(this.content.nativeElement, 'insertAdjacentHTML', [`beforeend`,
  `
  <tr>
    <td>
      <input type="file">
    </td>
    <td>
      <input type="file">
    </td>
  </tr>
  <tr>
    <td>
      <mat-input-container>
        <input matInput placeholder="image Info" type="text">
      </mat-input-container>
    </td>
    <td>
      <mat-input-container>
        <input matInput placeholder="image Info" type="text">
      </mat-input-container>
    </td>
  </tr>
`]);
</code>```

}

make-template.component.html

```<code>...
<tbody #tContent>
          // add here
</tbody>
<button type="button" mat-raised-button color="primary" (click)="addTbody()">click here</button>
</code>```

答:
You can use dynamic component here to append it-

```<code>constructor(private compiler: Compiler, public vcRef: ViewContainerRef) { }

  @ViewChild('tContent')
  tContent: ViewContainerRef;
  cmpRef: any;

ngOnInit() {
  let dom = this.appendDom('<h1>Dynamic Component</h1>');
}

appendDom(template: string) {
     const html = template;
        if (!html) return;

        if (this.cmpRef) {
            this.cmpRef.destroy();
        }
        const compMetadata = new Component({
            template: html
        });

        let factory = this.createComponentFactory(this.compiler, compMetadata);
        const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);
        this.cmpRef = this.vcRef.createComponent(factory, this.vcRef.length, injector);
        const hostView = <EmbeddedViewRef<any>>this.cmpRef.hostView;
        return hostView.rootNodes[0];
}
</code>```

// createComponentFactory Method

```<code>createComponentFactory(compiler: Compiler, metadata: Component) {
    @Component(metadata)
    class DynamicComponent {

    };
    @NgModule({
        imports: [CommonModule],
        declarations: [DynamicComponent]
    })
    class DynamicHtmlModule { }
    let moduleWithComponentFactory = compiler.compileModuleAndAllComponentsSync(DynamicHtmlModule);
    return moduleWithComponentFactory.componentFactories.find(x => x.componentType === DynamicComponent);
}
</code>```

}

Plunker

Body:
I'm making a template that if button is clicked then append elements that I want to.
I could append it exactly with following codes but I couldn't add style, angular-material2.
If you have any idea, leave your tip, please.

make-template.component.ts

@ViewChild('tContent') content: ElementRef;

  addTbody() {
    let content = document.getElementById('tContent');
    console.log(this.content.nativeElement);
    this.renderer.invokeElementMethod(this.content.nativeElement, 'insertAdjacentHTML', [`beforeend`,
  `

      <input type="file">

      <input type="file">

      <mat-input-container>
        <input matInput placeholder="image Info" type="text">
      </mat-input-container>

      <mat-input-container>
        <input matInput placeholder="image Info" type="text">
      </mat-input-container>

`]);

}

make-template.component.html

...

          // add here

<button type="button" mat-raised-button color="primary" (click)="addTbody()">click here</button>

Body:
You can use dynamic component here to append it-

constructor(private compiler: Compiler, public vcRef: ViewContainerRef) { }

  @ViewChild('tContent')
  tContent: ViewContainerRef;
  cmpRef: any;

ngOnInit() {
  let dom = this.appendDom('<h1>Dynamic Component</h1>');
}

appendDom(template: string) {
     const html = template;
        if (!html) return;

        if (this.cmpRef) {
            this.cmpRef.destroy();
        }
        const compMetadata = new Component({
            template: html
        });

        let factory = this.createComponentFactory(this.compiler, compMetadata);
        const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);
        this.cmpRef = this.vcRef.createComponent(factory, this.vcRef.length, injector);
        const hostView = <EmbeddedViewRef<any>>this.cmpRef.hostView;
        return hostView.rootNodes[0];
}

// createComponentFactory Method

createComponentFactory(compiler: Compiler, metadata: Component) {
    @Component(metadata)
    class DynamicComponent {

    };
    @NgModule({
        imports: [CommonModule],
        declarations: [DynamicComponent]
    })
    class DynamicHtmlModule { }
    let moduleWithComponentFactory = compiler.compileModuleAndAllComponentsSync(DynamicHtmlModule);
    return moduleWithComponentFactory.componentFactories.find(x => x.componentType === DynamicComponent);
}

}

Plunker


问:
Multipel condition at SQL Case
I have 3 tables to join with:

```<code>ALERT_CASE_HEADER
 - alert_key
ALERT_ITEM
- entity_key
-status_id
-entity_name='Active Alert'
STATUSES
-name
-id
</code>```

Both alert tables use alert_key and entity_key to link. The summation of case only take place if both keys are same value and entity_name='Active Alert' for each of the available status name. And the id column in table STATUSES is linked to ALERT_ITEM.status_id

Can I do something like this? I tried to run the script but it seem very slow.

```<code>SELECT
  SUM(
    CASE
      WHEN s.name = 'Pending'
      AND ach.alert_key = ai.entity_key
      AND ai.entity_name = 'Active Alert'
      THEN 1
      ELSE 0
    END
  ) AS PENDING, SUM(
    CASE
      WHEN s.name = 'new'
      AND ach.alert_key = ai.entity_key
      AND ai.entity_name = 'Active Alert'
      THEN 1
      ELSE 0
    END
  ) AS NEW, SUM(
    CASE
      WHEN s.name = 'cancel'
      AND ach.alert_key = ai.entity_key
      AND ai.entity_name = 'Active Alert'
      THEN 1
      ELSE 0
    END
  ) AS CANCEL
FROM
  STATUSES s, ALERT_CASE_HEADER ach, ALERT_ITEM ai;
</code>```

(From an answer by the asker Nov 14 '17 at 9:53 that should have been an edit:)

The script i am using as per below, just focus on the 2 join statements.The second join is working but not the first one.

```<code> SELECT CUS.ORGUNIT_CODE AS ORGANIZATION_UNITS,
  SUM(
    CASE
      WHEN S.name = 'Pending' THEN 1 ELSE 0
    END
    ) AS PENDING_AUTOCLOSURE,
  SUM(
    CASE
      WHEN S.name = 'New' THEN 1 ELSE 0
    END
    ) AS NEW,
  SUM(
    CASE
      WHEN S.name = 'Under Investigation' THEN 1 ELSE 0
    END
  ) AS UNDER_INVESTIGATION,
  SUM(
    CASE
       WHEN S.Name = 'Escalated' THEN 1 ELSE 0
    END
  ) AS ESCALATED,
   SUM(
    CASE
       WHEN S.Name = 'Recommend True Positive' THEN 1 ELSE 0
    END
  ) AS RECOMMEND_TRUE_POSITIVE,
   SUM(
    CASE
       WHEN S.Name = 'Reopen Under Investigation' THEN 1 ELSE 0
    END
  ) AS REOPEN_UNDER_INVESTIGATION
FROM
  STATUSES S,CUSTOMERS CUS,ALERT_ITEM AI
  JOIN ALERT_ITEM AI ON S.ID = AI.STATUS_ID
  JOIN ALERT_CASE_HEADER ACH ON AI.ENTITY_KEY = ACH.ALERT_KEY
WHERE AI.ENTITY_NAME = 'Active Alert'
AND   AI.ORGUNIT_ID = CUS.ORGUNIT_ID
GROUP BY CUS.ORGUNIT_CODE;
</code>```

答:
You can use this :</p>

```<code>SELECT
  SUM(
    CASE
      WHEN s.name = 'Pending' THEN 1 ELSE 0
    END
    ) AS PENDING,
  SUM(
    CASE
      WHEN s.name = 'new' THEN 1 ELSE 0
    END
    ) AS NEW,
  SUM(
    CASE
      WHEN s.name = 'cancel' THEN 1 ELSE 0
    END
  ) AS CANCEL
FROM
  STATUSES s
  join ALERT_ITEM ai on s.id=ai.status_id
  join ALERT_CASE_HEADER ach on ai.entity_key=ach.alert_key
where ai.entity_name = 'Active Alert'
</code>```

ContentLicense: CC BY-SA 4.0

Title: Multipel condition at SQL Case

Body:
I have 3 tables to join with:

ALERT_CASE_HEADER
 - alert_key
ALERT_ITEM
- entity_key
-status_id
-entity_name='Active Alert'
STATUSES
-name
-id

Both alert tables use alert_key and entity_key to link. The summation of case only take place if both keys are same value and entity_name='Active Alert' for each of the available status name. And the id column in table STATUSES is linked to ALERT_ITEM.status_id

Can I do something like this? I tried to run the script but it seem very slow.

SELECT
  SUM(
    CASE
      WHEN s.name = 'Pending'
      AND ach.alert_key = ai.entity_key
      AND ai.entity_name = 'Active Alert'
      THEN 1
      ELSE 0
    END
  ) AS PENDING, SUM(
    CASE
      WHEN s.name = 'new'
      AND ach.alert_key = ai.entity_key
      AND ai.entity_name = 'Active Alert'
      THEN 1
      ELSE 0
    END
  ) AS NEW, SUM(
    CASE
      WHEN s.name = 'cancel'
      AND ach.alert_key = ai.entity_key
      AND ai.entity_name = 'Active Alert'
      THEN 1
      ELSE 0
    END
  ) AS CANCEL
FROM
  STATUSES s, ALERT_CASE_HEADER ach, ALERT_ITEM ai;

(From an answer by the asker Nov 14 '17 at 9:53 that should have been an edit:)

The script i am using as per below, just focus on the 2 join statements.The second join is working but not the first one.

 SELECT CUS.ORGUNIT_CODE AS ORGANIZATION_UNITS,
  SUM(
    CASE
      WHEN S.name = 'Pending' THEN 1 ELSE 0
    END
    ) AS PENDING_AUTOCLOSURE,
  SUM(
    CASE
      WHEN S.name = 'New' THEN 1 ELSE 0
    END
    ) AS NEW,
  SUM(
    CASE
      WHEN S.name = 'Under Investigation' THEN 1 ELSE 0
    END
  ) AS UNDER_INVESTIGATION,
  SUM(
    CASE
       WHEN S.Name = 'Escalated' THEN 1 ELSE 0
    END
  ) AS ESCALATED,
   SUM(
    CASE
       WHEN S.Name = 'Recommend True Positive' THEN 1 ELSE 0
    END
  ) AS RECOMMEND_TRUE_POSITIVE,
   SUM(
    CASE
       WHEN S.Name = 'Reopen Under Investigation' THEN 1 ELSE 0
    END
  ) AS REOPEN_UNDER_INVESTIGATION
FROM
  STATUSES S,CUSTOMERS CUS,ALERT_ITEM AI
  JOIN ALERT_ITEM AI ON S.ID = AI.STATUS_ID
  JOIN ALERT_CASE_HEADER ACH ON AI.ENTITY_KEY = ACH.ALERT_KEY
WHERE AI.ENTITY_NAME = 'Active Alert'
AND   AI.ORGUNIT_ID = CUS.ORGUNIT_ID
GROUP BY CUS.ORGUNIT_CODE;

Body:
You can use this :

SELECT
  SUM(
    CASE
      WHEN s.name = 'Pending' THEN 1 ELSE 0
    END
    ) AS PENDING,
  SUM(
    CASE
      WHEN s.name = 'new' THEN 1 ELSE 0
    END
    ) AS NEW,
  SUM(
    CASE
      WHEN s.name = 'cancel' THEN 1 ELSE 0
    END
  ) AS CANCEL
FROM
  STATUSES s
  join ALERT_ITEM ai on s.id=ai.status_id
  join ALERT_CASE_HEADER ach on ai.entity_key=ach.alert_key
where ai.entity_name = 'Active Alert'


问:
Error In fill in read.table in R
I am trying to import the data from the CSV file. The code I used is below

```<code>New <- read.table("New.csv", fill="TRUE")
</code>```

and below is the CSV file data:

```<code>Name    Sex Age Score   Aspirations
Rhea    F   18  98  Doctor
John    M   17  90  Engineer
Rads    F   21  87  Air Hostess
</code>```

The R console is sending me an error and I am not sure how to deal with this. I am a beginner in R.

Error in fill && length(col.names) > cols : invalid 'x' type in 'x &&
  y'

答:
Remove the quotation marks from TRUE, so it reads</p>

```<code>New <- read.table("New.csv", fill=TRUE)
</code>```

Title: Error In fill in read.table in R

Body:
I am trying to import the data from the CSV file. The code I used is below

New <- read.table("New.csv", fill="TRUE")

and below is the CSV file data:

Name    Sex Age Score   Aspirations
Rhea    F   18  98  Doctor
John    M   17  90  Engineer
Rads    F   21  87  Air Hostess

The R console is sending me an error and I am not sure how to deal with this. I am a beginner in R.

Error in fill && length(col.names) > cols : invalid 'x' type in 'x &&
  y'

Body:
Remove the quotation marks from TRUE, so it reads

New <- read.table("New.csv", fill=TRUE)


问:
Sum the number of firms in one year
Suppose I have a dataframe as follows:

```<code>dt=structure(list(id = c(1L, 1L, 1L, 1L, 2L, 3L, 3L, 3L, 4L, 4L,
4L, 4L, 5L, 5L, 6L, 6L), year = c(2001L, 2002L, 2003L, 2004L,
2002L, 2002L, 2003L, 2004L, 2002L, 2003L, 2004L, 2005L, 2001L,
2002L, 2001L, 2002L)), .Names = c("firm", "year"), row.names = c(NA,
-16L), class = "data.frame")

dt
 firm year
1   1 2001
2   1 2002
3   1 2003
4   1 2004
5   2 2002
6   3 2002
7   3 2003
8   3 2004
9   4 2002
10  4 2003
11  4 2004
12  4 2005
13  5 2001
14  5 2002
15  6 2001
16  6 2002
</code>```

Now, I hope to sum the number of firms which have exited the market in one year. For example, I want a table like this:

```<code> resulttable
     All 2001 2002 2003 2004 2005
2001   3    0    2    0    1    0
2002   3    0    1    0    1    1
</code>```

The first row of resulttable means that 3 firms entered the market in year 2001 and 2 firms exited in 2003, 1 firm exited in year 2004. Thanks!

答:
Here is a slightly different approach using data.table which creates the totals before reshaping from long to wide format:

```<code>library(data.table)
setDT(dt)[, .(entry = min(year), exit = max(year)), by = firm][, All := .N, by = entry][
  , dcast(.SD, entry + All ~ exit, length, value.var = "firm")]
</code>```

```<code>   entry All 2002 2004 2005
1:  2001   3    2    1    0
2:  2002   3    1    1    1
</code>```

This is already conveying all essential results which the OP verbally described in the question.

However, OP's expected result includes columns for the years 2001 and 2003 although they contain only 0. If it is required to show years without entries or exits, this can be accomplished by completing the missing years before computing the totals All and reshaping:

```<code>setDT(dt)[, .(entry = min(year), exit = max(year)), by = firm][
  CJ(entry = dt$year, exit = dt$year, unique = TRUE), on = .(entry, exit)][
    , All := sum(!is.na(firm)), by = entry][][
      , dcast(.SD, entry + All ~ exit, function(x) (sum(!is.na(x))), value.var = "firm")]
</code>```

```<code>   entry All 2001 2002 2003 2004 2005
1:  2001   3    0    2    0    1    0
2:  2002   3    0    1    0    1    1
3:  2003   0    0    0    0    0    0
4:  2004   0    0    0    0    0    0
5:  2005   0    0    0    0    0    0
</code>```

The missing years are completed by joining with a table of all available combinations of year which is created by a cross join CJ(). The completion introduces a lot of NA values in firm, therefore length(firm) has to be replaced by sum(!is.na(firm)) as aggregation function.

The extension of the resulting wide format can be controlled by the range of years given in CJ(). E.g., the empty entry years 2003 to 2005 can be dropped by

```<code>setDT(dt)[, .(entry = min(year), exit = max(year)), by = firm][
  CJ(entry = min(entry):max(entry), exit = dt$year, unique = TRUE), on = .(entry, exit)][
    , All := sum(!is.na(firm)), by = entry][][
      , dcast(.SD, entry + All ~ exit, function(x) (sum(!is.na(x))), value.var = "firm")]
</code>```

```<code>   entry All 2001 2002 2003 2004 2005
1:  2001   3    0    2    0    1    0
2:  2002   3    0    1    0    1    1
</code>```

which reproduces exactly OP's expected resulttable.

Or, drop also the  empty exit years 2001 and 2005 by

```<code>setDT(dt)[, .(entry = min(year), exit = max(year)), by = firm][
  CJ(entry = min(entry):max(entry), exit = min(exit):max(exit)), on = .(entry, exit)][
    , All := sum(!is.na(firm)), by = entry][][
      , dcast(.SD, entry + All ~ exit, function(x) (sum(!is.na(x))), value.var = "firm")]
</code>```

```<code>   entry All 2002 2003 2004 2005
1:  2001   3    2    0    1    0
2:  2002   3    1    0    1    1
</code>```

Title: Sum the number of firms in one year

Body:
Suppose I have a dataframe as follows:

dt=structure(list(id = c(1L, 1L, 1L, 1L, 2L, 3L, 3L, 3L, 4L, 4L,
4L, 4L, 5L, 5L, 6L, 6L), year = c(2001L, 2002L, 2003L, 2004L,
2002L, 2002L, 2003L, 2004L, 2002L, 2003L, 2004L, 2005L, 2001L,
2002L, 2001L, 2002L)), .Names = c("firm", "year"), row.names = c(NA,
-16L), class = "data.frame")

dt
 firm year
1   1 2001
2   1 2002
3   1 2003
4   1 2004
5   2 2002
6   3 2002
7   3 2003
8   3 2004
9   4 2002
10  4 2003
11  4 2004
12  4 2005
13  5 2001
14  5 2002
15  6 2001
16  6 2002

Now, I hope to sum the number of firms which have exited the market in one year. For example, I want a table like this:

 resulttable
     All 2001 2002 2003 2004 2005
2001   3    0    2    0    1    0
2002   3    0    1    0    1    1

The first row of resulttable means that 3 firms entered the market in year 2001 and 2 firms exited in 2003, 1 firm exited in year 2004. Thanks!

Body:
Here is a slightly different approach using data.table which creates the totals before reshaping from long to wide format:

library(data.table)
setDT(dt)[, .(entry = min(year), exit = max(year)), by = firm][, All := .N, by = entry][
  , dcast(.SD, entry + All ~ exit, length, value.var = "firm")]

   entry All 2002 2004 2005
1:  2001   3    2    1    0
2:  2002   3    1    1    1

This is already conveying all essential results which the OP verbally described in the question.

However, OP's expected result includes columns for the years 2001 and 2003 although they contain only 0. If it is required to show years without entries or exits, this can be accomplished by completing the missing years before computing the totals All and reshaping:

setDT(dt)[, .(entry = min(year), exit = max(year)), by = firm][
  CJ(entry = dt$year, exit = dt$year, unique = TRUE), on = .(entry, exit)][
    , All := sum(!is.na(firm)), by = entry][][
      , dcast(.SD, entry + All ~ exit, function(x) (sum(!is.na(x))), value.var = "firm")]

   entry All 2001 2002 2003 2004 2005
1:  2001   3    0    2    0    1    0
2:  2002   3    0    1    0    1    1
3:  2003   0    0    0    0    0    0
4:  2004   0    0    0    0    0    0
5:  2005   0    0    0    0    0    0

The missing years are completed by joining with a table of all available combinations of year which is created by a cross join CJ(). The completion introduces a lot of NA values in firm, therefore length(firm) has to be replaced by sum(!is.na(firm)) as aggregation function.

The extension of the resulting wide format can be controlled by the range of years given in CJ(). E.g., the empty entry years 2003 to 2005 can be dropped by

setDT(dt)[, .(entry = min(year), exit = max(year)), by = firm][
  CJ(entry = min(entry):max(entry), exit = dt$year, unique = TRUE), on = .(entry, exit)][
    , All := sum(!is.na(firm)), by = entry][][
      , dcast(.SD, entry + All ~ exit, function(x) (sum(!is.na(x))), value.var = "firm")]

   entry All 2001 2002 2003 2004 2005
1:  2001   3    0    2    0    1    0
2:  2002   3    0    1    0    1    1

which reproduces exactly OP's expected resulttable.

Or, drop also the  empty exit years 2001 and 2005 by

setDT(dt)[, .(entry = min(year), exit = max(year)), by = firm][
  CJ(entry = min(entry):max(entry), exit = min(exit):max(exit)), on = .(entry, exit)][
    , All := sum(!is.na(firm)), by = entry][][
      , dcast(.SD, entry + All ~ exit, function(x) (sum(!is.na(x))), value.var = "firm")]

   entry All 2002 2003 2004 2005
1:  2001   3    2    0    1    0
2:  2002   3    1    0    1    1


问:
Visual Studio 2012 change web browser
If I click control-click a hyperlink in the text editor, it opens the URL in a new Visual Studio tab. I would rather the link open outside Visual Studio in my system's default web browser (happens to be Google Chrome). How can I arrange this?

I'm talking about hyperlinks in code comments.

I am using Visual Studio 2012. I found a similar question dated 2009, however the accepted answer (a macro) doesn't work in Visual Studio 2012.

答: VS 2012  -->> File -->> Browse With -- >> Select Browser -->> Click on "set Default" Button -->> Now Click "Browse" Button</p>

Title: Visual Studio 2012 change web browser


问:
check if jquery has been loaded, then load it if false
Does anyone know how to check if jquery has been loaded (with javascript) then load it if it hasnt been loaded.

something like

```<code>if(!jQuery) {
    //load jquery file
}
</code>```

答:
```<code>var f = ()=>{
    if (!window.jQuery) {
        var e = document.createElement('script');
        e.src = "https://code.jquery.com/jquery-3.2.1.min.js";
        e.onload = function () {
            jQuery.noConflict();
            console.log('jQuery ' + jQuery.fn.jquery + ' injected.');
        };
        document.head.appendChild(e);
    } else {
        console.log('jQuery ' + jQuery.fn.jquery + '');
    }
};
f();
</code>```

Body:
Does anyone know how to check if jquery has been loaded (with javascript) then load it if it hasnt been loaded.

something like

if(!jQuery) {
    //load jquery file
}


问:
Catching CollectiveViewSource's Filter event in ViewModel
How do I catch Filter event of CollectionViewSource in ViewModel using MVVM light?</p>

答: You might be interested in the BookLibrary sample application which delegates the Filter of a CollectionViewSource to the ViewModel. However, it doesn't use MVVM Light. The sample is part of the WPF Application Framework (WAF).


问:
How to use Excel formula combining replace and match
I have these sets of values in Excel and I want them to be replaced, please see the attached screenshot:

答:
I am not sure what you mean by "replace", but I think what you need is lookup function.

try this Vlookup function:

```<code>=VLOOKUP(D2,A:B,2,FALSE)
</code>```

You can learn more about vlookup here

Body:
I am not sure what you mean by "replace", but I think what you need is lookup function.

try this Vlookup function:

=VLOOKUP(D2,A:B,2,FALSE)

You can learn more about vlookup here


问:
Bash script that will read a number from file and run command if number equals or is higher than X value
I would like to have a script that reads a number from a file, and if this number equals or higher a certain value, it will run another command, if not, script will just die, it would be something like this:

```<code>[root@firewall ~]# cat result.txt
50
[root@firewall ~]#
[root@firewall ~]# ./run.sh
result.txt is higher or equals 50. Running /sbin/reboot
[root@firewall ~]#
</code>```

Thanks for any help.

答:
```<code>#!/bin/bash

THRESHOLD=50
VALUE=$(cat result.txt)

# -eq -> equals
# -gt -> greater than
# -ge -> greater than or equal (you are looking for this one)

if [ $VALUE -ge $THRESHOLD ]
then
  # Your action
fi
</code>```

Body:
I would like to have a script that reads a number from a file, and if this number equals or higher a certain value, it will run another command, if not, script will just die, it would be something like this:

[root@firewall ~]# cat result.txt
50
[root@firewall ~]#
[root@firewall ~]# ./run.sh
result.txt is higher or equals 50. Running /sbin/reboot
[root@firewall ~]#

Thanks for any help.


答:
looking to your code  i suggest you of refactor your query this way

using the join between the table instead of condition in case

```<code>  SELECT
    SUM(
      CASE
        WHEN s.name = 'Pending'
        THEN 1
        ELSE 0
      END
    ) AS PENDING
    , SUM(
      CASE
        WHEN s.name = 'new'
        THEN 1
        ELSE 0
      END
    ) AS NEW
   , SUM(
      CASE
        WHEN s.name = 'cancel'
        THEN 1
        ELSE 0
      END
    ) AS CANCEL
  FROM STATUSES s
  INNER JOIN ALERT_ITEM ai ON s.id = ai.status_id
      AND  ai.entity_name = 'Active Alert'
  INNER JOIN  ALERT_CASE_HEADER ach ON ach.alert_key = ai.entity_key
</code>```

Update after the new OP code

don't mix implicit and explicit join

```<code>   SELECT CUS.ORGUNIT_CODE AS ORGANIZATION_UNITS,
    SUM(
      CASE
        WHEN S.name = 'Pending' THEN 1 ELSE 0
      END
      ) AS PENDING_AUTOCLOSURE,
    SUM(
      CASE
        WHEN S.name = 'New' THEN 1 ELSE 0
      END
      ) AS NEW,
    SUM(
      CASE
        WHEN S.name = 'Under Investigation' THEN 1 ELSE 0
      END
    ) AS UNDER_INVESTIGATION,
    SUM(
      CASE
         WHEN S.Name = 'Escalated' THEN 1 ELSE 0
      END
    ) AS ESCALATED,
     SUM(
      CASE
         WHEN S.Name = 'Recommend True Positive' THEN 1 ELSE 0
      END
    ) AS RECOMMEND_TRUE_POSITIVE,
     SUM(
      CASE
         WHEN S.Name = 'Reopen Under Investigation' THEN 1 ELSE 0
      END
    ) AS REOPEN_UNDER_INVESTIGATION
  FROM
    STATUSES S
    JOIN ALERT_ITEM AI ON S.ID = AI.STATUS_ID
    JOIN ALERT_CASE_HEADER ACH ON AI.ENTITY_KEY = ACH.ALERT_KEY
    INNER JOIN CUSTOMERS CUS ON  AI.ORGUNIT_ID = CUS.ORGUNIT_ID
  WHERE AI.ENTITY_NAME = 'Active Alert'
  GROUP BY CUS.ORGUNIT_CODE;
</code>```

Title: Multipel condition at SQL Case

Body:
looking to your code  i suggest you of refactor your query this way

using the join between the table instead of condition in case

  SELECT
    SUM(
      CASE
        WHEN s.name = 'Pending'
        THEN 1
        ELSE 0
      END
    ) AS PENDING
    , SUM(
      CASE
        WHEN s.name = 'new'
        THEN 1
        ELSE 0
      END
    ) AS NEW
   , SUM(
      CASE
        WHEN s.name = 'cancel'
        THEN 1
        ELSE 0
      END
    ) AS CANCEL
  FROM STATUSES s
  INNER JOIN ALERT_ITEM ai ON s.id = ai.status_id
      AND  ai.entity_name = 'Active Alert'
  INNER JOIN  ALERT_CASE_HEADER ach ON ach.alert_key = ai.entity_key

Update after the new OP code

don't mix implicit and explicit join

   SELECT CUS.ORGUNIT_CODE AS ORGANIZATION_UNITS,
    SUM(
      CASE
        WHEN S.name = 'Pending' THEN 1 ELSE 0
      END
      ) AS PENDING_AUTOCLOSURE,
    SUM(
      CASE
        WHEN S.name = 'New' THEN 1 ELSE 0
      END
      ) AS NEW,
    SUM(
      CASE
        WHEN S.name = 'Under Investigation' THEN 1 ELSE 0
      END
    ) AS UNDER_INVESTIGATION,
    SUM(
      CASE
         WHEN S.Name = 'Escalated' THEN 1 ELSE 0
      END
    ) AS ESCALATED,
     SUM(
      CASE
         WHEN S.Name = 'Recommend True Positive' THEN 1 ELSE 0
      END
    ) AS RECOMMEND_TRUE_POSITIVE,
     SUM(
      CASE
         WHEN S.Name = 'Reopen Under Investigation' THEN 1 ELSE 0
      END
    ) AS REOPEN_UNDER_INVESTIGATION
  FROM
    STATUSES S
    JOIN ALERT_ITEM AI ON S.ID = AI.STATUS_ID
    JOIN ALERT_CASE_HEADER ACH ON AI.ENTITY_KEY = ACH.ALERT_KEY
    INNER JOIN CUSTOMERS CUS ON  AI.ORGUNIT_ID = CUS.ORGUNIT_ID
  WHERE AI.ENTITY_NAME = 'Active Alert'
  GROUP BY CUS.ORGUNIT_CODE;


问:
how to change icon colors dynamically in react js
how to change icons colors dynamically below here:

```<code>var byillingvalues=[];
for(var i in this.state.Alldata){
  byillingvalues.push({bycdata:this.state.Alldata[i].label})
}

var values=byillingvalues.map(function(d,idx){
        let colors=["#F0F8FF","#FFE4C4","#8A2BE2"];
        for(var i=0;i<=colors.length;i++){
              if(i==idx){
               return (<span key={idx}>{<i className="fa fa-square" aria-
                hidden="true" color:colors[i]></i>} {d.bycdata}   </span>);
             }

        }

});
</code>```

How to change icon colors dynamically in react?

答:
The color property need to be a style to i tag. You need to write

```<code><i className="fa fa-square"
   aria-hidden="true"
   style={{color:colors[i]}}>
</i>
</code>```

Body:
how to change icons colors dynamically below here:

var byillingvalues=[];
for(var i in this.state.Alldata){
  byillingvalues.push({bycdata:this.state.Alldata[i].label})
}

var values=byillingvalues.map(function(d,idx){
        let colors=["#F0F8FF","#FFE4C4","#8A2BE2"];
        for(var i=0;i<=colors.length;i++){
              if(i==idx){
               return ({} {d.bycdata}   );
             }

        }

});

How to change icon colors dynamically in react?

Body:
The color property need to be a style to i tag. You need to write

<i className="fa fa-square"
   aria-hidden="true"
   style={{color:colors[i]}}>
</i>


问:
Breaking line at operator with PEP8?
If I have a long expression with an operator:

```<code>if (this_is_a_really_long_expression > this_is_a_really_really_long_expression):
</code>```

how do I break it the line so it adheres to PEP8?

if I break it after the operator:

```<code>if (this_is_a_really_long_expression >
    this_is_a_really_really_long_expression):
</code>```

Atom (my editor) gives a syntax error for some reason...

答:
PEP8 now (since 2016-06-08) recommends breaking before the binary operator:

For decades the recommended style was to break after binary operators. But this can hurt readability in two ways: the operators tend to get scattered across different columns on the screen, and each operator is moved away from its operand and onto the previous line. Here, the eye has to do extra work to tell which items are added and which are subtracted:

```<code># No: operators sit far away from their operands
income = (gross_wages +
          taxable_interest +
          (dividends - qualified_dividends) -
          ira_deduction -
          student_loan_interest)
</code>```

To solve this readability problem, mathematicians and their publishers follow the opposite convention. Donald Knuth explains the traditional rule in his Computers and Typesetting series: "Although formulas within a paragraph always break after binary operations and relations, displayed formulas always break before binary operations" [3].

Following the tradition from mathematics usually results in more readable code:

```<code># Yes: easy to match operators with operands
income = (gross_wages
        + taxable_interest
        + (dividends - qualified_dividends)
        - ira_deduction
        - student_loan_interest)
</code>```

Specifically in this case, the alternatives would be:

```<code># No: last two lines have the same indentation
if (this_is_a_really_long_expression >
    this_is_a_really_really_long_expression):
    something_with_same_indentation()

# No: slightly better, but still last two lines have same indent
if (this_is_a_really_long_expression
    > this_is_a_really_really_long_expression):
    something_with_same_indentation()

# Yes (historically): easy to see it's not the next block
if (this_is_a_really_long_expression >
        this_is_a_really_really_long_expression):
    something_else()

# Yes: easy to see it's not the next block and what binary operator it is
if (this_is_a_really_long_expression
        > this_is_a_really_really_long_expression):
    something_else()
</code>```

Personally I strongly prefer the latter, however it's worth mentioning that at the moment yapf still outputs the 3rd (though I think it's a bug/not yet implemented)!

Linters (including Atom's!) will warn on the first two with E129 visually indented line with same indent as next logical line.

Atom (my editor) gives a syntax error for some reason...

I tested Atom (it worked), it's not a SyntaxError, but there may be something broken in your setup.

Title: Breaking line at operator with PEP8?

Body:
If I have a long expression with an operator:

if (this_is_a_really_long_expression > this_is_a_really_really_long_expression):

how do I break it the line so it adheres to PEP8?

if I break it after the operator:

if (this_is_a_really_long_expression >
    this_is_a_really_really_long_expression):

Atom (my editor) gives a syntax error for some reason...

Body:
PEP8 now (since 2016-06-08) recommends breaking before the binary operator:

For decades the recommended style was to break after binary operators. But this can hurt readability in two ways: the operators tend to get scattered across different columns on the screen, and each operator is moved away from its operand and onto the previous line. Here, the eye has to do extra work to tell which items are added and which are subtracted:

# No: operators sit far away from their operands
income = (gross_wages +
          taxable_interest +
          (dividends - qualified_dividends) -
          ira_deduction -
          student_loan_interest)

To solve this readability problem, mathematicians and their publishers follow the opposite convention. Donald Knuth explains the traditional rule in his Computers and Typesetting series: "Although formulas within a paragraph always break after binary operations and relations, displayed formulas always break before binary operations" [3].

Following the tradition from mathematics usually results in more readable code:

# Yes: easy to match operators with operands
income = (gross_wages
        + taxable_interest
        + (dividends - qualified_dividends)
        - ira_deduction
        - student_loan_interest)

Specifically in this case, the alternatives would be:

# No: last two lines have the same indentation
if (this_is_a_really_long_expression >
    this_is_a_really_really_long_expression):
    something_with_same_indentation()

# No: slightly better, but still last two lines have same indent
if (this_is_a_really_long_expression
    > this_is_a_really_really_long_expression):
    something_with_same_indentation()

# Yes (historically): easy to see it's not the next block
if (this_is_a_really_long_expression >
        this_is_a_really_really_long_expression):
    something_else()

# Yes: easy to see it's not the next block and what binary operator it is
if (this_is_a_really_long_expression
        > this_is_a_really_really_long_expression):
    something_else()

Personally I strongly prefer the latter, however it's worth mentioning that at the moment yapf still outputs the 3rd (though I think it's a bug/not yet implemented)!

Linters (including Atom's!) will warn on the first two with E129 visually indented line with same indent as next logical line.

Atom (my editor) gives a syntax error for some reason...

I tested Atom (it worked), it's not a SyntaxError, but there may be something broken in your setup.


问:
Using multiple @GenericGenerator?
I experimented with Hibernate's @GenericGenerator in a Spring Boot project (Hibernate 5). Made a test entity like this:

```<code>@Entity
public class BatchTest implements Serializable {
    private static final long serialVersionUID = 3012542467060581674L;

    @Id
    @GeneratedValue(generator = "batchTestIdGenerator")
    @GenericGenerator(
            name = "batchTestIdGenerator",
            strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
            parameters = {
                    @org.hibernate.annotations.Parameter(name = "increment_size",value = "1000")
            }
    )
    private long id;

    @Lob
    @Column(nullable = false)
    private String someVal;
...
</code>```

Using this generator I can insert entities really fast with JPA (I have a Spring Repository, served by a @Service) and it's cool, but how is the sequence actually stored? My database currently is an SQL Server 2016 instance, and in the schema, I can see that I have a dbo.hibernate_sequence:

If I create a second entity, with a different generator, I get an exception during startup:

```<code>@Id
@GeneratedValue(generator = "batchTestIdGenerator2", strategy = GenerationType.SEQUENCE)
@GenericGenerator(
        name = "batchTestIdGenerator2",
        strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
        parameters = {
                @org.hibernate.annotations.Parameter(name = "increment_size",value = "500")
        }
)
private long id;

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Multiple references to database sequence [hibernate_sequence] were encountered attempting toset conflicting values for 'increment size'.  Found [500] and [1000]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
</code>```

Can I define different sequences at all? It seems like It tries to use the same dbo.hibernate_sequence for both sequences (id did not create a new dbo sequence in the database) and just disregards the name. If it is possible to define N number of sequence, how can I do it?

Edit: I tried to create the sequences manually (matching names), but I still get the same error.

答:
According to section 11.1.48 SequenceGenerator Annotation of the JPA 2.1 specification:

The scope of the generator name is global to the persistence unit (across all generator types).

So you can't have duplicate generators.

Title: Using multiple @GenericGenerator?

Body:
I experimented with Hibernate's @GenericGenerator in a Spring Boot project (Hibernate 5). Made a test entity like this:

@Entity
public class BatchTest implements Serializable {
    private static final long serialVersionUID = 3012542467060581674L;

    @Id
    @GeneratedValue(generator = "batchTestIdGenerator")
    @GenericGenerator(
            name = "batchTestIdGenerator",
            strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
            parameters = {
                    @org.hibernate.annotations.Parameter(name = "increment_size",value = "1000")
            }
    )
    private long id;

    @Lob
    @Column(nullable = false)
    private String someVal;
...

Using this generator I can insert entities really fast with JPA (I have a Spring Repository, served by a @Service) and it's cool, but how is the sequence actually stored? My database currently is an SQL Server 2016 instance, and in the schema, I can see that I have a dbo.hibernate_sequence:

If I create a second entity, with a different generator, I get an exception during startup:

@Id
@GeneratedValue(generator = "batchTestIdGenerator2", strategy = GenerationType.SEQUENCE)
@GenericGenerator(
        name = "batchTestIdGenerator2",
        strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
        parameters = {
                @org.hibernate.annotations.Parameter(name = "increment_size",value = "500")
        }
)
private long id;

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Multiple references to database sequence [hibernate_sequence] were encountered attempting toset conflicting values for 'increment size'.  Found [500] and [1000]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]

Can I define different sequences at all? It seems like It tries to use the same dbo.hibernate_sequence for both sequences (id did not create a new dbo sequence in the database) and just disregards the name. If it is possible to define N number of sequence, how can I do it?

Edit: I tried to create the sequences manually (matching names), but I still get the same error.


问:
mPDF not showing image in generated PDF instead showing red x symbol and full url for background image
Recently I have moved from my staging server to production server and I don't have access to any of these servers.
Both of these servers are linux.

On the new server while generating the pdf using mPDF with symfony 1.4 framework, images like rupee symbol are not getting displayed instead a small red "x" symbol is getting displayed in pdf.

Also, when I try to give background image to pdf, full image path like "http://example.com/image/rupee-image.jpg" is getting displayed instead of image.

Rupee symbol, other images and background images are working fine on my staging server.

When, I did $mpdf->showImageError(), It's saying "mPDF Image Error:  Could not find image file" and pasting the url in browser displays the image perfectly.

Any help will be greatly appreciated.

答:
My problem was PHP 7 in this case! I check condition

```<code>if (!empty('/images/someimg.png')) {
    echo '<img ...';
} else {
    echo 'error in PHP 7';
}
</code>```

Be carefull using it. Version PHP 7.0.19

Body:
My problem was PHP 7 in this case! I check condition

if (!empty('/images/someimg.png')) {
    echo '<img ...';
} else {
    echo 'error in PHP 7';
}

Be carefull using it. Version PHP 7.0.19


问:
How do I wrap a function with an object in a class in javascript?
Let's say I have a class named Human.

```<code>function Human(name, gender, age, personality){
    this.name = name;
    this.gender = gender;
    this.age = age;
    this.personality = personality;
}
</code>```

and I have some functions for the class such as greeting and introduce. So I create them like this:

```<code>Human.prototype.introduce = function() {
    var _gender = {"M": "Boy", "F": "Girl"};
    switch(this.personality)
    {
    case "passionate":
        alert("Hi, how are you? My name is " + this.name + ". I'm " + this.age + " years old " + _gender[this.gender] + ". ");
        break;
    case "aggressive":
        alert("I'm " + this.name + ". What you want? ");
        break;
    }
}

Human.prototype.greeting = function() {
    alert("Hi!");
}
</code>```

Since introduce and greeting can be grouped by the same category (let's name it speak), how can I simply wrap this two functions with an object? I've tried this:

```<code>Human.prototype.speak = {};
Human.prototype.speak.greeting = function(){
    alert("Hi!");
}
Human.prototype.speak.introduce = function(){
var _gender = {"M": "Boy", "F": "Girl"};
        switch(this.personality)
        {
        case "passionate":
            alert("Hi, how are you? My name is " + this.name + ". I'm " + this.age + " years old " + _gender[this.gender] + ". ");
            break;
        case "aggressive":
            alert("I'm " + this.name + ". What you want? ");
            break;
        }
}
</code>```

Now the question is, when a function is wrapped by an object, this in the introduce function is no longer referring to the instance. So how can I work this out?

I would like to call the function as this:

```<code>var eminem = new Human("Marshall Mathers", "M", 45, "aggressive");
eminem.speak.introduce();
</code>```

答:
```<code>function Human(name, gender, age, personality){

    this.name = name;
    this.gender = gender;
    this.age = age;
    this.personality = personality;

    var self = this; //this is how

    this.speak = {

        introduce: function() {

            var _gender = {"M": "Boy", "F": "Girl"};
            switch(self.personality)
            {
            case "passionate":
                alert("Hi, how are you? My name is " + self.name + ". I'm " + self.age + " years old " + _gender[self.gender] + ". ");
                break;
            case "aggressive":
                alert("I'm " + self.name + ". What you want? ");
                break;
            }
        },

        greeting: function() {

            alert("Hi!");
        }
    };
}

var hulk = new Human("Hulk", "M", 33, "aggressive");
hulk.speak.introduce();
</code>```

Body:
Let's say I have a class named Human.

function Human(name, gender, age, personality){
    this.name = name;
    this.gender = gender;
    this.age = age;
    this.personality = personality;
}

and I have some functions for the class such as greeting and introduce. So I create them like this:

Human.prototype.introduce = function() {
    var _gender = {"M": "Boy", "F": "Girl"};
    switch(this.personality)
    {
    case "passionate":
        alert("Hi, how are you? My name is " + this.name + ". I'm " + this.age + " years old " + _gender[this.gender] + ". ");
        break;
    case "aggressive":
        alert("I'm " + this.name + ". What you want? ");
        break;
    }
}

Human.prototype.greeting = function() {
    alert("Hi!");
}

Since introduce and greeting can be grouped by the same category (let's name it speak), how can I simply wrap this two functions with an object? I've tried this:

Human.prototype.speak = {};
Human.prototype.speak.greeting = function(){
    alert("Hi!");
}
Human.prototype.speak.introduce = function(){
var _gender = {"M": "Boy", "F": "Girl"};
        switch(this.personality)
        {
        case "passionate":
            alert("Hi, how are you? My name is " + this.name + ". I'm " + this.age + " years old " + _gender[this.gender] + ". ");
            break;
        case "aggressive":
            alert("I'm " + this.name + ". What you want? ");
            break;
        }
}

Now the question is, when a function is wrapped by an object, this in the introduce function is no longer referring to the instance. So how can I work this out?

I would like to call the function as this:

var eminem = new Human("Marshall Mathers", "M", 45, "aggressive");
eminem.speak.introduce();


问:
MVC- Manage Virtaul Path for Js and Css file
I want manage path for JS and Css file without changing filder structure
 currrenlty my path is

```<code><link rel="stylesheet" href="@Url.Content("~/Content/newTheme/css/font.css")" type="text/css" />
</code>```

But i want path Like

```<code><link rel="stylesheet" href="@Url.Content("~/Myproject/Content/newTheme/css/font.css")" type="text/css" />
</code>```

Without changing folder structure
 One option is copy all files and folders in Myproject folder. But problem duplication of files.

答:
Are you sure you have a folder name "animate.css" I can see written twice so it can be a issue. secondly if MyProject is name of your folder you don't need to write that in path.

Simply using ~ will take the root of the URL (the path you see in browser). The first one should work, just remove the duplicate animate.css from href attribute.

Body:
I want manage path for JS and Css file without changing filder structure
 currrenlty my path is

<link rel="stylesheet" href="@Url.Content("~/Content/newTheme/css/font.css")" type="text/css" />

But i want path Like

<link rel="stylesheet" href="@Url.Content("~/Myproject/Content/newTheme/css/font.css")" type="text/css" />

Without changing folder structure
 One option is copy all files and folders in Myproject folder. But problem duplication of files.


问:
adding complex value in 3 Dimensional Array
I have a data type numpy.complex128 for added to matrix 3D (3 Dimensional Array). I write script like below. when I run the script there was a warning like "ComplexWarning: Casting complex values to real discards the imaginary part", and the result of 3D matrix was just real value, not include imaginary value. How can I fix it if I want to add both real and imaginary in that matrix 3D?</p>

```<code>for i in range (0, nper):
    zz = []
    x = np.zeros((nl,2,2))
    for j in range (0, nl):
        z = np.sqrt(phi*amu*res[j]/per[i])
        zz.append(complex(z,z))
        exp0 = np.exp((-2)*zz[j]/res[j]*thi[j])
        exp1 = complex(1,0)+exp0
        exp2 = complex(1,0)-exp0
    #matrix 3D
        x[j,0,0] = exp1
        x[j,0,1] = zz[j]*exp2
        x[j,1,0] = exp2/zz[j]
        x[j,1,1] = exp1
</code>```

答:
You probably missed to tell numpy that your x array is complex:

```<code>x = np.zeros((nl, 2, 2), dtype=np.complex128)
</code>```

Body:
I have a data type numpy.complex128 for added to matrix 3D (3 Dimensional Array). I write script like below. when I run the script there was a warning like "ComplexWarning: Casting complex values to real discards the imaginary part", and the result of 3D matrix was just real value, not include imaginary value. How can I fix it if I want to add both real and imaginary in that matrix 3D?

for i in range (0, nper):
    zz = []
    x = np.zeros((nl,2,2))
    for j in range (0, nl):
        z = np.sqrt(phi*amu*res[j]/per[i])
        zz.append(complex(z,z))
        exp0 = np.exp((-2)*zz[j]/res[j]*thi[j])
        exp1 = complex(1,0)+exp0
        exp2 = complex(1,0)-exp0
    #matrix 3D
        x[j,0,0] = exp1
        x[j,0,1] = zz[j]*exp2
        x[j,1,0] = exp2/zz[j]
        x[j,1,1] = exp1

Body:
You probably missed to tell numpy that your x array is complex:

x = np.zeros((nl, 2, 2), dtype=np.complex128)


问:
Vue.js replace hashtags in text with <router-link>
I receive some text from server which may contain some hashtags and when displaying this text I would like to convert these tags with links.

Example text is: "Today #weather is very nice"

Following code converts the string to

```<code>Today <router-link to="/tag/weather">#weather</router-link> is very nice
</code>```

but it is not rendered again to  tag.

```<code><template>
       <p v-html="content"/>
</template>

<script>
export default {
    methods: {
        convertHashTags: function(str) {
            return str.replace(/#([\w]+)/g,'<router-link to="/tag/$1">#$1</router-link>')
        }
    },
    data() {
        return{
             content: 'Today #weather is very nice'
        };
    }

</script>
</code>```

How can I re-render  content?

I tried https://codepen.io/movii/pen/WORoyg  this approach but it expects whole string to be a single link not some text and some links.

答:
Your code seems to fit ok into the dynamic-link component.

console.clear()

const Foo = { template: '
foo
' }
const Bar = { template: '
bar
' }
const Weather = { template: '
weather
' }

const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar },
  { path: '/tag/weather', component: Weather },
]

Vue.component('dynamic-link', {
  template: '<component v-bind:is="transformed"></component>',
  props: ['text'],
  methods: {
    convertHashTags: function(str) {
      const spanned = `<span>${str}</span>`
      return spanned.replace(/#([\w]+)/g,'<router-link to="/tag/$1">#$1</router-link>')
    }
  },
  computed: {
    transformed () {
      const template = this.convertHashTags(this.text);
      return {
        template: template,
        props: this.$options.props
      }
    }
  }
})

const router = new VueRouter({ routes })

const app = new Vue({
  router,
  data () {
    return {
      text: 'Today #weather is very nice'
    }
  }
}).$mount('#app');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.min.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

<div id="app">
  <router-link to="/bar">Go to Bar</router-link> |
  <dynamic-link :text="text"></dynamic-link>

  <router-view></router-view>
</div></code>```

Body:
I receive some text from server which may contain some hashtags and when displaying this text I would like to convert these tags with links.

Example text is: "Today #weather is very nice"

Following code converts the string to

Today <router-link to="/tag/weather">#weather</router-link> is very nice

but it is not rendered again to  tag.

<template>

</template>

How can I re-render  content?

I tried https://codepen.io/movii/pen/WORoyg  this approach but it expects whole string to be a single link not some text and some links.

Body:
Your code seems to fit ok into the dynamic-link component.

console.clear()

const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
const Weather = { template: '<div>weather</div>' }

const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar },
  { path: '/tag/weather', component: Weather },
]

Vue.component('dynamic-link', {
  template: '<component v-bind:is="transformed"></component>',
  props: ['text'],
  methods: {
    convertHashTags: function(str) {
      const spanned = `<span>${str}</span>`
      return spanned.replace(/#([\w]+)/g,'<router-link to="/tag/$1">#$1</router-link>')
    }
  },
  computed: {
    transformed () {
      const template = this.convertHashTags(this.text);
      return {
        template: template,
        props: this.$options.props
      }
    }
  }
})

const router = new VueRouter({ routes })

const app = new Vue({
  router,
  data () {
    return {
      text: 'Today #weather is very nice'
    }
  }
}).$mount('#app');

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.min.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

<div id="app">
  <router-link to="/bar">Go to Bar</router-link> |
  <dynamic-link :text="text"></dynamic-link>

  <router-view></router-view>
</div>


问:
Fetching Images from a folder and display them in modal using PHP
Im practicing some new things in Php and I have been trying to do this since past two days. I am counting the images in a given folder and displaying those images on the web-page.
Here's the code on my page.

```<code><?php
require "../_inc/master.inc.php";
require "../webConfig/web.config.php";
?>
<?php
doctype();
head_start("Gallery");
?>
<link rel="stylesheet" type="text/css" href="../lib/css/gallery.css" media="all" />
<?php
head_close();
?>
<?php
disp_head_start();
disp_head_close();
menu();
function countFolder($dir) {
 return (count(scandir($dir)) - 2);
}
$count=countFolder('../lib/media/imgs/uploads/gallery');
?>
<p> </p>
<div class="row" style="background-color:#7D37CE; padding:2%">
<?php for($i=1;$i<=$count;$i++){ ?>
<script>$(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip();
});</script>
    <div class="panel-group col-xs-12 col-sm-12 col-md-3 col-lg-3">
        <div class="panel panel-default">
            <div class="panel-body">
                <div class="thumb">
                    <a href="#" class="image-responsive" data-toggle="tooltip" title="Click to View">
                    <?php echo $i ?>
                        <img class="image-responsive g_img" data-toggle="modal" data-target="#image" src="../lib/media/imgs/uploads/gallery/<?php echo $i ?>.jpg" height="250px" width="100%" alt="Image" />
                        <?php //$name = $i ?>
                    </a>
                <!--image modal-->
                    <div id="image" class="modal fade" role="dialog">
                    <div class="modal-dialog">
                    <div class="modal-content">
                    <div class="modal-header">
                    <input type="submit" class="close bt" data-dismiss="modal" value="×" />
                    </div>
                    <div class="modal-body">
                    <img src="../lib/media/imgs/uploads/gallery/<?php echo $i ?>.jpg" class="mimg" alt="This image failed to load. Please reload the page." />
                    </div>
                    <div class="modal-footer">
                    <input type="submit" class="close bt" data-dismiss="modal" value="Close" />
                    </div>
                    </div>
                    </div>
                    </div>
                <!--// modal-->
                </div>
            </div>
        </div>
    </div>

<?php }?>

<?php

footer();
?>
</div>
<?php
close();
?>
</code>```

What my code does is it first counts the number of images in a folder and display's the image Thumbnails on the page. Here is the screenshot of the output

When clicked on the image, a modal box opens and shows that image like as shown in the image.

The Images in the folder have been named 1,2,3,4.... and so on.

My problem is that thumbnails are being displayed properly, but on clicking the image(whether first or any), the modal shows only the first image.

Thanks in advance.....

答:
it is because of data-target="#image"

You can use data-target="#image<?php echo $i ?>"

& change id="image<?php echo $i ?>" Modal
 ID also

Like:

```<code><?php
require "../_inc/master.inc.php";
require "../webConfig/web.config.php";
?>
<?php
doctype();
head_start("Gallery");
?>
<link rel="stylesheet" type="text/css" href="../lib/css/gallery.css" media="all" />
<?php
head_close();
?>
<?php
disp_head_start();
disp_head_close();
menu();
function countFolder($dir) {
 return (count(scandir($dir)) - 2);
}
$count=countFolder('../lib/media/imgs/uploads/gallery');
?>
<p> </p>
<div class="row" style="background-color:#7D37CE; padding:2%">
<?php for($i=1;$i<=$count;$i++){ ?>
<script>$(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip();
});</script>
    <div class="panel-group col-xs-12 col-sm-12 col-md-3 col-lg-3">
        <div class="panel panel-default">
            <div class="panel-body">
                <div class="thumb">
                    <a href="#" class="image-responsive" data-toggle="tooltip" title="Click to View">
                    <?php echo $i ?>
                        <img class="image-responsive g_img" data-toggle="modal" data-target="#image<?php echo $i ?>" src="../lib/media/imgs/uploads/gallery/<?php echo $i ?>.jpg" height="250px" width="100%" alt="Image" />
                        <?php //$name = $i ?>
                    </a>
                <!--image modal-->
                    <div id="image<?php echo $i ?>" class="modal fade" role="dialog">
                    <div class="modal-dialog">
                    <div class="modal-content">
                    <div class="modal-header">
                    <input type="submit" class="close bt" data-dismiss="modal" value="×" />
                    </div>
                    <div class="modal-body">
                    <img src="../lib/media/imgs/uploads/gallery/<?php echo $i ?>.jpg" class="mimg" alt="This image failed to load. Please reload the page." />
                    </div>
                    <div class="modal-footer">
                    <input type="submit" class="close bt" data-dismiss="modal" value="Close" />
                    </div>
                    </div>
                    </div>
                    </div>
                <!--// modal-->
                </div>
            </div>
        </div>
    </div>

<?php }?>

<?php

footer();
?>
</div>
<?php
close();
?>
</code>```

Body:
Im practicing some new things in Php and I have been trying to do this since past two days. I am counting the images in a given folder and displaying those images on the web-page.
Here's the code on my page.

<?php
require "../_inc/master.inc.php";
require "../webConfig/web.config.php";
?>
<?php
doctype();
head_start("Gallery");
?>
<link rel="stylesheet" type="text/css" href="../lib/css/gallery.css" media="all" />
<?php
head_close();
?>
<?php
disp_head_start();
disp_head_close();
menu();
function countFolder($dir) {
 return (count(scandir($dir)) - 2);
}
$count=countFolder('../lib/media/imgs/uploads/gallery');
?>

<?php for($i=1;$i<=$count;$i++){ ?>

                    <?php echo $i ?>
                        <img class="image-responsive g_img" data-toggle="modal" data-target="#image" src="../lib/media/imgs/uploads/gallery/<?php echo $i ?>.jpg" height="250px" width="100%" alt="Image" />
                        <?php //$name = $i ?>

                    <input type="submit" class="close bt" data-dismiss="modal" value="×" />

                    <img src="../lib/media/imgs/uploads/gallery/<?php echo $i ?>.jpg" class="mimg" alt="This image failed to load. Please reload the page." />

                    <input type="submit" class="close bt" data-dismiss="modal" value="Close" />

<?php }?>

<?php

footer();
?>

<?php
close();
?>

What my code does is it first counts the number of images in a folder and display's the image Thumbnails on the page. Here is the screenshot of the output

When clicked on the image, a modal box opens and shows that image like as shown in the image.

The Images in the folder have been named 1,2,3,4.... and so on.

My problem is that thumbnails are being displayed properly, but on clicking the image(whether first or any), the modal shows only the first image.

Thanks in advance.....

Body:
it is because of data-target="#image"

You can use data-target="#image<?php echo $i ?>"

& change id="image<?php echo $i ?>" Modal <div> ID also

Like:

<?php
require "../_inc/master.inc.php";
require "../webConfig/web.config.php";
?>
<?php
doctype();
head_start("Gallery");
?>
<link rel="stylesheet" type="text/css" href="../lib/css/gallery.css" media="all" />
<?php
head_close();
?>
<?php
disp_head_start();
disp_head_close();
menu();
function countFolder($dir) {
 return (count(scandir($dir)) - 2);
}
$count=countFolder('../lib/media/imgs/uploads/gallery');
?>
<p>&nbsp;</p>
<div class="row" style="background-color:#7D37CE; padding:2%">
<?php for($i=1;$i<=$count;$i++){ ?>
<script>$(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip();
});</script>
    <div class="panel-group col-xs-12 col-sm-12 col-md-3 col-lg-3">
        <div class="panel panel-default">
            <div class="panel-body">
                <div class="thumb">
                    <a href="#" class="image-responsive" data-toggle="tooltip" title="Click to View">
                    <?php echo $i ?>
                        <img class="image-responsive g_img" data-toggle="modal" data-target="#image<?php echo $i ?>" src="../lib/media/imgs/uploads/gallery/<?php echo $i ?>.jpg" height="250px" width="100%" alt="Image" />
                        <?php //$name = $i ?>
                    </a>
                <!--image modal-->
                    <div id="image<?php echo $i ?>" class="modal fade" role="dialog">
                    <div class="modal-dialog">
                    <div class="modal-content">
                    <div class="modal-header">
                    <input type="submit" class="close bt" data-dismiss="modal" value="&times;" />
                    </div>
                    <div class="modal-body">
                    <img src="../lib/media/imgs/uploads/gallery/<?php echo $i ?>.jpg" class="mimg" alt="This image failed to load. Please reload the page." />
                    </div>
                    <div class="modal-footer">
                    <input type="submit" class="close bt" data-dismiss="modal" value="Close" />
                    </div>
                    </div>
                    </div>
                    </div>
                <!--// modal-->
                </div>
            </div>
        </div>
    </div>

<?php }?>

<?php

footer();
?>
</div>
<?php
close();
?>


问:
Mysql select where t4.name=x and t2 or t3 have a t1.user !? :)
To explain my problem lets imagine 4 tables.

```<code>users - (userid, user.data)

buy - (buyid, productid, userid, buy.conditions)

sell - (sellid, productid, userid, sell.conditions)
</code>```

product - (productid, product.data)

I want to do a select that returns all the users and product data when there is a user that have products with X on the name to buy or sell.

```<code>SELECT userid,
       USER.DATA,
       productid,
       product.DATA
FROM   users,
       buy,
       sell,
       products
WHERE  ( buy.userid = users.userid
          OR sell.userid = users.userid )
       AND ( buy.productid = product.productid
              OR buy.productid = product.productid )
       AND product.DATA LIKE '%x%'
</code>```

this doesnt work but I belive you get the idea of what I am tryng to do.

答:
You could use the EXISTS clause:  </p>

```<code>SELECT userid,
       USER.DATA,
       productid,
       product.DATA
FROM   users,
       products
WHERE  ( EXISTS (SELECT *
             FROM   buy
                    INNER JOIN product
                      ON ( buy.productid = product.productid )
             WHERE  buy.userid = users.userid
                    AND product.DATA LIKE '%x%') )
        OR ( EXISTS (SELECT *
                 FROM   sell
                        INNER JOIN product
                          ON ( sell.productid = product.productid )
                 WHERE  sell.userid = users.userid
                        AND product.DATA LIKE '%x%')

        AND products.userid = users.userid)
</code>```

Body:
To explain my problem lets imagine 4 tables.

users - (userid, user.data)

buy - (buyid, productid, userid, buy.conditions)

sell - (sellid, productid, userid, sell.conditions)

product - (productid, product.data)

I want to do a select that returns all the users and product data when there is a user that have products with X on the name to buy or sell.

SELECT userid,
       USER.DATA,
       productid,
       product.DATA
FROM   users,
       buy,
       sell,
       products
WHERE  ( buy.userid = users.userid
          OR sell.userid = users.userid )
       AND ( buy.productid = product.productid
              OR buy.productid = product.productid )
       AND product.DATA LIKE '%x%'

this doesnt work but I belive you get the idea of what I am tryng to do.

Body:
You could use the EXISTS clause:

SELECT userid,
       USER.DATA,
       productid,
       product.DATA
FROM   users,
       products
WHERE  ( EXISTS (SELECT *
             FROM   buy
                    INNER JOIN product
                      ON ( buy.productid = product.productid )
             WHERE  buy.userid = users.userid
                    AND product.DATA LIKE '%x%') )
        OR ( EXISTS (SELECT *
                 FROM   sell
                        INNER JOIN product
                          ON ( sell.productid = product.productid )
                 WHERE  sell.userid = users.userid
                        AND product.DATA LIKE '%x%')

        AND products.userid = users.userid)


问:
Opencart get error when send email
Recently i moved my opencart shop to a new host but i found new issue in sending email by system, after user submit an order, system send a confirmation email for him and also for me (admin) successfully but user see an error:

Warning: mail(/var/log/php_mail.log): faild to open stream: Permission
  denied in ///system/library/mail.php on line 164

and also when i want to add a history to his order, when i check Notify Customer i see an error:

SyntaxError: Unexpected token < in JSON at position 0 OK Warning:
  mail(/var/log/php_mail.log): faild to open stream: Permission denied
  in ///system/library/mail.php on line 164

What this mean? and what's the problem?

I googled but none of results related to sending email case.

Thanks in advance

答:
I solved this issue. for future, if anyone face with this problem:

in e-mail setting should add e-mail with a -f at the beginning:

```<code>-fyou@youremail.com
</code>```

Title: Opencart get error when send email

Body:
I solved this issue. for future, if anyone face with this problem:

in e-mail setting should add e-mail with a -f at the beginning:

-fyou@youremail.com