问:
How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?
Wireless debugging was recently added as a feature in Xcode 9, iOS 11, and tvOS 11. Apple TV 4K doesn't have a USB port, so it requires wireless debugging. How do you perform this wireless debugging in Xcode?</p>

答:
For wireless debugging, Mac system and iPhone/Device should be on same network.
For making on same network you can do as -
Either you can start hotspot on Mac & connect that on iPhone/Device or vice versa.

On Mac

OR

On iPhone-

Xcode ► Window ►  Devices and Simulators ► select devices Tab ► click connect
  via network

https://help.apple.com/xcode/mac/9.0/index.html?localePath=en.lproj#/devbc48d1bad


来源: stackexchange

问:
How can I set a JWT Bearer token on HTMLMediaElement .load() request
I have an API which is using JWT for client authentication and this is working well for normal requests, but I can't find any way to control the headers that will get sent along with the request when I use the HTMLMediaElement to load an audio file for playback.

I'm using Angular 4 with Typescript, and here's the kind of code I'm using to load my URL, which works fine if I disable the access control on the API:

```<code>public Load(url: string): number{
    if (!this.audioElement) {
        this.audioElement = new Audio();
        this.audioElement.autoplay = false;
        this.audioElement.preload = 'auto';
    }
    this.audioElement.src = url;
    this.audioElement.load();
    this.audioElement.pause();
    return this.audioElement.duration;
}
</code>```

答:
I've got a similar requirement where I need to stream authenticated audio via a media player From an ASP.net WebApi.

You can elegantly achieve this using the HttpInterceptor which was introduced with Angular 4.3. This enables you to intercept http requests and add the bearer token:

This blog post describes how to achieve this: Angular Authentication: Using the Http Client and Http Interceptors

```<code>   // src/app/auth/token.interceptor.ts
import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { AuthService } from './auth/auth.service';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(public auth: AuthService) {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    request = request.clone({
      setHeaders: {
        Authorization: `Bearer ${this.auth.getToken()}`
      }
    });
    return next.handle(request);
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an API which is using JWT for client authentication and this is working well for normal requests, but I can't find any way to control the headers that will get sent along with the request when I use the HTMLMediaElement to load an audio file for playback.

I'm using Angular 4 with Typescript, and here's the kind of code I'm using to load my URL, which works fine if I disable the access control on the API:

public Load(url: string): number{
    if (!this.audioElement) {
        this.audioElement = new Audio();
        this.audioElement.autoplay = false;
        this.audioElement.preload = 'auto';
    }
    this.audioElement.src = url;
    this.audioElement.load();
    this.audioElement.pause();
    return this.audioElement.duration;
}

Body:
I've got a similar requirement where I need to stream authenticated audio via a media player From an ASP.net WebApi.

You can elegantly achieve this using the HttpInterceptor which was introduced with Angular 4.3. This enables you to intercept http requests and add the bearer token:

This blog post describes how to achieve this: Angular Authentication: Using the Http Client and Http Interceptors

   // src/app/auth/token.interceptor.ts
import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { AuthService } from './auth/auth.service';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(public auth: AuthService) {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    request = request.clone({
      setHeaders: {
        Authorization: `Bearer ${this.auth.getToken()}`
      }
    });
    return next.handle(request);
  }
}


问:
android notification firebase
I send a notification to android through PHP, and it gets normal on android.

But when I send more than one, it only shows the last one, and I wanted it to show all of them.

is it possible?

How can i do this?

PHP

```<code>$msg = array
          (
        'nome'  => $comando,
          );
    $fields = array
            (
                'to'    => $token,
                'data'  => $msg
            );

    $headers = array
            (
                'Content-Type: application/json',
                'Authorization: key= KEY'
            );

#Send Reponse To FireBase Server
        $ch = curl_init();
        curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
        curl_setopt( $ch,CURLOPT_POST, true );
        curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
        curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
        $result = curl_exec($ch );
        curl_close( $ch );

#Echo Result Of FireBase Server
echo $result;
</code>```

android

```<code>Intent intent = new Intent(this, MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                PendingIntent pendingIntent = PendingIntent.getActivity(this, 1410,
                        intent, PendingIntent.FLAG_UPDATE_CURRENT);

                Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
                alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                NotificationCompat.Builder notificationBuilder = new
                        NotificationCompat.Builder(this)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setSound(alert)
                        .setContentTitle("teste")
                        .setContentText("teste "+msg+"!")
                        .setAutoCancel(true)
                        .setOnlyAlertOnce(true)
                        .setPriority(2)
                        .setContentIntent(pendingIntent);

                NotificationManager notificationManager =
                        (NotificationManager)
                                getSystemService(Context.NOTIFICATION_SERVICE);

                notificationManager.notify(1410, notificationBuilder.build());
</code>```

答:
Cancel all the notifications before notifying the new one..</p>

```<code>NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();

notificationManager.notify(1410, notificationBuilder.build());
</code>```

Title: android notification firebase

Body:
I send a notification to android through PHP, and it gets normal on android.

But when I send more than one, it only shows the last one, and I wanted it to show all of them.

is it possible?

How can i do this?

PHP

$msg = array
          (
        'nome'  => $comando,
          );
    $fields = array
            (
                'to'    => $token,
                'data'  => $msg
            );

    $headers = array
            (
                'Content-Type: application/json',
                'Authorization: key= KEY'
            );

#Send Reponse To FireBase Server
        $ch = curl_init();
        curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
        curl_setopt( $ch,CURLOPT_POST, true );
        curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
        curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
        $result = curl_exec($ch );
        curl_close( $ch );

#Echo Result Of FireBase Server
echo $result;

android

Intent intent = new Intent(this, MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                PendingIntent pendingIntent = PendingIntent.getActivity(this, 1410,
                        intent, PendingIntent.FLAG_UPDATE_CURRENT);

                Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
                alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                NotificationCompat.Builder notificationBuilder = new
                        NotificationCompat.Builder(this)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setSound(alert)
                        .setContentTitle("teste")
                        .setContentText("teste "+msg+"!")
                        .setAutoCancel(true)
                        .setOnlyAlertOnce(true)
                        .setPriority(2)
                        .setContentIntent(pendingIntent);

                NotificationManager notificationManager =
                        (NotificationManager)
                                getSystemService(Context.NOTIFICATION_SERVICE);

                notificationManager.notify(1410, notificationBuilder.build());

Body:
Cancel all the notifications before notifying the new one..

NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();

notificationManager.notify(1410, notificationBuilder.build());


问:
Right approach to apply a HTML/CSS/JS theme to an React app
I've been trying to apply a template I bought on themeforest.net to my React web app. Converting template's HTML/CSS part to React components is relatively easy, however, I found it challenging to get the jQuery part to work.

The template uses several jQuery plugins, such as mmenu, magnific-popup, chosen. The sample index.html includes a custom.js near the end of body tag. By glancing through this custom.js (over 1000 lines of code), I found what it does is basically using jQuery selector to select a certain DOM node, then either applying a jQuery plugin function or extra CSS classes to the selected node. To me, this custom.js is a kitchen sink.

This works well in the static demo HTML pages, as the custom.js is loaded towards the end of the HTML page, all nodes are presented at the moment and ready for selectors to select.

However, being a single page application, React apps update DOM elements dynamically without the need to refresh the page. I found, in several places, the jQuery plugins lose controls over the DOM nodes after route being changed, or props updated.

A graceful but slower approach I can think of is to replace jQuery plugins with their functionally equivalent React components.

Another solution is to, hypothetically, brutal force executing the kitchen sink custom.js again an again, whenever there's a route change or component content update. But my gut feeling tells me I don't want to go there.

I would appreciate if anyone who has done this before could shed some light. At the moment, I use semantic-ui-react to style my app.

The theme I've been trying to apply is Listeo on themeforest.

PS: I read https://reactjs.org/docs/integrating-with-other-libraries.html but didn't find it a quick solution to me.

答:
This is a tricky part when converting HTML themes to react. If you are using jquery to manipulate DOM then you are neglecting the core principle of react. I have been through same situation few times. I have tried custom.js method you mentioned. From my experience it's not worth it you would run into lots of trouble and end up writing half of the libraries. And don't get me started on production you will want to rewrite everything from scratch.

I would suggest you to use equivalent React Components. It will be much easier for you to maintain the project later.


答:
Remove 1410 from this line and change PendingIntent line also.

```<code>PendingIntent pendingIntent = PendingIntent.getActivity(this, 1410,
                    intent, PendingIntent.FLAG_UPDATE_CURRENT);
notificationManager.notify(1410, notificationBuilder.build());
</code>```

Add this line for generate unique id and use it to notify .

```<code>int id = (int) System.currentTimeMillis();
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);
notificationManager.notify(id, notificationBuilder.build());
</code>```

Title: android notification firebase

Body:
Remove 1410 from this line and change PendingIntent line also.

PendingIntent pendingIntent = PendingIntent.getActivity(this, 1410,
                    intent, PendingIntent.FLAG_UPDATE_CURRENT);
notificationManager.notify(1410, notificationBuilder.build());

Add this line for generate unique id and use it to notify .

int id = (int) System.currentTimeMillis();
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);
notificationManager.notify(id, notificationBuilder.build());


问:
d3.js create same svg object with different data
I have a script, that works fine and create a chord diagram I need.
But now I want to create the same .svg file on another div but with different matrix.
Should I duplicate the same script for a new svg, or I can do in more efficient way?

You can find my code here.

Now my .Js script use drawChordWithMatrix(matrix_T1_T2) to show chord on div with id chart
What should I do to run drawChordWithMatrix(matrix_T2_T3) on id chart1

答:
One way i can think is

1) Move the SVG creation into the drawChordWithMatrix

So you need to pass the id to which you need to attach the SVG.
something like this function drawChordWithMatrix(matrix, id), and you create your SVG in the function like this.

```<code>var svg = d3.select(id).append("svg")//selecting on basis of ID.
            .attr("width", (width + margin.left + margin.right))
            .attr("height", (height + margin.top + margin.bottom));
</code>```

2) Next move all functions like fade, fadeOnChord , etc.. into the drawChordWithMatrix so that they all have the same scope.

working code here

Body:
One way i can think is

1) Move the SVG creation into the drawChordWithMatrix

So you need to pass the id to which you need to attach the SVG.
something like this function drawChordWithMatrix(matrix, id), and you create your SVG in the function like this.

var svg = d3.select(id).append("svg")//selecting on basis of ID.
            .attr("width", (width + margin.left + margin.right))
            .attr("height", (height + margin.top + margin.bottom));

2) Next move all functions like fade, fadeOnChord , etc.. into the drawChordWithMatrix so that they all have the same scope.

working code here


问:
Finding whats in one table that is not in another table
I have following two tables:

```<code>CREATE TABLE TEMP1(ID INT)
CREATE TABLE TEMP2(ID INT)

INSERT INTO TEMP1 SELECT 1
INSERT INTO TEMP1 SELECT 2
INSERT INTO TEMP1 SELECT 3
INSERT INTO TEMP1 SELECT 4

INSERT INTO TEMP2 SELECT 1
INSERT INTO TEMP2 SELECT 2
INSERT INTO TEMP2 SELECT 3
INSERT INTO TEMP2 SELECT 4
INSERT INTO TEMP2 SELECT 5

SELECT * FROM TEMP1
SELECT * FROM TEMP2
</code>```

I am trying to find the records which are in TEMP2, but not in TEMP1 i.e. 5.
If I run the following query, I get the proper result:

```<code>  SELECT DISTINCT [ID2] FROM (
   SELECT DISTINCT
   C1.[ID] AS [ID1]
   ,C2.[ID] AS [ID2]
   FROM TEMP1 C1
   FULL JOIN TEMP2 C2 ON C1.[ID]=C2.[ID]
   )A
   WHERE [ID1] IS NULL
   ORDER BY 1
</code>```

But when I run following query, I don't return anything:

```<code>   SELECT DISTINCT T2.[ID] FROM TEMP2 T2
   WHERE T2.[ID] NOT IN (SELECT DISTINCT T1.[ID] FROM TEMP1 T1 )
   ORDER BY 1
</code>```

Any idea whats wrong?

答:
I would suggest you should use <b> EXCEPT </B></p>

```<code>select ID from TEMP2
EXCEPT
Select ID from TEMP1
</code>```

Body:
I have following two tables:

CREATE TABLE TEMP1(ID INT)
CREATE TABLE TEMP2(ID INT)

INSERT INTO TEMP1 SELECT 1
INSERT INTO TEMP1 SELECT 2
INSERT INTO TEMP1 SELECT 3
INSERT INTO TEMP1 SELECT 4

INSERT INTO TEMP2 SELECT 1
INSERT INTO TEMP2 SELECT 2
INSERT INTO TEMP2 SELECT 3
INSERT INTO TEMP2 SELECT 4
INSERT INTO TEMP2 SELECT 5

SELECT * FROM TEMP1
SELECT * FROM TEMP2

I am trying to find the records which are in TEMP2, but not in TEMP1 i.e. 5.
If I run the following query, I get the proper result:

  SELECT DISTINCT [ID2] FROM (
   SELECT DISTINCT
   C1.[ID] AS [ID1]
   ,C2.[ID] AS [ID2]
   FROM TEMP1 C1
   FULL JOIN TEMP2 C2 ON C1.[ID]=C2.[ID]
   )A
   WHERE [ID1] IS NULL
   ORDER BY 1

But when I run following query, I don't return anything:

   SELECT DISTINCT T2.[ID] FROM TEMP2 T2
   WHERE T2.[ID] NOT IN (SELECT DISTINCT T1.[ID] FROM TEMP1 T1 )
   ORDER BY 1

Any idea whats wrong?

Body:
I would suggest you should use  EXCEPT

select ID from TEMP2
EXCEPT
Select ID from TEMP1


答:
The problem is in this line

```<code> notificationManager.notify(1410, notificationBuilder.build());
</code>```

the first parameter id should be different for each notification . Otherwise it will override the previous one .

A simple way around is to Use SharedPreference to get and store the Id . And each time use a incremented one. See the example below.

```<code> private int getNotificationId(){
    SharedPreferences  sp = PreferenceManager.getDefaultSharedPreferences(this);
    int lastId=sp.getInt("notify_id",0);
    sp.edit().putInt("notify_id",lastId+1).commit();
    return lastId;
}

 notificationManager.notify(getNotificationId(), notificationBuilder.build());
</code>```

Title: android notification firebase

Body:
The problem is in this line

 notificationManager.notify(1410, notificationBuilder.build());

the first parameter id should be different for each notification . Otherwise it will override the previous one .

A simple way around is to Use SharedPreference to get and store the Id . And each time use a incremented one. See the example below.

 private int getNotificationId(){
    SharedPreferences  sp = PreferenceManager.getDefaultSharedPreferences(this);
    int lastId=sp.getInt("notify_id",0);
    sp.edit().putInt("notify_id",lastId+1).commit();
    return lastId;
}

 notificationManager.notify(getNotificationId(), notificationBuilder.build());


问:
Select query result to List<int>
I have problem to do below query in Entity Framework and also equate the result to List:</p>

```<code>select count(*) from user_behave_fact
where beef_dairy_stat = 'True' and param_id = 2
group by p_min,p_max
go

using (var db = new J_DBEntities())
{
    List<int> dry_icc_ctn_mm = db.user_behave_fact.Where(x => x.beef_dairy_stat == true && x.param_id == 1)
        .GroupBy(x => new {x.p_min, x.p_max}).Count();
}
</code>```

答:
Try This instead</p>

```<code>using (var db = new J_DBEntities())
{
    List<int> dry_icc_ctn_mm = db.user_behave_fact.Where(x => x.beef_dairy_stat == true && x.param_id == 1)
        .GroupBy(x => new {x.p_min, x.p_max}).Select(y=>y.Count());
}
</code>```

Title: Select query result to List<int>

Body:
I have problem to do below query in Entity Framework and also equate the result to List:

select count(*) from user_behave_fact
where beef_dairy_stat = 'True' and param_id = 2
group by p_min,p_max
go

using (var db = new J_DBEntities())
{
    List<int> dry_icc_ctn_mm = db.user_behave_fact.Where(x => x.beef_dairy_stat == true && x.param_id == 1)
        .GroupBy(x => new {x.p_min, x.p_max}).Count();
}

Body:
Try This instead

using (var db = new J_DBEntities())
{
    List<int> dry_icc_ctn_mm = db.user_behave_fact.Where(x => x.beef_dairy_stat == true && x.param_id == 1)
        .GroupBy(x => new {x.p_min, x.p_max}).Select(y=>y.Count());
}


问:
htaccess 301 redirect example.com/beta/xyz to example.com/xyz
I need a general rule that maps every URL in the /beta subdirectory to the corresponding URL in the root; essentially I need to remove /beta from all URLs.

In case it makes any difference, the URLs are dynamically generated by WordPress.

Currently my .htaccess file is:

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
#END WordPress
</code>```

Can you tell me where to put the new lines?

Thank you!

答:
Your question is not entirely clear, but I would bet that what you want is having a Wordpress installed in somedir/beta appear in yoursite.com/ instead of yoursite.com/beta/.  The rules you pasted are in somedir/beta/.htaccess, and are the default Wordpress rules.  You must leave those alone.

What you need for that is to put the following rules in the root directory, as in, somedir/.htaccess, after changing example.com to your own domain.  Your webserver first reads this root .htaccess, and when it does, it will know to rewrite requests to /beta.

```<code><IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteCond %{REQUEST_URI} !^/beta/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /beta/$1
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteRule ^(/)?$ beta/index.php [L]
</IfModule>
</code>```

More info in the Codex:
https://codex.wordpress.org/Giving_WordPress_Its_Own_Directory

Body:
I need a general rule that maps every URL in the /beta subdirectory to the corresponding URL in the root; essentially I need to remove /beta from all URLs.

In case it makes any difference, the URLs are dynamically generated by WordPress.

Currently my .htaccess file is:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
#END WordPress

Can you tell me where to put the new lines?

Thank you!

Body:
Your question is not entirely clear, but I would bet that what you want is having a Wordpress installed in somedir/beta appear in yoursite.com/ instead of yoursite.com/beta/.  The rules you pasted are in somedir/beta/.htaccess, and are the default Wordpress rules.  You must leave those alone.

What you need for that is to put the following rules in the root directory, as in, somedir/.htaccess, after changing example.com to your own domain.  Your webserver first reads this root .htaccess, and when it does, it will know to rewrite requests to /beta.

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteCond %{REQUEST_URI} !^/beta/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /beta/$1
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteRule ^(/)?$ beta/index.php [L]
</IfModule>

More info in the Codex:
https://codex.wordpress.org/Giving_WordPress_Its_Own_Directory


问:
MySQL date format convert "Fri, 06 Nov 2015 04:06:05 -0500"
I have "Fri, 06 Nov 2015 04:06:05 -0500" date format in MySQL.

I want to convert it to Y-m-d H:i:s format within MySQL query. Can anyone please help?

I tried this DATE_FORMAT("Fri, 06 Nov 2015 04:06:05 -0500", '%Y-%m-%d H:i:s') but didn't work.

答:
You need to make two transformations here, to cover the general case.  First, you need to convert your non standard timestamp into a date, and then you need to format that date in the output you want.  Diagramatically:

```<code>your timestamp string -> MySQL date -> some other string output
</code>```

Consider this query:

```<code>SELECT
    DATE_FORMAT(STR_TO_DATE('Fri, 06 Nov 2015 04:06:05 -0500', '%a, %d %b %Y %H:%i:%S'),
                '%Y-%m-%d %H:%i:%s') AS output
FROM dual;
</code>```

Demo

Body:
You need to make two transformations here, to cover the general case.  First, you need to convert your non standard timestamp into a date, and then you need to format that date in the output you want.  Diagramatically:

your timestamp string -> MySQL date -> some other string output

Consider this query:

SELECT
    DATE_FORMAT(STR_TO_DATE('Fri, 06 Nov 2015 04:06:05 -0500', '%a, %d %b %Y %H:%i:%S'),
                '%Y-%m-%d %H:%i:%s') AS output
FROM dual;

Demo


问:
Oracle Apex ORA-00922: missing or invalid option
I tried creating a table on oracle apex but when I run it, it shows the following error: ORA-00922: missing or invalid option.
Here's my code:

```<code>CREATE TABLE  "PROD_INDEX"
   (
       "PNO" NUMBER (4,0) NOT NULL ENABLE,
    "CATEGORY" VARCHAR(15) ,
    "PRODUCT" VARCHAR2(10),
    "COUNTRY" VARCHAR2(9),
    "BRAND" VARCHAR(10)),
    "DATE" DATE,
    "YEAR" NUMBER(4,0),
    "COST" NUMBER(7,2),
    "SALES" NUMBER(10,2),
     PRIMARY KEY ("PNO") ENABLE
   )
/
</code>```

So what could be the problem?

答:
Run the below statement.</p>

```<code>CREATE TABLE "PROD_INDEX"
(
    "PNO" NUMBER (4,0) NOT NULL ENABLE,
    "CATEGORY" VARCHAR(15) ,
    "PRODUCT" VARCHAR2(10),
    "COUNTRY" VARCHAR2(9),
    "BRAND" VARCHAR(10),
    "DATE" DATE,
    "YEAR" NUMBER(4,0),
    "COST" NUMBER(7,2),
    "SALES" NUMBER(10,2),
    PRIMARY KEY ("PNO") ENABLE
)
</code>```

Body:
I tried creating a table on oracle apex but when I run it, it shows the following error: ORA-00922: missing or invalid option.
Here's my code:

CREATE TABLE  "PROD_INDEX"
   (
       "PNO" NUMBER (4,0) NOT NULL ENABLE,
    "CATEGORY" VARCHAR(15) ,
    "PRODUCT" VARCHAR2(10),
    "COUNTRY" VARCHAR2(9),
    "BRAND" VARCHAR(10)),
    "DATE" DATE,
    "YEAR" NUMBER(4,0),
    "COST" NUMBER(7,2),
    "SALES" NUMBER(10,2),
     PRIMARY KEY ("PNO") ENABLE
   )
/

So what could be the problem?

Body:
Run the below statement.

CREATE TABLE "PROD_INDEX"
(
    "PNO" NUMBER (4,0) NOT NULL ENABLE,
    "CATEGORY" VARCHAR(15) ,
    "PRODUCT" VARCHAR2(10),
    "COUNTRY" VARCHAR2(9),
    "BRAND" VARCHAR(10),
    "DATE" DATE,
    "YEAR" NUMBER(4,0),
    "COST" NUMBER(7,2),
    "SALES" NUMBER(10,2),
    PRIMARY KEY ("PNO") ENABLE
)


问:
MySQL/PHPMyAdmin - Importing 15,000 rows with 512MB of RAM
I'm trying to import 15,000 rows of data into my MySQL database. I know exactly how I would do this normally, but I have a constraint. 512MB of RAM... What's the most efficient way of doing this? Is there any way for MySQL to automatically import at a slower rate that way it doesn't crash due to not enough memory? Also, note that I'm using PHPMyAdmin. Thanks!</p>

答: How big of each row? If 1k(which is already very big) each row, 15000 rows only 15M, I don't think this will be a problem. If you really worry about it, just insert one row each time, don't use a bulk insert.</p>


答:
In android code you are using only one notification id, change it to dynamic and you will see all notifications.

change following line:

```<code>notificationManager.notify(getUniqueId(), notificationBuilder.build());

...
private int getUniqueId() {
    return (int) (System.currentTimeMillis() / 1000);
}
</code>```

Title: android notification firebase

Body:
In android code you are using only one notification id, change it to dynamic and you will see all notifications.

change following line:

notificationManager.notify(getUniqueId(), notificationBuilder.build());

...
private int getUniqueId() {
    return (int) (System.currentTimeMillis() / 1000);
}


问:
In Rails 3 how can you access the user_id of the last user in the database in your model?
Edit See Below:

```<code>class Post < ActiveRecord::Base
  last_user_id = User.last.id
  validates_inclusion_of :user_id, :in => 0..last_user_id
end
</code>```

The above solution works but as vojlo explains, once in production the code will only be executed once and the model will then validate against an incorrect range of users.

I'm working on a tutorial (rails 3.0.3) and have tried for the last half hour to figure out how to tell rails that one of the classes in my model should make sure the :user_id is within the range zero to the user_id of the last user in the database.

I know I need to be using:

```<code>validates_inclusion_of :user_id, :in 0..(can't figure out this piece)
</code>```

I was able to easily ensure the number entered for User_ID in numeric with:

```<code>validates_numericality_of :user_id
</code>```

I'm looking for information on where to research this, I took a good look at the ActiveRecord Validators documentation and didn't find much there.

答:
What happens if a User deletes their account? Don't you really just want to check for existence of the user?

```<code>class Post < ActiveRecord::Base
  belongs_to :user
  validates_presence_of :user
  ...
</code>```

Otherwise it's this pattern, which evaluates the post for validity against your requirements - the user_id is greater than zero and less than the largest user ID currently in the database:

```<code>class Post < ActiveRecord::Base
  include ActiveModel::Validations
  validates_with UserIdValidator
  ...

class UserIdValidator < ActiveModel::Validator
  def validate(record)
    max_user = User.find(:one, :order=>["id"])
    unless(user_id > max_user.id && user_id > 0)
      record.errors[:base] << "This record is invalid"
    end
  end
end
</code>```

But I still don't quite understand why you would want to do this - is there something particularly special about your user id? I'd recommend the first approach.

ContentLicense: CC BY-SA 2.5

Body:
Edit See Below:

class Post < ActiveRecord::Base
  last_user_id = User.last.id
  validates_inclusion_of :user_id, :in => 0..last_user_id
end

The above solution works but as vojlo explains, once in production the code will only be executed once and the model will then validate against an incorrect range of users.

I'm working on a tutorial (rails 3.0.3) and have tried for the last half hour to figure out how to tell rails that one of the classes in my model should make sure the :user_id is within the range zero to the user_id of the last user in the database.

I know I need to be using:

validates_inclusion_of :user_id, :in 0..(can't figure out this piece)

I was able to easily ensure the number entered for User_ID in numeric with:

validates_numericality_of :user_id

I'm looking for information on where to research this, I took a good look at the ActiveRecord Validators documentation and didn't find much there.

Body:
What happens if a User deletes their account? Don't you really just want to check for existence of the user?

class Post < ActiveRecord::Base
  belongs_to :user
  validates_presence_of :user
  ...

Otherwise it's this pattern, which evaluates the post for validity against your requirements - the user_id is greater than zero and less than the largest user ID currently in the database:

class Post < ActiveRecord::Base
  include ActiveModel::Validations
  validates_with UserIdValidator
  ...

class UserIdValidator < ActiveModel::Validator
  def validate(record)
    max_user = User.find(:one, :order=>["id"])
    unless(user_id > max_user.id && user_id > 0)
      record.errors[:base] << "This record is invalid"
    end
  end
end

But I still don't quite understand why you would want to do this - is there something particularly special about your user id? I'd recommend the first approach.


答:
You used PendingIntent.FLAG_UPDATE_CURRENT and no unique id for each Notification. Use this for showing Notification -

```<code>private void sendNotification(String messageBody) {
        int uniqueNotificationId = (int) (System.currentTimeMillis() & 0xfffffff);
        Intent intent = new Intent(this, LoginActivity.class); // Where you will go after clicking on notification
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, uniqueNotificationId /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

       //PendingIntent pendingIntent= PendingIntent.getActivity(this, uniqueNotificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        android.support.v4.app.NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle("FCM Message")
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(uniqueNotificationId  /* ID of notification */, notificationBuilder.build());
    }
</code>```

Title: android notification firebase

Body:
I send a notification to android through PHP, and it gets normal on android.

But when I send more than one, it only shows the last one, and I wanted it to show all of them.

is it possible?

How can i do this?

PHP

$msg = array
          (
        'nome'  => $comando,
          );
    $fields = array
            (
                'to'    => $token,
                'data'  => $msg
            );

    $headers = array
            (
                'Content-Type: application/json',
                'Authorization: key= KEY'
            );

#Send Reponse To FireBase Server
        $ch = curl_init();
        curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
        curl_setopt( $ch,CURLOPT_POST, true );
        curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
        curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
        $result = curl_exec($ch );
        curl_close( $ch );

#Echo Result Of FireBase Server
echo $result;

android

Intent intent = new Intent(this, MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                PendingIntent pendingIntent = PendingIntent.getActivity(this, 1410,
                        intent, PendingIntent.FLAG_UPDATE_CURRENT);

                Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
                alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                NotificationCompat.Builder notificationBuilder = new
                        NotificationCompat.Builder(this)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setSound(alert)
                        .setContentTitle("teste")
                        .setContentText("teste "+msg+"!")
                        .setAutoCancel(true)
                        .setOnlyAlertOnce(true)
                        .setPriority(2)
                        .setContentIntent(pendingIntent);

                NotificationManager notificationManager =
                        (NotificationManager)
                                getSystemService(Context.NOTIFICATION_SERVICE);

                notificationManager.notify(1410, notificationBuilder.build());

Body:
You used PendingIntent.FLAG_UPDATE_CURRENT and no unique id for each Notification. Use this for showing Notification -

private void sendNotification(String messageBody) {
        int uniqueNotificationId = (int) (System.currentTimeMillis() & 0xfffffff);
        Intent intent = new Intent(this, LoginActivity.class); // Where you will go after clicking on notification
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, uniqueNotificationId /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

       //PendingIntent pendingIntent= PendingIntent.getActivity(this, uniqueNotificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        android.support.v4.app.NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle("FCM Message")
                        .setContentText(messageBody)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(uniqueNotificationId  /* ID of notification */, notificationBuilder.build());
    }


问:
Elixir/Erlang split bitstring on newlines?
Is there a way to split a bitstring loaded from a file on newlines? I have something like this:

```<code>A line of text
Additional line of text
And another line
</code>```

And I want an array like this:

```<code>["A line of text",
"Additional line of text",
"And another line"]
</code>```

Is there a function to split the text on newlines to produce something like this array?

Thanks in advance.

答:
If you simply split a string on \n, there are some serious portability problems. This is because many systems use \n, a few such as older macs use \r and Windows uses \r\n to delimit new lines.

The safer way to do it would be to use a regex to match any of the three above possibilities:String.split(str, ~r{(\r\n|\r|\n)}.

Body:
Is there a way to split a bitstring loaded from a file on newlines? I have something like this:

A line of text
Additional line of text
And another line

And I want an array like this:

["A line of text",
"Additional line of text",
"And another line"]

Is there a function to split the text on newlines to produce something like this array?

Thanks in advance.

ContentLicense: CC BY-SA 4.0


问:
What am I doing wrong? Implementing infix to postfix using a stack
I'm trying to write an infix to postfix expression converter using a stack. Basically, it's an implementation of the Shunting Yard algorithm as found on wikipedia.

```<code>/*
    This function returns the precedence of a presented token. To keep comparisons
    simple, the higher the return value, the higher the precedence. Not to be
    confused with priority.

    From https://web.archive.org/web/20120822075917/http://en.literateprograms.org:80/Special:DownloadCode/Shunting_yard_algorithm_(Python)
*/
int precedence(string token)
{
    switch(token.at(0))
    {
        case '+':
            return 1;
        case '-':
            return 1;
        case '*':
            return 2;
        case '/':
          return 2;
        case '(':
            return 0;
        case ')':
            return 0;
    }

    return 0;
}

/*
  Returns true if the supplied token is an operator.
*/
bool is_operator(const string& token)
{
    return token == "*"
        || token == "/"
        || token == "+"
        || token == "-";
}

/*
  Returns true if the supplied token is an operand (not an operator).
*/
bool is_operand(const string& token)
{
    return !is_operator(token) && (token != "(") && (token != ")");
}

void display(const vector<string>& v)
{
    for(unsigned int i=0; i<v.size(); i++)
    {
        cout << v[i] << " ";
    }
    cout << endl;
}

string associativity(const string& token)
{
    if(token == "*" || token == "+")
    {
        return "left";
    }
    else if(token == "/" || token =="-")
    {
        return "left";
    }

    return "?";
}

/*
    From wikipedia:

while there are tokens to be read:
    read a token.
    if the token is a number, then push it to the output queue.
    if the token is an operator, then:
        while (there is an operator at the top of the operator stack with
            greater precedence) or (the operator at the top of the operator stack has
                        equal precedence and
                        the operator is left associative) and
                      (the operator at the top of the stack is not a left bracket):
                pop operators from the operator stack, onto the output queue.
        push the read operator onto the operator stack.
    if the token is a left bracket (i.e. "("), then:
        push it onto the operator stack.
    if the token is a right bracket (i.e. ")"), then:
        while the operator at the top of the operator stack is not a left bracket:
            pop operators from the operator stack onto the output queue.
        pop the left bracket from the stack.
if there are no more tokens to read:
    while there are still operator tokens on the stack:
        pop the operator onto the output queue.
exit.
*/
vector<string> infix_to_postfix(const vector<string>& infix, bool& error)
{
    vector<string> postfix;
    stack<string> operators;

    for(string token : infix)
    {
        if(is_operand(token))
        {
            postfix.push_back(token);
        }
        if(is_operator(token))
        {
            while
            (
                (!operators.empty() && precedence(operators.peek()) > precedence(token))
            || (!operators.empty() && (precedence(operators.peek()) == precedence(token))   && (associativity(token) == "left") && (token != "("))
            )
            {
                string tk = operators.pop();
                if(tk != "(" && tk != ")")
                {
                    postfix.push_back(tk);
                }
            }
            operators.push(token);
        }
        if(token == "(")
        {
            operators.push(token);
        }
        if(token == ")")
        {
            while(!operators.empty() && operators.peek() != "(")
            {
                postfix.push_back(operators.pop());
            }
            if(!operators.empty())
            {
                operators.pop();
            }
        }
    }

    while(!operators.empty())
    {
        postfix.push_back(operators.pop());
    }

    return postfix;
}
</code>```

I expect this code to return a valid postfix expression in the form of a vector containing the relevant tokens.

The following evaluate function returns weird numbers for a longer expression I'm testing with.

```<code>double evaluate(const vector<string>& postfix, bool& error)
{
    error = false;
    double result;
    stack<double> numbers;
    for(unsigned int i=0; i<postfix.size(); i++)
    {
        string token = postfix[i];

        if(is_operand(token))
        {
            numbers.push(stod(token));
        }
        else
        {
            double operand1 = numbers.pop();
            double operand2 = numbers.pop();
            switch(token.at(0))
            {
                case '+':
                    numbers.push(operand1 + operand2);
                    break;
                case '-':
                    numbers.push(operand1 - operand2);
                    break;
                case '*':
                    numbers.push(operand1 * operand2);
                    break;
                case '/':
                    numbers.push(operand1 / operand2);
                    break;
            }
        }
    }
</code>```

For example, consider this input and output:

```<code>Infix: ( 3 + 3 * 5 ) * 6 - 2 / 1 + 3 + 3 * 5 * ( 4 + 1 )
Postfix: 3 3 5 * + 6 * 2 1 / 3 3 5 4 1 + * * + + -
Result: -29.5
</code>```

Google says its 184.

Update:
I included an associativity function from wikipedia. I also updated the expression result.

Update 2:
Incorporated the comments that made this code work.

答:
Obviously your postfix conversion output is already wrong. ( 3 + 3 * 5 ) should have become 3 3 5 * +, not 3 3 + 5 *

```<code>       while
        (
            (!operators.empty() && precedence(token) <= precedence(operators.peek()))
            || (!operators.empty() && operators.peek() != "(")
        )
</code>```

This part is wrong. The text says (pred(operators.peek()) > pred(token)) || (pred(operators.peek()) == pred(token) && token != "(").

As a result, you did always wrongly pop the operator whenever it was not a closing parantheses, ignoring operator precedence.

```<code>        double operand1 = numbers.pop();
        double operand2 = numbers.pop();
</code>```

That part is also wrong. Operand 2 is the one higher on the stack. Switch them around.

Body:
I'm trying to write an infix to postfix expression converter using a stack. Basically, it's an implementation of the Shunting Yard algorithm as found on wikipedia.

/*
    This function returns the precedence of a presented token. To keep comparisons
    simple, the higher the return value, the higher the precedence. Not to be
    confused with priority.

    From https://web.archive.org/web/20120822075917/http://en.literateprograms.org:80/Special:DownloadCode/Shunting_yard_algorithm_(Python)
*/
int precedence(string token)
{
    switch(token.at(0))
    {
        case '+':
            return 1;
        case '-':
            return 1;
        case '*':
            return 2;
        case '/':
          return 2;
        case '(':
            return 0;
        case ')':
            return 0;
    }

    return 0;
}

/*
  Returns true if the supplied token is an operator.
*/
bool is_operator(const string& token)
{
    return token == "*"
        || token == "/"
        || token == "+"
        || token == "-";
}

/*
  Returns true if the supplied token is an operand (not an operator).
*/
bool is_operand(const string& token)
{
    return !is_operator(token) && (token != "(") && (token != ")");
}

void display(const vector<string>& v)
{
    for(unsigned int i=0; i<v.size(); i++)
    {
        cout << v[i] << " ";
    }
    cout << endl;
}

string associativity(const string& token)
{
    if(token == "*" || token == "+")
    {
        return "left";
    }
    else if(token == "/" || token =="-")
    {
        return "left";
    }

    return "?";
}

/*
    From wikipedia:

while there are tokens to be read:
    read a token.
    if the token is a number, then push it to the output queue.
    if the token is an operator, then:
        while (there is an operator at the top of the operator stack with
            greater precedence) or (the operator at the top of the operator stack has
                        equal precedence and
                        the operator is left associative) and
                      (the operator at the top of the stack is not a left bracket):
                pop operators from the operator stack, onto the output queue.
        push the read operator onto the operator stack.
    if the token is a left bracket (i.e. "("), then:
        push it onto the operator stack.
    if the token is a right bracket (i.e. ")"), then:
        while the operator at the top of the operator stack is not a left bracket:
            pop operators from the operator stack onto the output queue.
        pop the left bracket from the stack.
if there are no more tokens to read:
    while there are still operator tokens on the stack:
        pop the operator onto the output queue.
exit.
*/
vector<string> infix_to_postfix(const vector<string>& infix, bool& error)
{
    vector<string> postfix;
    stack<string> operators;

    for(string token : infix)
    {
        if(is_operand(token))
        {
            postfix.push_back(token);
        }
        if(is_operator(token))
        {
            while
            (
                (!operators.empty() && precedence(operators.peek()) > precedence(token))
            || (!operators.empty() && (precedence(operators.peek()) == precedence(token))   && (associativity(token) == "left") && (token != "("))
            )
            {
                string tk = operators.pop();
                if(tk != "(" && tk != ")")
                {
                    postfix.push_back(tk);
                }
            }
            operators.push(token);
        }
        if(token == "(")
        {
            operators.push(token);
        }
        if(token == ")")
        {
            while(!operators.empty() && operators.peek() != "(")
            {
                postfix.push_back(operators.pop());
            }
            if(!operators.empty())
            {
                operators.pop();
            }
        }
    }

    while(!operators.empty())
    {
        postfix.push_back(operators.pop());
    }

    return postfix;
}

I expect this code to return a valid postfix expression in the form of a vector containing the relevant tokens.

The following evaluate function returns weird numbers for a longer expression I'm testing with.

double evaluate(const vector<string>& postfix, bool& error)
{
    error = false;
    double result;
    stack<double> numbers;
    for(unsigned int i=0; i<postfix.size(); i++)
    {
        string token = postfix[i];

        if(is_operand(token))
        {
            numbers.push(stod(token));
        }
        else
        {
            double operand1 = numbers.pop();
            double operand2 = numbers.pop();
            switch(token.at(0))
            {
                case '+':
                    numbers.push(operand1 + operand2);
                    break;
                case '-':
                    numbers.push(operand1 - operand2);
                    break;
                case '*':
                    numbers.push(operand1 * operand2);
                    break;
                case '/':
                    numbers.push(operand1 / operand2);
                    break;
            }
        }
    }

For example, consider this input and output:

Infix: ( 3 + 3 * 5 ) * 6 - 2 / 1 + 3 + 3 * 5 * ( 4 + 1 )
Postfix: 3 3 5 * + 6 * 2 1 / 3 3 5 4 1 + * * + + -
Result: -29.5

Google says its 184.

Update:
I included an associativity function from wikipedia. I also updated the expression result.

Update 2:
Incorporated the comments that made this code work.

Body:
Obviously your postfix conversion output is already wrong. ( 3 + 3 * 5 ) should have become 3 3 5 * +, not 3 3 + 5 *

       while
        (
            (!operators.empty() && precedence(token) <= precedence(operators.peek()))
            || (!operators.empty() && operators.peek() != "(")
        )

This part is wrong. The text says (pred(operators.peek()) > pred(token)) || (pred(operators.peek()) == pred(token) && token != "(").

As a result, you did always wrongly pop the operator whenever it was not a closing parantheses, ignoring operator precedence.

        double operand1 = numbers.pop();
        double operand2 = numbers.pop();

That part is also wrong. Operand 2 is the one higher on the stack. Switch them around.


问:
C# Case Sensitivity in Switch-statement
I'm working a little with switch statements and want to know how to ignore the case sensitivity when it comes to input values.

Here is my code:

```<code>using System;

namespace SwitchStatements
{
class MainClass
{
    public static void Main(string[] args)
    {
    Start:
        Console.WriteLine("Please Input the Grade");
        char grade = Convert.ToChar(Console.ReadLine());

        switch (grade)
        {
            case 'A':
                Console.WriteLine("Excellent Work!");
                break;
            case 'B':
                Console.WriteLine("Very Good Effort! Just a couple of     Errors =)");
                break;
            case 'C':
                Console.WriteLine("You Passed. Push Yourself Next Time");
                break;
            case 'D':
                Console.WriteLine("Better put in more effort next time. I know you can do better");
                break;
            default:
                Console.WriteLine("Invalid Grade.");
                break;
        }
        Console.ReadKey();
        goto Start;
    }
}
}
</code>```

If I put 'a' in instead of 'A' it returns the default response.

Can I use perhaps a .Comparison of some sort? If so where would I put it?

答:
string letterGrade;
            int grade = 0;</p>

```<code>        // This will hold the final letter grade
        Console.Write("Input the grade :");

        switch (grade)
        {

            case 1:
                // 90-100 is an A
                letterGrade = "A";
                Console.WriteLine("grade b/n 90-100");
                break;
            case 2:
                // 80-89 is a B
                letterGrade = "B";
                Console.WriteLine("grade b/n 80-89");
                break;
            case 3:
                // 70-79 is a C
                letterGrade = "C";
                Console.WriteLine("grade b/n 70-79");
                break;
            case 4:
                // 60-69 is a D
                letterGrade = "D";
                Console.WriteLine(" grade b/n 60-69 ");
                break;
            default:
                // point whic is less than 59
                Console.WriteLine("Invalid grade");

                break;
        }
</code>```

Title: C# Case Sensitivity in Switch-statement

Body:
I'm working a little with switch statements and want to know how to ignore the case sensitivity when it comes to input values.

Here is my code:

using System;

namespace SwitchStatements
{
class MainClass
{
    public static void Main(string[] args)
    {
    Start:
        Console.WriteLine("Please Input the Grade");
        char grade = Convert.ToChar(Console.ReadLine());

        switch (grade)
        {
            case 'A':
                Console.WriteLine("Excellent Work!");
                break;
            case 'B':
                Console.WriteLine("Very Good Effort! Just a couple of     Errors =)");
                break;
            case 'C':
                Console.WriteLine("You Passed. Push Yourself Next Time");
                break;
            case 'D':
                Console.WriteLine("Better put in more effort next time. I know you can do better");
                break;
            default:
                Console.WriteLine("Invalid Grade.");
                break;
        }
        Console.ReadKey();
        goto Start;
    }
}
}

If I put 'a' in instead of 'A' it returns the default response.

Can I use perhaps a .Comparison of some sort? If so where would I put it?

Body:
string letterGrade;
            int grade = 0;

        // This will hold the final letter grade
        Console.Write("Input the grade :");

        switch (grade)
        {

            case 1:
                // 90-100 is an A
                letterGrade = "A";
                Console.WriteLine("grade b/n 90-100");
                break;
            case 2:
                // 80-89 is a B
                letterGrade = "B";
                Console.WriteLine("grade b/n 80-89");
                break;
            case 3:
                // 70-79 is a C
                letterGrade = "C";
                Console.WriteLine("grade b/n 70-79");
                break;
            case 4:
                // 60-69 is a D
                letterGrade = "D";
                Console.WriteLine(" grade b/n 60-69 ");
                break;
            default:
                // point whic is less than 59
                Console.WriteLine("Invalid grade");

                break;
        }


问:
How can I find out which Form trigger the script?
I'm trying to have my standalone script a common trigger(onFormSubmit trigger) for multiple forms and determine the which form triggered the script.

```<code>function myFunction() {
  ScriptApp.newTrigger('onFormSubmit').forForm('FormID_1').onFormSubmit().create();
  ScriptApp.newTrigger('onFormSubmit').forForm('FormID_2').onFormSubmit().create();
  ScriptApp.newTrigger('onFormSubmit').forForm('FormID_3').onFormSubmit().create();
}

function onFormSubmit(e){
  Logger.log(e);
}
</code>```

However the parameter e only has {authMode=FULL, response=FormResponse, triggerUid=......}, no FormId.

How can I know which form triggered the script?

答:
Please think of this as one of several answers. From your question, it is found that you can retrieve triggerUid from the parameter e. So how about saving triggerUid using PropertiesService? triggerUid is ID for each trigger. By using this ID, the form which is submitted can be retrieved.

When you use this sample script, at first, please run myFunction(), and submit using form. You can see the result at Stackdriver (View -> Stackdriver Logging). The form ID of form which was used can be retrieved.

The sample script is as follows.

Sample script :

```<code>function myFunction() {
  var FormID_1 = 'FormID_1';
  var FormID_2 = 'FormID_2';
  var FormID_3 = 'FormID_3';
  var form1 = ScriptApp.newTrigger('onFormSubmit').forForm(FormID_1).onFormSubmit().create();
  var form2 = ScriptApp.newTrigger('onFormSubmit').forForm(FormID_2).onFormSubmit().create();
  var form3 = ScriptApp.newTrigger('onFormSubmit').forForm(FormID_3).onFormSubmit().create();
  var forms = {};
  forms[FormID_1] = form1.getUniqueId();
  forms[FormID_2] = form2.getUniqueId();
  forms[FormID_3] = form3.getUniqueId();
  PropertiesService.getScriptProperties().setProperties(forms);
}

function onFormSubmit(e) {
  var forms = PropertiesService.getScriptProperties().getProperties();
  for (v in forms) {
    if (forms[v] == e.triggerUid) {
      console.log(v) // v is the form name which was submitted. You can see this at Stackdriver.
    }
  }
}
</code>```

Reference :

PropertiesService

If I misunderstand your question, I'm sorry.

Edit :

How about this? In this case, each form has each function. And each function calls onFormSubmit(e).

```<code>function myFunction() {
  ScriptApp.newTrigger('form1').forForm('FormID_1').onFormSubmit().create();
  ScriptApp.newTrigger('form2').forForm('FormID_2').onFormSubmit().create();
  ScriptApp.newTrigger('form3').forForm('FormID_3').onFormSubmit().create();
}

function form1(e){
  onFormSubmit(e)
}

function form2(e){
  onFormSubmit(e)
}

function form3(e){
  onFormSubmit(e)
}

function onFormSubmit(e){
  Logger.log(e);
}
</code>```

Body:
I'm trying to have my standalone script a common trigger(onFormSubmit trigger) for multiple forms and determine the which form triggered the script.

function myFunction() {
  ScriptApp.newTrigger('onFormSubmit').forForm('FormID_1').onFormSubmit().create();
  ScriptApp.newTrigger('onFormSubmit').forForm('FormID_2').onFormSubmit().create();
  ScriptApp.newTrigger('onFormSubmit').forForm('FormID_3').onFormSubmit().create();
}

function onFormSubmit(e){
  Logger.log(e);
}

However the parameter e only has {authMode=FULL, response=FormResponse, triggerUid=......}, no FormId.

How can I know which form triggered the script?

Body:
Please think of this as one of several answers. From your question, it is found that you can retrieve triggerUid from the parameter e. So how about saving triggerUid using PropertiesService? triggerUid is ID for each trigger. By using this ID, the form which is submitted can be retrieved.

When you use this sample script, at first, please run myFunction(), and submit using form. You can see the result at Stackdriver (View -> Stackdriver Logging). The form ID of form which was used can be retrieved.

The sample script is as follows.

Sample script :

function myFunction() {
  var FormID_1 = 'FormID_1';
  var FormID_2 = 'FormID_2';
  var FormID_3 = 'FormID_3';
  var form1 = ScriptApp.newTrigger('onFormSubmit').forForm(FormID_1).onFormSubmit().create();
  var form2 = ScriptApp.newTrigger('onFormSubmit').forForm(FormID_2).onFormSubmit().create();
  var form3 = ScriptApp.newTrigger('onFormSubmit').forForm(FormID_3).onFormSubmit().create();
  var forms = {};
  forms[FormID_1] = form1.getUniqueId();
  forms[FormID_2] = form2.getUniqueId();
  forms[FormID_3] = form3.getUniqueId();
  PropertiesService.getScriptProperties().setProperties(forms);
}

function onFormSubmit(e) {
  var forms = PropertiesService.getScriptProperties().getProperties();
  for (v in forms) {
    if (forms[v] == e.triggerUid) {
      console.log(v) // v is the form name which was submitted. You can see this at Stackdriver.
    }
  }
}

Reference :

PropertiesService

If I misunderstand your question, I'm sorry.

Edit :

How about this? In this case, each form has each function. And each function calls onFormSubmit(e).

function myFunction() {
  ScriptApp.newTrigger('form1').forForm('FormID_1').onFormSubmit().create();
  ScriptApp.newTrigger('form2').forForm('FormID_2').onFormSubmit().create();
  ScriptApp.newTrigger('form3').forForm('FormID_3').onFormSubmit().create();
}

function form1(e){
  onFormSubmit(e)
}

function form2(e){
  onFormSubmit(e)
}

function form3(e){
  onFormSubmit(e)
}

function onFormSubmit(e){
  Logger.log(e);
}


问:
Toggle Bootstrap button text on button click?
I want to toggle the text on a button each time it's clicked, e.g. from "Show more..." to "Show less...".

I have a button that's used to expand or collapse a nearby block (see the Collapse section of the Bootstrap docs, click the example "Link with href" button there to see what I mean).

The HTML for such a Bootstrap button looks like this:

```<code><a class="btn btn-primary" data-toggle="collapse" href="#collapseExample">
    See more...
</a>
</code>```

When the related block is collapsed I want the button text to be e.g. "Show more..." and when it's expanded I want it to be e.g. "Show less...".

I've seen solutions that separate the button text off into jQuery, Javascript or CSS - but that makes it difficult to read the HTML (the button text is somewhere else entirely to the button) and also makes it more difficult to localize.

答:
I tried a couple of these approaches before cobbling this one together. It is the simplest, most readable approach I've seen so far:

```<code>    <a href="#" data-toggle='collapse'
        data-target="#filters,#view_filters,#hide_filters">
      <span id='view_filters' class='collapse in'>View Filters</span>
      <span id='hide_filters' class='collapse out'>Hide Filters</span>
    </a>

    <div id="filters" class="collapse out">
      Now you see me!
    </div>
</code>```

The main purpose of this link is to toggle visibility of div#filters...but it takes advantage of multiple selectors in data_target to also toggle the visibility of the two versions of the link text. Just make sure you've got one text as ".collapse .in" and the other as ".collapse .out".

Beyond its simplicity, I like that this is very reliable. Because the  tag is never hidden or manipulated, you'll never accidentally lose the view/hide link while debugging.

Body:
I want to toggle the text on a button each time it's clicked, e.g. from "Show more..." to "Show less...".

I have a button that's used to expand or collapse a nearby block (see the Collapse section of the Bootstrap docs, click the example "Link with href" button there to see what I mean).

The HTML for such a Bootstrap button looks like this:

    See more...

When the related block is collapsed I want the button text to be e.g. "Show more..." and when it's expanded I want it to be e.g. "Show less...".

I've seen solutions that separate the button text off into jQuery, Javascript or CSS - but that makes it difficult to read the HTML (the button text is somewhere else entirely to the button) and also makes it more difficult to localize.

Body:
I tried a couple of these approaches before cobbling this one together. It is the simplest, most readable approach I've seen so far:

    <a href="#" data-toggle='collapse'
        data-target="#filters,#view_filters,#hide_filters">
      <span id='view_filters' class='collapse in'>View Filters</span>
      <span id='hide_filters' class='collapse out'>Hide Filters</span>
    </a>

    <div id="filters" class="collapse out">
      Now you see me!
    </div>

The main purpose of this link is to toggle visibility of div#filters...but it takes advantage of multiple selectors in data_target to also toggle the visibility of the two versions of the link text. Just make sure you've got one text as ".collapse .in" and the other as ".collapse .out".

Beyond its simplicity, I like that this is very reliable. Because the  tag is never hidden or manipulated, you'll never accidentally lose the view/hide link while debugging.


问:
Integer Value Right Padding in SQL
Step1: I have a table called XYZ which contains following integer columns:

```<code> ID      A          B          C
 1    201507    20150810   20150311
 2    20150812  201509     201510
</code>```

I need to write a SQL query where if any values of A, B, and C is smaller than 8 digits then I need to consider it as 8 digits by adding zeros to the right of the value for step2 (I am not allowed to update the table.). For example:

```<code> ID      A            B          C
 1    20150700    20150810   20150311
 2    20150812    20150900   20151000
</code>```

How to add zeros to the right of the integer values through SQL query?

Step 2: I need to find for each record A<B, B<C or not. Please let me know how to write the query. I am using PostgreSQL. Thank you.

答:
Try this:

```<code>select cast(left(cast(A as varchar(20)) + '00000000', 8) as int) as [A],
       cast(left(cast(B as varchar(20)) + '00000000', 8) as int) as [B],
       cast(left(cast(C as varchar(20)) + '00000000', 8) as int) as [C]
from TABLE_NAME
</code>```

If you want to avoid any casting, this might be solution:

```<code>select case when 8 - LEN(A) > 0 then A * Power(10, (8 - LEN(A))) else A end as [A],
       case when 8 - LEN(B) > 0 then B * Power(10, (8 - LEN(B))) else B end as [B],
       case when 8 - LEN(C) > 0 then C * Power(10, (8 - LEN(C))) else C end as [C]
from MY_TABLE
</code>```

Title: Integer Value Right Padding in SQL

Body:
Step1: I have a table called XYZ which contains following integer columns:

 ID      A          B          C
 1    201507    20150810   20150311
 2    20150812  201509     201510

I need to write a SQL query where if any values of A, B, and C is smaller than 8 digits then I need to consider it as 8 digits by adding zeros to the right of the value for step2 (I am not allowed to update the table.). For example:

 ID      A            B          C
 1    20150700    20150810   20150311
 2    20150812    20150900   20151000

How to add zeros to the right of the integer values through SQL query?

Step 2: I need to find for each record A<B, B<C or not. Please let me know how to write the query. I am using PostgreSQL. Thank you.

Body:
Try this:

select cast(left(cast(A as varchar(20)) + '00000000', 8) as int) as [A],
       cast(left(cast(B as varchar(20)) + '00000000', 8) as int) as [B],
       cast(left(cast(C as varchar(20)) + '00000000', 8) as int) as [C]
from TABLE_NAME

If you want to avoid any casting, this might be solution:

select case when 8 - LEN(A) > 0 then A * Power(10, (8 - LEN(A))) else A end as [A],
       case when 8 - LEN(B) > 0 then B * Power(10, (8 - LEN(B))) else B end as [B],
       case when 8 - LEN(C) > 0 then C * Power(10, (8 - LEN(C))) else C end as [C]
from MY_TABLE


问:
How to Cast List(Int) to Int without using for loop
I'm Trying to cast Second Element of nested List(Int) var element = List(List[String]()) to Int

```<code>  element :+= List("rules", "8")
</code>```

I tried like var value = element.tail().toString.toInt but it returns List(Int)

also tried var value =  element.tail().map(_.toString.toInt) but no luck again List(8)

I want to convert the tail part of List("8") to Integer

I don't find any direct method to do so, So I tried like

```<code>for(convert <- element.tail){ var casted = convert.toInt }
</code>```

What is the efficient way to convert the second element of a nested List(Int) to Int ?

答:
The tail method returns another List with all the elements except the first. That's why it doesn't work in your case.
If you know that your list has exactly 2 elements, you can access the second either by last or list(1) and then call toInt, so in your case

```<code>element.last.toInt
</code>```

or

```<code>element(1).toInt
</code>```

Body:
I'm Trying to cast Second Element of nested List(Int) var element = List(List[String]()) to Int

  element :+= List("rules", "8")

I tried like var value = element.tail().toString.toInt but it returns List(Int)

also tried var value =  element.tail().map(_.toString.toInt) but no luck again List(8)

I want to convert the tail part of List("8") to Integer

I don't find any direct method to do so, So I tried like

for(convert <- element.tail){ var casted = convert.toInt }

What is the efficient way to convert the second element of a nested List(Int) to Int ?

Body:
The tail method returns another List with all the elements except the first. That's why it doesn't work in your case.
If you know that your list has exactly 2 elements, you can access the second either by last or list(1) and then call toInt, so in your case

element.last.toInt

or

element(1).toInt


问:
SQL Query calculating the average of an average
I read through several posts on similar issues to this, and cannot seem to find the correct solution. I have tried adding the calculation to several parts of the query, without success. I am sure I am missing something simple.

I work at a mine and I was asked to accomplish the following:

They want to know which trucks was more than 5 % below the average payload of all the other trucks average payload over the past 3 days. It also needs to exclude any trucks that had less than 10 loads

There are 3 tables:

hist_loads (Gives payload and a lot of other information)

hist_exproot (Gives information related to dates, need this to give
a readable date)

hist_eqmtlist (Need this to determine the specific truck models, as
not all truck models must be included)

All of the above tables are joined together by a column called "shiftindex")

Below is my Query:

```<code>    IF OBJECT_ID ('tempdb.dbo.#pave') IS NOT NULL DROP TABLE dbo.#pave;
IF OBJECT_ID ('tempdb.dbo.#pfinal') IS NOT NULL DROP TABLE dbo.#pfinal;

select
    shiftdate
    ,truck
    ,AVG(measureton) as measureton
    ,COUNT(excav) as loads
into #pfinal
from hist_loads as hl
inner join hist_exproot as he on
he.shiftindex = hl.shiftindex
inner join hist_eqmtlist as heq on
heq.shiftindex = hl.shiftindex and
hl.truck = heq.eqmtid
where hl.shiftindex between
                            (select min(shiftindex)
                            from hist_exproot
                            where datepart(year,shiftdate) = datepart(year, getdate()-3)
                            and datepart(month,shiftdate) = datepart(month, getdate()-3)
                            and datepart(day,shiftdate) = datepart(day, getdate()-3))
        and
                            (select max(shiftindex)
                            from hist_exproot
                            where datepart(year,shiftdate) = datepart(year, getdate()-1)
                            and datepart(month,shiftdate) = datepart(month, getdate()-1)
                            and datepart(day,shiftdate) = datepart(day, getdate()-1))

and eqmttype in ('Euclid EH4500','Euclid EH4500-W','Euclid EH4500-HW')
and expit like 1
and measureton not like 0

group by eqmttype, truck, shiftdate
having COUNT(excav) > 10

select
    shiftdate
    ,AVG(measureton) as measureton
    ,COUNT(excav) as loads
into #pave
from hist_loads as hl
inner join hist_exproot as he on
he.shiftindex = hl.shiftindex
inner join hist_eqmtlist as heq on
heq.shiftindex = hl.shiftindex and
hl.truck = heq.eqmtid
where hl.shiftindex between
                            (select min(shiftindex)
                            from hist_exproot
                            where datepart(year,shiftdate) = datepart(year, getdate()-3)
                            and datepart(month,shiftdate) = datepart(month, getdate()-3)
                            and datepart(day,shiftdate) = datepart(day, getdate()-3))
        and
                            (select max(shiftindex)
                            from hist_exproot
                            where datepart(year,shiftdate) = datepart(year, getdate()-1)
                            and datepart(month,shiftdate) = datepart(month, getdate()-1)
                            and datepart(day,shiftdate) = datepart(day, getdate()-1))

and eqmttype in ('Euclid EH4500','Euclid EH4500-W','Euclid EH4500-HW')
and measureton not like 0

group by eqmttype, shiftdate
having COUNT(excav) > 10

select ave.shiftdate, ave.measureton, final.truck
from #pave as ave
left join #pfinal as final on
ave.shiftdate = final.shiftdate
where final.measureton < ave.measureton
order by truck
</code>```

My Result:

```<code>shiftdate           measureton         truck
2017-12-03 00:00:00 230.444365964912    DT01
2017-12-02 00:00:00 231.123014419048    DT04
2017-12-02 00:00:00 231.123014419048    DT07
2017-12-03 00:00:00 230.444365964912    DT07
2017-12-04 00:00:00 226.141955641026    DT07
2017-12-04 00:00:00 226.141955641026    DT10
2017-12-02 00:00:00 231.123014419048    DT13
2017-12-03 00:00:00 230.444365964912    DT14
2017-12-02 00:00:00 231.123014419048    DT15
2017-12-03 00:00:00 230.444365964912    DT17
2017-12-04 00:00:00 226.141955641026    DT17
2017-12-03 00:00:00 230.444365964912    DT20
2017-12-04 00:00:00 226.141955641026    DT20
2017-12-02 00:00:00 231.123014419048    DT22
2017-12-04 00:00:00 226.141955641026    DT24
2017-12-02 00:00:00 231.123014419048    DT25
2017-12-02 00:00:00 231.123014419048    DT27
2017-12-03 00:00:00 230.444365964912    DT27
2017-12-04 00:00:00 226.141955641026    DT28
2017-12-02 00:00:00 231.123014419048    DT30
2017-12-02 00:00:00 231.123014419048    DT31
2017-12-03 00:00:00 230.444365964912    DT31
2017-12-04 00:00:00 226.141955641026    DT32
</code>```

But I only need the trucks that were more than 5% under the average payload. The above result seems to be all of the trucks average payload over the past 3 days. And there also seem to be some repetition between 3 numbers.

Any help would be appreciated.

答:
@DRapp. Thanks, this worked, with a bit of a tweak. Your date logic gave me some errors in SSMS. So I replaced it with my date logic:

```<code>Msg 206, Level 16, State 2, Line 1
Operand type clash: date is incompatible with int
</code>```

I also removed the shiftdate in the select statement, as I realized it was not a requirement to split it into seperate dates. On a request, I also extended the timeframe to 7 days. So the final working query looks as follows:

```<code>IF OBJECT_ID ('tempdb.dbo.#pTruckAvgs') IS NOT NULL DROP TABLE dbo.#pTruckAvgs;

SELECT
      truck,
      AVG(measureton) as measureton,
      COUNT(excav) as loads
   into
      #pTruckAvgs
   from
      hist_loads as hl
         inner join hist_exproot as he
            ON hl.shiftindex = he.shiftindex
         inner join hist_eqmtlist as heq
            ON hl.shiftindex = heq.shiftindex
            and hl.truck = heq.eqmtid
   where
          hl.shiftindex between
                            (select min(shiftindex)
                            from hist_exproot
                            where datepart(year,shiftdate) = datepart(year, getdate()-7)
                            and datepart(month,shiftdate) = datepart(month, getdate()-7)
                            and datepart(day,shiftdate) = datepart(day, getdate()-7))
        and
                            (select max(shiftindex)
                            from hist_exproot
                            where datepart(year,shiftdate) = datepart(year, getdate()-1)
                            and datepart(month,shiftdate) = datepart(month, getdate()-1)
                            and datepart(day,shiftdate) = datepart(day, getdate()-1))
      --and hl.shiftindex < CONVERT(date, getdate())
      and eqmttype in ('Euclid EH4500','Euclid EH4500-W','Euclid EH4500-HW')
      and expit like 1
      and measureton not like 0
      and measureton > 150
   group by
      eqmttype,
      truck
   having
      COUNT(excav) >= 10;

select
      TA.*,
      QualAvgs.AllAvg
    from
       #pTruckAvgs TA,
       (select AVG(measureton) as AllAvg
            from #pTruckAvgs ) QualAvgs
    where
       TA.measureTon < ( QualAvgs.AllAvg * .95);
</code>```

The result looks as follows:

```<code>truck   measureton          loads   AllAvg
DT05    204.876060232558    43      224.850465129605
</code>```

Thanks for everyone's assistance, it is highly appreciated.

Body:
I read through several posts on similar issues to this, and cannot seem to find the correct solution. I have tried adding the calculation to several parts of the query, without success. I am sure I am missing something simple.

I work at a mine and I was asked to accomplish the following:

They want to know which trucks was more than 5 % below the average payload of all the other trucks average payload over the past 3 days. It also needs to exclude any trucks that had less than 10 loads

There are 3 tables:

hist_loads (Gives payload and a lot of other information)

hist_exproot (Gives information related to dates, need this to give
a readable date)

hist_eqmtlist (Need this to determine the specific truck models, as
not all truck models must be included)

All of the above tables are joined together by a column called "shiftindex")

Below is my Query:

    IF OBJECT_ID ('tempdb.dbo.#pave') IS NOT NULL DROP TABLE dbo.#pave;
IF OBJECT_ID ('tempdb.dbo.#pfinal') IS NOT NULL DROP TABLE dbo.#pfinal;

select
    shiftdate
    ,truck
    ,AVG(measureton) as measureton
    ,COUNT(excav) as loads
into #pfinal
from hist_loads as hl
inner join hist_exproot as he on
he.shiftindex = hl.shiftindex
inner join hist_eqmtlist as heq on
heq.shiftindex = hl.shiftindex and
hl.truck = heq.eqmtid
where hl.shiftindex between
                            (select min(shiftindex)
                            from hist_exproot
                            where datepart(year,shiftdate) = datepart(year, getdate()-3)
                            and datepart(month,shiftdate) = datepart(month, getdate()-3)
                            and datepart(day,shiftdate) = datepart(day, getdate()-3))
        and
                            (select max(shiftindex)
                            from hist_exproot
                            where datepart(year,shiftdate) = datepart(year, getdate()-1)
                            and datepart(month,shiftdate) = datepart(month, getdate()-1)
                            and datepart(day,shiftdate) = datepart(day, getdate()-1))

and eqmttype in ('Euclid EH4500','Euclid EH4500-W','Euclid EH4500-HW')
and expit like 1
and measureton not like 0

group by eqmttype, truck, shiftdate
having COUNT(excav) > 10

select
    shiftdate
    ,AVG(measureton) as measureton
    ,COUNT(excav) as loads
into #pave
from hist_loads as hl
inner join hist_exproot as he on
he.shiftindex = hl.shiftindex
inner join hist_eqmtlist as heq on
heq.shiftindex = hl.shiftindex and
hl.truck = heq.eqmtid
where hl.shiftindex between
                            (select min(shiftindex)
                            from hist_exproot
                            where datepart(year,shiftdate) = datepart(year, getdate()-3)
                            and datepart(month,shiftdate) = datepart(month, getdate()-3)
                            and datepart(day,shiftdate) = datepart(day, getdate()-3))
        and
                            (select max(shiftindex)
                            from hist_exproot
                            where datepart(year,shiftdate) = datepart(year, getdate()-1)
                            and datepart(month,shiftdate) = datepart(month, getdate()-1)
                            and datepart(day,shiftdate) = datepart(day, getdate()-1))

and eqmttype in ('Euclid EH4500','Euclid EH4500-W','Euclid EH4500-HW')
and measureton not like 0

group by eqmttype, shiftdate
having COUNT(excav) > 10

select ave.shiftdate, ave.measureton, final.truck
from #pave as ave
left join #pfinal as final on
ave.shiftdate = final.shiftdate
where final.measureton < ave.measureton
order by truck

My Result:

shiftdate           measureton         truck
2017-12-03 00:00:00 230.444365964912    DT01
2017-12-02 00:00:00 231.123014419048    DT04
2017-12-02 00:00:00 231.123014419048    DT07
2017-12-03 00:00:00 230.444365964912    DT07
2017-12-04 00:00:00 226.141955641026    DT07
2017-12-04 00:00:00 226.141955641026    DT10
2017-12-02 00:00:00 231.123014419048    DT13
2017-12-03 00:00:00 230.444365964912    DT14
2017-12-02 00:00:00 231.123014419048    DT15
2017-12-03 00:00:00 230.444365964912    DT17
2017-12-04 00:00:00 226.141955641026    DT17
2017-12-03 00:00:00 230.444365964912    DT20
2017-12-04 00:00:00 226.141955641026    DT20
2017-12-02 00:00:00 231.123014419048    DT22
2017-12-04 00:00:00 226.141955641026    DT24
2017-12-02 00:00:00 231.123014419048    DT25
2017-12-02 00:00:00 231.123014419048    DT27
2017-12-03 00:00:00 230.444365964912    DT27
2017-12-04 00:00:00 226.141955641026    DT28
2017-12-02 00:00:00 231.123014419048    DT30
2017-12-02 00:00:00 231.123014419048    DT31
2017-12-03 00:00:00 230.444365964912    DT31
2017-12-04 00:00:00 226.141955641026    DT32

But I only need the trucks that were more than 5% under the average payload. The above result seems to be all of the trucks average payload over the past 3 days. And there also seem to be some repetition between 3 numbers.

Any help would be appreciated.

Body:
@DRapp. Thanks, this worked, with a bit of a tweak. Your date logic gave me some errors in SSMS. So I replaced it with my date logic:

Msg 206, Level 16, State 2, Line 1
Operand type clash: date is incompatible with int

I also removed the shiftdate in the select statement, as I realized it was not a requirement to split it into seperate dates. On a request, I also extended the timeframe to 7 days. So the final working query looks as follows:

IF OBJECT_ID ('tempdb.dbo.#pTruckAvgs') IS NOT NULL DROP TABLE dbo.#pTruckAvgs;

SELECT
      truck,
      AVG(measureton) as measureton,
      COUNT(excav) as loads
   into
      #pTruckAvgs
   from
      hist_loads as hl
         inner join hist_exproot as he
            ON hl.shiftindex = he.shiftindex
         inner join hist_eqmtlist as heq
            ON hl.shiftindex = heq.shiftindex
            and hl.truck = heq.eqmtid
   where
          hl.shiftindex between
                            (select min(shiftindex)
                            from hist_exproot
                            where datepart(year,shiftdate) = datepart(year, getdate()-7)
                            and datepart(month,shiftdate) = datepart(month, getdate()-7)
                            and datepart(day,shiftdate) = datepart(day, getdate()-7))
        and
                            (select max(shiftindex)
                            from hist_exproot
                            where datepart(year,shiftdate) = datepart(year, getdate()-1)
                            and datepart(month,shiftdate) = datepart(month, getdate()-1)
                            and datepart(day,shiftdate) = datepart(day, getdate()-1))
      --and hl.shiftindex < CONVERT(date, getdate())
      and eqmttype in ('Euclid EH4500','Euclid EH4500-W','Euclid EH4500-HW')
      and expit like 1
      and measureton not like 0
      and measureton > 150
   group by
      eqmttype,
      truck
   having
      COUNT(excav) >= 10;

select
      TA.*,
      QualAvgs.AllAvg
    from
       #pTruckAvgs TA,
       (select AVG(measureton) as AllAvg
            from #pTruckAvgs ) QualAvgs
    where
       TA.measureTon < ( QualAvgs.AllAvg * .95);

The result looks as follows:

truck   measureton          loads   AllAvg
DT05    204.876060232558    43      224.850465129605

Thanks for everyone's assistance, it is highly appreciated.


问:
Fastest way to code up hitting a URL
I need to login to a site, then hit a certain URL about a thousand times (with different params, of course).

The URL is something this:

```<code>http://www.foo.com/bar.asp?id=x    ' where x is the ID
</code>```

Of course if I simply hit the URL without being logged, it will fail.
I am not very familiar with this type of work, but I would imagine that whatever the method I choose, it would have to support cookies.

I was thinking that I could create a winform app with a browser control and somehow drive it, but that seems like a massive overkill.

Is there a better way?

答:
If you are determined to do it in your code itself then i dont think any thing is stopping you from doing that.
HttpRequest and HttpResponse classes has pretty much everything you need to do that.

Moreover if you are concerned about cookies then you could always store received cookies in a database or file and send them with every subsequent request.

If you want to know the structure of the Http Request like a GET request then look here.

Also you can make your request look like a Request from browser by specifying the Proper Request Headers...(However it doesn't work every time)

And all this can be done even in a console app

Title: Fastest way to code up hitting a URL

Body:
I need to login to a site, then hit a certain URL about a thousand times (with different params, of course).

The URL is something this:

http://www.foo.com/bar.asp?id=x    ' where x is the ID

Of course if I simply hit the URL without being logged, it will fail.
I am not very familiar with this type of work, but I would imagine that whatever the method I choose, it would have to support cookies.

I was thinking that I could create a winform app with a browser control and somehow drive it, but that seems like a massive overkill.

Is there a better way?


问:
How can I compare all the values of an enum with a given array in java?
I have an enum class with values:

```<code>  enum carBrand{BMW,HONDA,MERC,AUDI};
</code>```

And there's an array called Sales with Array values:

```<code> sales[] = {CHEVVY, BMW , MERC, AUDI};
</code>```

So how could I check that the sales[] has all the values of enum carBrand?

I'm trying to put it in a for loop as:

```<code> for(int i = 0; i<sales.length;i++){
     if(carBrand.sales == sales[i]){
        return true;
     }
 return false;
 }
</code>```

答:
I would, personally, suggest using a list object rather than an Array where you are using such, however, this should work.

```<code>public static boolean checkArray(carBrand[] array) {
    for (carBrand c : carBrand.values()) {
        boolean found = false;
        for (carBrand a : array) {
            if (a == c) {
                found = true;
                break;
            }
        }
        if (!found) {
            return false;
        }
    }
    return true;
}
</code>```

where the "array" parameter would be invoked as the sales object in your code.

This code will return false if not every enum value exists within your array.

Off-topic:
Things like this are actually all over the internet - here, google, even Bing (as garbo as Bing is), so searching before requesting help, probably a viable choice

Body:
I have an enum class with values:

  enum carBrand{BMW,HONDA,MERC,AUDI};

And there's an array called Sales with Array values:

 sales[] = {CHEVVY, BMW , MERC, AUDI};

So how could I check that the sales[] has all the values of enum carBrand?

I'm trying to put it in a for loop as:

 for(int i = 0; i<sales.length;i++){
     if(carBrand.sales == sales[i]){
        return true;
     }
 return false;
 }

Body:
I would, personally, suggest using a list object rather than an Array where you are using such, however, this should work.

public static boolean checkArray(carBrand[] array) {
    for (carBrand c : carBrand.values()) {
        boolean found = false;
        for (carBrand a : array) {
            if (a == c) {
                found = true;
                break;
            }
        }
        if (!found) {
            return false;
        }
    }
    return true;
}

where the "array" parameter would be invoked as the sales object in your code.

This code will return false if not every enum value exists within your array.

Off-topic:
Things like this are actually all over the internet - here, google, even Bing (as garbo as Bing is), so searching before requesting help, probably a viable choice


问:
Convert string to FontAwesome icon and assign to icon field
I have a xml to save FontAwesome icon as string like

```<code> <Icon Name="faMainMenuFile">
      <Content>FolderOutline</Content>
      <Size>50</Size>
    </Icon>
</code>```

So I parse the xml file, I will get FolderOutline string

but assign the icon field is

```<code>faMainMenuFile.Icon = FontAwesome.WPF.FontAwesomeIcon.FolderOutline
</code>```

I try to create a function to convert string to FontAwesome.WPF.FontAwesomeIcon

```<code>public FontAwesome.WPF.FontAwesomeIcon GetUIFontAwesome(string strIcon)
    {
        if(strIcon == "Calculator") return FontAwesome.WPF.FontAwesomeIcon.Calculator;
        if (strIcon == "FolderOutline") return FontAwesome.WPF.FontAwesomeIcon.FolderOutline;

        return FontAwesome.WPF.FontAwesomeIcon.None;
    }
</code>```

But I will create giant list to handle this feature,

How can I fix it ?

答:
You can do this to  convert string to enum :</p>

```<code>public FontAwesome.WPF.FontAwesomeIcon GetUIFontAwesome(string strIcon)
{
    FontAwesome.WPF.FontAwesomeIcon item;
    if (Enum.TryParse(strIcon, out item))
        return item;
    else
        return FontAwesome.WPF.FontAwesomeIcon.None;
}
</code>```

Body:
I have a xml to save FontAwesome icon as string like

 <Icon Name="faMainMenuFile">
      <Content>FolderOutline</Content>
      <Size>50</Size>
    </Icon>

So I parse the xml file, I will get FolderOutline string

but assign the icon field is

faMainMenuFile.Icon = FontAwesome.WPF.FontAwesomeIcon.FolderOutline

I try to create a function to convert string to FontAwesome.WPF.FontAwesomeIcon

public FontAwesome.WPF.FontAwesomeIcon GetUIFontAwesome(string strIcon)
    {
        if(strIcon == "Calculator") return FontAwesome.WPF.FontAwesomeIcon.Calculator;
        if (strIcon == "FolderOutline") return FontAwesome.WPF.FontAwesomeIcon.FolderOutline;

        return FontAwesome.WPF.FontAwesomeIcon.None;
    }

But I will create giant list to handle this feature,

How can I fix it ?

Body:
You can do this to  convert string to enum :

public FontAwesome.WPF.FontAwesomeIcon GetUIFontAwesome(string strIcon)
{
    FontAwesome.WPF.FontAwesomeIcon item;
    if (Enum.TryParse(strIcon, out item))
        return item;
    else
        return FontAwesome.WPF.FontAwesomeIcon.None;
}


问:
How to eliminate if-else with same condition but different actions inside another if-else?
Suppose I have the code like following:

```<code>int age=(from user input);
int weight=(from user input);

if(age>60){
    if(weight>100){
        function1();
    }else if(weight<40){
        function2();
    }else{
        function3();
    }
}else if(age<20){
    if(weight>100){
        function4();
    }else if(weight<40){
        function5();
    }else{
        function6();
    }
}else{
    if(weight>100){
        function7();
    }else if(weight<40){
        function8();
    }else{
        function9();
    }
}
</code>```

the problem is that the code pattern:

```<code>if(weight>100){
    //do something different
}else if(weight<40){
    //do something different
}else{
    //do something different
}
</code>```

repeats as there are different ranges of age. And I can't enclose the inner if-else into a single function, because the things to do is different even through the condition is the same. Is there any way to modify this code so that the code pattern:

```<code>if(age>60){
    //do something different
}else if(age<20){
    //do something different
}else{
    //do something different
}
</code>```

and

```<code>if(weight>100){
    //do something different
}else if(weight<40){
    //do something different
}else{
    //do something different
}
</code>```

would appear once only?

答:
I didn't completely get your question but from what I see it seems you wan't to lose your redundant code so here is what I suggest.

Create a temp variable suppose

```<code>int ageGroup;
</code>```

and a function to compute the weight calculations where ageGroup is passed as a parameter

```<code>void CheckWeight(int ageGroup)
{
}
</code>```

You can further reduce the redundant code by creating another function to manage your work done in function 1-9 in switch conditions.

Your final code blocks will look like this :

```<code>if(age>60){
    CheckWeight(1);
}else if(age<20){
    CheckWeight(2)
}else{
    CheckWeight(3)
}

void CheckWeight(int ageGroup)
{
    if(weight>100){
       Compute(ageGroup,1);
    }else if(weight<40){
       Compute(ageGroup,2);
    }else{
       Compute(ageGroup,3);
    }
}

void Compute(int ageGroup,int weightGroup)
{
    switch(ageGroup)
    {
        case 1:
            switch(weightGroup)
            {
                case 1:
                    //func1;
                    break;
                case 2:
                    //func 2;
                    break;
                .
                .
            }
            break;
       case 2:
       .
       .
       .
    }
}
</code>```

This is the best I can come up with, there may be other implementations.

Body:
Suppose I have the code like following:

int age=(from user input);
int weight=(from user input);

if(age>60){
    if(weight>100){
        function1();
    }else if(weight<40){
        function2();
    }else{
        function3();
    }
}else if(age<20){
    if(weight>100){
        function4();
    }else if(weight<40){
        function5();
    }else{
        function6();
    }
}else{
    if(weight>100){
        function7();
    }else if(weight<40){
        function8();
    }else{
        function9();
    }
}

the problem is that the code pattern:

if(weight>100){
    //do something different
}else if(weight<40){
    //do something different
}else{
    //do something different
}

repeats as there are different ranges of age. And I can't enclose the inner if-else into a single function, because the things to do is different even through the condition is the same. Is there any way to modify this code so that the code pattern:

if(age>60){
    //do something different
}else if(age<20){
    //do something different
}else{
    //do something different
}

and

if(weight>100){
    //do something different
}else if(weight<40){
    //do something different
}else{
    //do something different
}

would appear once only?

Body:
I didn't completely get your question but from what I see it seems you wan't to lose your redundant code so here is what I suggest.

Create a temp variable suppose

int ageGroup;

and a function to compute the weight calculations where ageGroup is passed as a parameter

void CheckWeight(int ageGroup)
{
}

You can further reduce the redundant code by creating another function to manage your work done in function 1-9 in switch conditions.

Your final code blocks will look like this :

if(age>60){
    CheckWeight(1);
}else if(age<20){
    CheckWeight(2)
}else{
    CheckWeight(3)
}

void CheckWeight(int ageGroup)
{
    if(weight>100){
       Compute(ageGroup,1);
    }else if(weight<40){
       Compute(ageGroup,2);
    }else{
       Compute(ageGroup,3);
    }
}

void Compute(int ageGroup,int weightGroup)
{
    switch(ageGroup)
    {
        case 1:
            switch(weightGroup)
            {
                case 1:
                    //func1;
                    break;
                case 2:
                    //func 2;
                    break;
                .
                .
            }
            break;
       case 2:
       .
       .
       .
    }
}

This is the best I can come up with, there may be other implementations.


问:
How to use map function instead of for loop in javascript?
This is my array :

```<code>var filteredData = [{ id: 1, phoneno: '91888888888', sender: 'test' },{ id: 2, phoneno: '9199999999999', sender: 'hel' }]
</code>```

I use for loop

```<code>for (var i = 0; i < filteredData.length; i++) {
   if (filteredData[i].sender === test) {
       console.log('worked');
   }else{
       console.log('not worked');
   }
}
</code>```

How to exactly do this with map ? in javascript instead of for loop.

答:
```<code>filteredData.map(value => {
    if (value.sender === test) {
        console.log("worked");
    } else {
        console.log('not worked');
    }
});
</code>```

Body:
This is my array :

var filteredData = [{ id: 1, phoneno: '91888888888', sender: 'test' },{ id: 2, phoneno: '9199999999999', sender: 'hel' }]

I use for loop

for (var i = 0; i < filteredData.length; i++) {
   if (filteredData[i].sender === test) {
       console.log('worked');
   }else{
       console.log('not worked');
   }
}

How to exactly do this with map ? in javascript instead of for loop.