问:
PHP SQL Server: Trying to find most recent entry into a database by the column Date and Time
New to SQL and PHP so please be merciful and I see that this explanation is horrible so sorry in advance.

This query is returning false when ran. What I'm trying to do pull the most recent entry out of the database by the timestamp that is stored in the DateAndTime column that corresponds with the ID Row example.

My thinking is that I sort the rows by their dates and time then take the first row that corresponds to the ID.

```<code>$mostRecent_Query = "SELECT TOP 1 *
FROM locationFTable
ORDER BY DateAndTime DESC Where ID like $conID";

$resultTime = sqlsrv_query($conn, $mostRecent_Query);
</code>```

答:
```<code>$mostRecent_Query = "SELECT `location`, `DateAndTime` FROM locationFTable Where ID = $conI ORDER BY DateAndTime DESC";
</code>```

Body:
New to SQL and PHP so please be merciful and I see that this explanation is horrible so sorry in advance.

This query is returning false when ran. What I'm trying to do pull the most recent entry out of the database by the timestamp that is stored in the DateAndTime column that corresponds with the ID Row example.

My thinking is that I sort the rows by their dates and time then take the first row that corresponds to the ID.

$mostRecent_Query = "SELECT TOP 1 *
FROM locationFTable
ORDER BY DateAndTime DESC Where ID like $conID";

$resultTime = sqlsrv_query($conn, $mostRecent_Query);


来源: stackexchange

问:
How to add GENERATED BY DEFAULT AS IDENTITY in MySQL table?
I have a DB2 Table and i am trying to convert into  MySQL table . This is the DB2 table :

```<code>CREATE TABLE MY_TABLE (
  ID BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 1 INCREMENT BY 1 NO MAXVALUE NO CYCLE CACHE 100),
  ACTIVE SMALLINT NOT NULL,
  PRIMARY KEY (ID)
)#
</code>```

i have converted to MySQL like :

```<code>CREATE TABLE MY_TABLE (
  ID BIGINT ,
  ACTIVE SMALLINT NOT NULL,
  PRIMARY KEY (ID)
);
</code>```

and i am running one procedure

```<code>create procedure test_proced(
    in to_create bigint,
    out created bigint
)
begin
     set created = (select count(vnr.id) from MY_TABLE vnr);
    while (created < to_create) do
      insert into MY_TABLE (active) values(0);
      set created = created + 1;
    end while;
end;
</code>```

But after adding with above procedure on this table , I am getting some error like :

```<code>Caused by: java.sql.SQLException: Field 'id' doesn't have a default value
</code>```

Now i am suspecting the GENERATED BY DEFAULT AS IDENTITY . Is this error due to this problem ?  If it is , How to convert to corresponding MySQL Table ?

答: Adding AUTO INCREMENT to your primary key would fix this issue.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a DB2 Table and i am trying to convert into  MySQL table . This is the DB2 table :

CREATE TABLE MY_TABLE (
  ID BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 1 INCREMENT BY 1 NO MAXVALUE NO CYCLE CACHE 100),
  ACTIVE SMALLINT NOT NULL,
  PRIMARY KEY (ID)
)#

i have converted to MySQL like :

CREATE TABLE MY_TABLE (
  ID BIGINT ,
  ACTIVE SMALLINT NOT NULL,
  PRIMARY KEY (ID)
);

and i am running one procedure

create procedure test_proced(
    in to_create bigint,
    out created bigint
)
begin
     set created = (select count(vnr.id) from MY_TABLE vnr);
    while (created < to_create) do
      insert into MY_TABLE (active) values(0);
      set created = created + 1;
    end while;
end;

But after adding with above procedure on this table , I am getting some error like :

Caused by: java.sql.SQLException: Field 'id' doesn't have a default value

Now i am suspecting the GENERATED BY DEFAULT AS IDENTITY . Is this error due to this problem ?  If it is , How to convert to corresponding MySQL Table ?


问:
How to convert python(.py) file to unreadable code format
I have written python code and saved as program.py file.Now When i open "program.py" file it should be unreadable format.

Can anyone suggest me how to fix this issue.

答:
You can creat pyc file with compileall:

Put your python files in a folder and run the command in this folder:(Source)

```<code>python -m compileall .
</code>```

This command will produce a pyc file in __pycache__ folder. You can use this file like other python files:(Source)

```<code>python myfile.pyc
</code>```

Body:
You can creat pyc file with compileall:

Put your python files in a folder and run the command in this folder:(Source)

python -m compileall .

This command will produce a pyc file in __pycache__ folder. You can use this file like other python files:(Source)

python myfile.pyc


问:
Old value kept on ngModel change
Dealing with a table which need a filter by data, I've created the following screen:

What I need is to remove values outside the date start criteria of the filter so I've done this on my EsightComponent:

```<code>startDateChange($event, dt, col) {
  this.loading = true;
  this.eSightEndSubscription = this.eSightService.getByContractId(this.contractId).subscribe(
    res => {
      const filterResults = this.reads.filter((read) => {
        const iteratorDate = new Date(20 + read.timestamp.slice(-2), read.timestamp.slice(0, 2) - 1, 1);
        console.log(this.startDateFilter);
        return iteratorDate <= this.startDateFilter;
      }, this);

      this.processRightAnswer(filterResults);
    },
    error => {
      console.log('ERROR');
    },
    () => {
      this.loading = false;
    });
}
</code>```

And this is my view:

```<code><h4>Lecturas eSight <small>contrato {{ contractId }}</small></h4>

<p-calendar dateFormat="mm/yy" [(ngModel)]="startDateFilter" (onBlur)="startDateChange($event, dt, col)"></p-calendar>
<p-calendar [(ngModel)]="endDateFilter" (change)="startDateChange($event, dt, col)"></p-calendar>

<p-dataTable [value]="reads" [rows]="30" [paginator]="true" [loading]="loading" selectionMode="single" scrollable="true" #dt>
  <ng-container *ngFor="let col of cols; let i = index;">
    <p-column [field]="col.field" [header]="col.header" *ngIf="i === 0" [style]="{ 'width': '170px' }">
    </p-column>
    <p-column [field]="col.field" [header]="col.header" *ngIf="col.header.length <= 10" [style]="{ 'width': '55px' }"></p-column>
    <p-column [field]="col.field" [header]="col.header" *ngIf="col.header.length > 10" [style]="{ 'width': '170px' }"></p-column>
  </ng-container>
</p-dataTable>

<button class="btn btn-warning" (click)="onReturn()">Atrás</button>
</code>```

Based on tho way data binding principle, this.startDateFilter should catch changes on it, but it doesn't. If I select a date on the calendar, it always displays the previous value, not the selected new one. That is seen on console.log(this.startDateFilter) line.

I've checked I could use ngOnChanges to catch changes and to have access to both old and new values, but this hook just works for @Input() values and this is not my case.

I wish to retrieve the value selected by the user and not an old one.

Thanks.

答:
It's happens because ngModel triggers after change datection, but you are watching for blur, that fires before detection

You should getting current value from $event, not from model value.
Something line

```<code>$event.value
</code>```

Title: Old value kept on ngModel change

Body:
Dealing with a table which need a filter by data, I've created the following screen:

What I need is to remove values outside the date start criteria of the filter so I've done this on my EsightComponent:

startDateChange($event, dt, col) {
  this.loading = true;
  this.eSightEndSubscription = this.eSightService.getByContractId(this.contractId).subscribe(
    res => {
      const filterResults = this.reads.filter((read) => {
        const iteratorDate = new Date(20 + read.timestamp.slice(-2), read.timestamp.slice(0, 2) - 1, 1);
        console.log(this.startDateFilter);
        return iteratorDate <= this.startDateFilter;
      }, this);

      this.processRightAnswer(filterResults);
    },
    error => {
      console.log('ERROR');
    },
    () => {
      this.loading = false;
    });
}

And this is my view:

Lecturas eSight contrato {{ contractId }}

  <ng-container *ngFor="let col of cols; let i = index;">

    <p-column [field]="col.field" [header]="col.header" *ngIf="col.header.length <= 10" [style]="{ 'width': '55px' }">

 10" [style]="{ 'width': '170px' }">

  </ng-container>

<button class="btn btn-warning" (click)="onReturn()">Atrás</button>

Based on tho way data binding principle, this.startDateFilter should catch changes on it, but it doesn't. If I select a date on the calendar, it always displays the previous value, not the selected new one. That is seen on console.log(this.startDateFilter) line.

I've checked I could use ngOnChanges to catch changes and to have access to both old and new values, but this hook just works for @Input() values and this is not my case.

I wish to retrieve the value selected by the user and not an old one.

Thanks.

Body:
It's happens because ngModel triggers after change datection, but you are watching for blur, that fires before detection

You should getting current value from $event, not from model value.
Something line

$event.value


问:
How do I make sure the line that appears under the first column is moved to the second column on top
I have created a responsive masonry to display some quotes on the page using css inline-block (ref - http://w3bits.com/css-masonry/).

The problem I am having is that somehow the top border that belongs to the 1st element on the 2nd and 3rd row are appearing at the end of the 1st and 2nd row respectively.

See my fiddle here for preview - https://fiddle.jshell.net/8ntahynh/

/*----------------- Testimonials CSS -----------------*/

.masonry {
  margin: 0 0;
  padding: 0;
  font-size: .85em;
  -moz-column-count: 3;
  -webkit-column-count: 3;
  column-count: 3;
}

.item {
  display: inline-block;
  background: #fff;
  padding: 1em;
  margin: 0 0 1.5em;
  width: 100%;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-shadow: 2px 2px 4px 2px #ccc;
}

.testimonial-img,
.center-cropped {
  height: 200px;
  width: 200px;
  object-fit: cover;
  object-position: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="masonry">
    <div class="item">
      <div class="testimonial-section">
        <blockquote>
          <i class="fa fa-quote-left" aria-hidden="true"></i>My new door looks a lot like my former front door. I got married and raised my children in that house. Good memories! The front door was made of solid oak and we could open the upper part, which
          we did when we talked to our neighbours for example. It was a pity that we had to move out of that house.
          <i class="fa fa-quote-right" aria-hidden="true"></i>
          <div>
            <span class="footer-source">-
                            <b>Mw. Louwen | </b>Resident at Pieter van Foreest Weidevogelhof in
                            <cite title="Source Title"> Pijnacker</cite>
                        </span>
          </div>
        </blockquote>

        <img src="https://s3-eu-central-1.amazonaws.com/truedoors/wp-content/uploads/truedoors-thestorybehindthedoor-community-quote-1013.jpg" class="center-cropped" alt="Responsive image">
      </div>
    </div></code>```

答:
The reason being is that you are using CSS columns to divide up the content. Part of the next column (the top of the box-shadow of the first item) is being displayed at the bottom of the previous column.

Add in some top margin to allow for this extra shadow:

```<code>.item {
  ...
  margin: .2em 0 1.5em;
  ...
}
</code>```

Check this out:
https://fiddle.jshell.net/v1r1g05p/

Body:
I have created a responsive masonry to display some quotes on the page using css inline-block (ref - http://w3bits.com/css-masonry/).

The problem I am having is that somehow the top border that belongs to the 1st element on the 2nd and 3rd row are appearing at the end of the 1st and 2nd row respectively.

See my fiddle here for preview - https://fiddle.jshell.net/8ntahynh/

/*----------------- Testimonials CSS -----------------*/

.masonry {
  margin: 0 0;
  padding: 0;
  font-size: .85em;
  -moz-column-count: 3;
  -webkit-column-count: 3;
  column-count: 3;
}

.item {
  display: inline-block;
  background: #fff;
  padding: 1em;
  margin: 0 0 1.5em;
  width: 100%;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-shadow: 2px 2px 4px 2px #ccc;
}

.testimonial-img,
.center-cropped {
  height: 200px;
  width: 200px;
  object-fit: cover;
  object-position: center;
}

          My new door looks a lot like my former front door. I got married and raised my children in that house. Good memories! The front door was made of solid oak and we could open the upper part, which
          we did when we talked to our neighbours for example. It was a pity that we had to move out of that house.

            -
                            Mw. Louwen | Resident at Pieter van Foreest Weidevogelhof in
                             Pijnacker

Body:
The reason being is that you are using CSS columns to divide up the content. Part of the next column (the top of the box-shadow of the first item) is being displayed at the bottom of the previous column.

Add in some top margin to allow for this extra shadow:

.item {
  ...
  margin: .2em 0 1.5em;
  ...
}

Check this out:
https://fiddle.jshell.net/v1r1g05p/


问:
Install laravel in shared hosting website's subfolder
im trying to install Laravel in my shared hosting website's(which is not laravel) subfolder.
for example in: example.com/dev

Structure:

```<code>->laravel
  ->app
  ->bootstrap
->public_html
  ...example.com folders & files
  ->dev
    ->css
    ->js
    ->.htacess
    ->index.php
    ... other Laravel public files
</code>```

My example.com/dev/index.php looks like this:

```<code>... laravel codes

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| our application. We just need to utilize it! We'll simply require it
| into the script here so that we don't have to worry about manual
| loading any of our classes later on. It feels great to relax.
|
*/

require __DIR__.'/../../laravel/bootstrap/autoload.php';

/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let us turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight our users.
|
*/

$app = require_once __DIR__.'/../../laravel/bootstrap/app.php';

... laravel codes
</code>```

Problem:
When i try to enter http://example.com/dev/ browser throws error:

This page isn’t working

mysite.com didn’t send any data.

ERR_EMPTY_RESPONSE

THERE ARE NO ANY INFORMATION/SOLUTION FOR THIS PROBLEM IN THE INTERNET.

ANY SOLUTION?

答:
From your text I assume you want call Laravel via http://example.com/dev/ If you hoster allows symlinks, you can try this.

```<code>-> laravel
  -> app
  -> ...
  -> public // symlinked to public_html/example.com/dev
  -> ...

-> public_html
  -> example.com folders & files
    -> dev // This is a symlink to laravel/public
</code>```

A better approach in my opinion would be to create a subdomain and call Laravel like http://dev.example.com. It depends on your hoster how you can do this.

Body:
im trying to install Laravel in my shared hosting website's(which is not laravel) subfolder.
for example in: example.com/dev

Structure:

->laravel
  ->app
  ->bootstrap
->public_html
  ...example.com folders & files
  ->dev
    ->css
    ->js
    ->.htacess
    ->index.php
    ... other Laravel public files

My example.com/dev/index.php looks like this:

... laravel codes

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| our application. We just need to utilize it! We'll simply require it
| into the script here so that we don't have to worry about manual
| loading any of our classes later on. It feels great to relax.
|
*/

require __DIR__.'/../../laravel/bootstrap/autoload.php';

/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let us turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight our users.
|
*/

$app = require_once __DIR__.'/../../laravel/bootstrap/app.php';

... laravel codes

Problem:
When i try to enter http://example.com/dev/ browser throws error:

This page isn’t working

mysite.com didn’t send any data.

ERR_EMPTY_RESPONSE

THERE ARE NO ANY INFORMATION/SOLUTION FOR THIS PROBLEM IN THE INTERNET.

ANY SOLUTION?

Body:
From your text I assume you want call Laravel via http://example.com/dev/ If you hoster allows symlinks, you can try this.

-> laravel
  -> app
  -> ...
  -> public // symlinked to public_html/example.com/dev
  -> ...

-> public_html
  -> example.com folders & files
    -> dev // This is a symlink to laravel/public

A better approach in my opinion would be to create a subdomain and call Laravel like http://dev.example.com. It depends on your hoster how you can do this.


问:
Handmade Estimator modifies parameters in __init__?
I am preparing a tailored preprocessing phase which is suppose to become part of a sklearn.pipeline.Pipeline. Here's the code of the preprocessor:

```<code>import string
from nltk import wordpunct_tokenize
from nltk.stem.snowball import SnowballStemmer
from nltk import sent_tokenize
from sklearn.base import BaseEstimator, TransformerMixin
from . import stopwords

class NLTKPreprocessor(BaseEstimator, TransformerMixin):
    def __init__(self, stopwords=stopwords.STOPWORDS_DE,
                 punct=string.punctuation,
                 lower=True, strip=True, lang='german'):
        """
        Based on:
        https://bbengfort.github.io/tutorials/2016/05/19/text-classification-nltk-sckit-learn.html
        """

        self.lower = lower
        self.strip = strip
        self.stopwords = set(stopwords)
        self.punct = set(punct)
        self.stemmer = SnowballStemmer(lang)
        self.lang = lang

    def fit(self, X, y=None):
        return self

    def inverse_transform(self, X):
        return [" ".join(doc) for doc in X]

    def transform(self, X):
        return [
            list(self.tokenize(doc)) for doc in X
        ]

    def tokenize(self, document):
        # Break the document into sentences
        for sent in sent_tokenize(document, self.lang):
            for token in wordpunct_tokenize(sent):
                # Apply preprocessing to the token
                token = token.lower() if self.lower else token
                token = token.strip() if self.strip else token
                token = token.strip('_') if self.strip else token
                token = token.strip('*') if self.strip else token

                # If stopword, ignore token and continue
                if token in self.stopwords:
                    continue

                # If punctuation, ignore token and continue
                if all(char in self.punct for char in token):
                    continue

                # Lemmatize the token and yield
                # lemma = self.lemmatize(token, tag)
                stem = self.stemmer.stem(token)
                yield stem
</code>```

Next, here is the pipeline I construct:

```<code>pipeline = Pipeline(
    [
        ('preprocess', nltkPreprocessor),
        ('vectorize', TfidfVectorizer(tokenizer=identity, preprocessor=None, lowercase=False)),
        ('clf', SGDClassifier(max_iter=1000, tol=1e-3))
    ]
)
</code>```

This all works nicely for a single pass; for example pipeline.fit(X,y) works nicely. However, when putting this pipeline inside a grid search

```<code>parameters = {
    'vectorize__use_idf': (True, False),
    'vectorize__max_df': np.arange(0.8, 1.01 ,0.05),
    'vectorize__smooth_idf': (True, False),
    'vectorize__sublinear_tf': (True, False),
    'vectorize__norm': ('l1', 'l2'),
    'clf__loss':  ('hinge', 'log', 'modified_huber', 'squared_hinge', 'perceptron'),
    'clf__alpha': (0.00001, 0.000001),
    'clf__penalty': ('l1', 'l2', 'elasticnet')
}
grid_search = GridSearchCV(pipeline, parameters, n_jobs=-1, verbose=1)
grid_search.fit(X_train, y_train)
</code>```

I get the following warning:

```<code>/Users/user/anaconda3/envs/myenv/lib/python3.6/site-packages/sklearn/base.py:115: DeprecationWarning: Estimator NLTKPreprocessor modifies parameters in __init__. This behavior is deprecated as of 0.18 and support for this behavior will be removed in 0.20.
  % type(estimator).__name__, DeprecationWarning)
</code>```

I don't understand what should be changed/fixed in the implementation. How can I maintain the functionality and remove the warning?

答:
I read the code under https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/base.py

Could reproduce the warning message. They went away after two changes:

frozenset rather than set. As a set considered mutable and as such will turn out to be different after a copy.

Initializing self.stemmer in the tokenize method rather than in __init__.

Body:
I am preparing a tailored preprocessing phase which is suppose to become part of a sklearn.pipeline.Pipeline. Here's the code of the preprocessor:

import string
from nltk import wordpunct_tokenize
from nltk.stem.snowball import SnowballStemmer
from nltk import sent_tokenize
from sklearn.base import BaseEstimator, TransformerMixin
from . import stopwords

class NLTKPreprocessor(BaseEstimator, TransformerMixin):
    def __init__(self, stopwords=stopwords.STOPWORDS_DE,
                 punct=string.punctuation,
                 lower=True, strip=True, lang='german'):
        """
        Based on:
        https://bbengfort.github.io/tutorials/2016/05/19/text-classification-nltk-sckit-learn.html
        """

        self.lower = lower
        self.strip = strip
        self.stopwords = set(stopwords)
        self.punct = set(punct)
        self.stemmer = SnowballStemmer(lang)
        self.lang = lang

    def fit(self, X, y=None):
        return self

    def inverse_transform(self, X):
        return [" ".join(doc) for doc in X]

    def transform(self, X):
        return [
            list(self.tokenize(doc)) for doc in X
        ]

    def tokenize(self, document):
        # Break the document into sentences
        for sent in sent_tokenize(document, self.lang):
            for token in wordpunct_tokenize(sent):
                # Apply preprocessing to the token
                token = token.lower() if self.lower else token
                token = token.strip() if self.strip else token
                token = token.strip('_') if self.strip else token
                token = token.strip('*') if self.strip else token

                # If stopword, ignore token and continue
                if token in self.stopwords:
                    continue

                # If punctuation, ignore token and continue
                if all(char in self.punct for char in token):
                    continue

                # Lemmatize the token and yield
                # lemma = self.lemmatize(token, tag)
                stem = self.stemmer.stem(token)
                yield stem

Next, here is the pipeline I construct:

pipeline = Pipeline(
    [
        ('preprocess', nltkPreprocessor),
        ('vectorize', TfidfVectorizer(tokenizer=identity, preprocessor=None, lowercase=False)),
        ('clf', SGDClassifier(max_iter=1000, tol=1e-3))
    ]
)

This all works nicely for a single pass; for example pipeline.fit(X,y) works nicely. However, when putting this pipeline inside a grid search

parameters = {
    'vectorize__use_idf': (True, False),
    'vectorize__max_df': np.arange(0.8, 1.01 ,0.05),
    'vectorize__smooth_idf': (True, False),
    'vectorize__sublinear_tf': (True, False),
    'vectorize__norm': ('l1', 'l2'),
    'clf__loss':  ('hinge', 'log', 'modified_huber', 'squared_hinge', 'perceptron'),
    'clf__alpha': (0.00001, 0.000001),
    'clf__penalty': ('l1', 'l2', 'elasticnet')
}
grid_search = GridSearchCV(pipeline, parameters, n_jobs=-1, verbose=1)
grid_search.fit(X_train, y_train)

I get the following warning:

/Users/user/anaconda3/envs/myenv/lib/python3.6/site-packages/sklearn/base.py:115: DeprecationWarning: Estimator NLTKPreprocessor modifies parameters in __init__. This behavior is deprecated as of 0.18 and support for this behavior will be removed in 0.20.
  % type(estimator).__name__, DeprecationWarning)

I don't understand what should be changed/fixed in the implementation. How can I maintain the functionality and remove the warning?


问:
Algorithm - Finding all of the connectors in a graph
Definition: In an undirected graph, vertex v is a connector if there are at least two other vertices x and w for which every path between x and w goes through v.

I am using an adjacency linked list to store my graph.

So my first thought was "duh, well a vertex is a connector if it is the only neighbor to a vertex."

And although that works I realize now that there are other cases where a vertex is a connector even if it does not have that quality.

I have come up with a solution where I check every path of a vertex's neighbor to see if I can reach every other vertex and as you can probably imagine this will be VERY time consuming.

I've been trying to come up with a quicker algorithm but am unable to do so. Can anyone give me a hint for how I should go about solving this problem?

答:
Suppose your graph is connected. if you remove a connector vertex, the graph must be disconnected. Then, count number of component of a graph using dfs or bfs in linear time. If the number of component changed, it means the removed vertex or node is a connector.

You can run this algorithm for each vertex. Time complexity of this algorithm is O(n^2).


问:
iframe google translate code?
I am using following code to add a google translator to my page header. But if I move it inside page content its not displaying anything. How to get the same translator box in iframe.

```<code><div id="google_translate_element" class="langSwitch"></div>
<script>
function googleTranslateElementInit() {
  new google.translate.TranslateElement({
    pageLanguage: 'en',
    includedLanguages: 'af,sq,ar,hy,az,eu,be,bg,ca,zh-CN,zh-TW,hr,cs,da,nl,en,et,tl,fi,fr,gl,ka,de,el,ht,iw,hi,hu,is,id,ga,it,ja,ko,la,lv,lt,mk,ms,mt,no,fa,pl,pt,ro,ru,sr,sk,sl,es,sw,sv,th,tr,uk,ur,vi,cy,yi',
    gaTrack: true,
    gaId: 'UA-2585500-1',
    layout: google.translate.TranslateElement.InlineLayout.SIMPLE
  }, 'google_translate_element');
}
</script>
<script src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
</code>```

Thanks

答: Check your

ContentLicense: CC BY-SA 2.5

Title: iframe google translate code?

Body:
I am using following code to add a google translator to my page header. But if I move it inside page content its not displaying anything. How to get the same translator box in iframe.

Thanks

Body: Check your <script src, it's //translate.google.com instead of http://translate.google.com/.


问:
How to call function in angular2 using typescript?
I am trying to call trimObj inside ngOnit but throws error , what is correct implementation when you use function in angular2 using typescript. New to typescript I will appreciate the help.

app.component.ts

```<code>    export class StreamComponent implements OnInit {
        displayedColumns = ['ticketNum', "assetID", "severity", "riskIndex", "riskValue", "ticketOpened", "lastModifiedDate", "eventType"];
        dataSource: MatTableDataSource<Element[]>;
        socket = io();
        constructor(private streamService: StreamService) {};
        ngOnInit() {
        this.socket.on('newMessage', (event) => {
                         console.log('New Event', event);
                          let data = trimObj(event);
                          this.dataSource.data.push(data);
                           this.dataSource.data = [...this.dataSource.data]
                          console.log("DATA",this.dataSource.filteredData);
                       });
                });
        }
        trimObj(obj) => {
              var neededKeys = ['ticketNum', "assetID", "severity", "riskIndex", "riskValue", "ticketOpened", "lastModifiedDate", "eventType"];
              var newObj = {};
              neededKeys.forEach(function (key) {
                newObj[key] = obj[key];
              });
              return newObj;
            }
    }

export interface Element {
    ticketNum: number;
    ticketOpened: number;
    eventType: string;
    riskIndex: string;
    riskValue: number;
    severity: string;
    lastModifiedDate: number;
    assetID: string;
}
</code>```

Error

```<code>ERROR in app.component.ts(29,17): error TS1144: '{' or ';' expected.
app.component.ts(29,20): error TS1068: Unexpected token. A constructor, method, accessor, or property was expected.
app.component.ts(38,1): error TS1128: Declaration or statement expected.
</code>```

答:
just call it with this

```<code>this.trimObj(event);
</code>```

You have actually other syntax issues. This is your corrected code:

```<code>export class StreamComponent implements OnInit {
    displayedColumns = [
        'ticketNum',
        'assetID',
        'severity',
        'riskIndex',
        'riskValue',
        'ticketOpened',
        'lastModifiedDate',
        'eventType'
    ];

    dataSource: MatTableDataSource<Element[]>;

    socket = io();

    constructor(private streamService: StreamService) {}

    ngOnInit() {
        this.socket.on('newMessage', event => {
            console.log('New Event', event);
            const data = this.trimObj(event);
            this.dataSource.data.push(data);
            this.dataSource.data = [...this.dataSource.data];
            console.log('DATA', this.dataSource.filteredData);
        });
    }

    trimObj(obj): Element {
        const neededKeys = [
            'ticketNum',
            'assetID',
            'severity',
            'riskIndex',
            'riskValue',
            'ticketOpened',
            'lastModifiedDate',
            'eventType'
        ];
        const newObj: Element = <any>{};
        neededKeys.forEach(function(key) {
            newObj[key] = obj[key];
        });
        return newObj;
    }
}
</code>```

Body:
I am trying to call trimObj inside ngOnit but throws error , what is correct implementation when you use function in angular2 using typescript. New to typescript I will appreciate the help.

app.component.ts

    export class StreamComponent implements OnInit {
        displayedColumns = ['ticketNum', "assetID", "severity", "riskIndex", "riskValue", "ticketOpened", "lastModifiedDate", "eventType"];
        dataSource: MatTableDataSource<Element[]>;
        socket = io();
        constructor(private streamService: StreamService) {};
        ngOnInit() {
        this.socket.on('newMessage', (event) => {
                         console.log('New Event', event);
                          let data = trimObj(event);
                          this.dataSource.data.push(data);
                           this.dataSource.data = [...this.dataSource.data]
                          console.log("DATA",this.dataSource.filteredData);
                       });
                });
        }
        trimObj(obj) => {
              var neededKeys = ['ticketNum', "assetID", "severity", "riskIndex", "riskValue", "ticketOpened", "lastModifiedDate", "eventType"];
              var newObj = {};
              neededKeys.forEach(function (key) {
                newObj[key] = obj[key];
              });
              return newObj;
            }
    }

export interface Element {
    ticketNum: number;
    ticketOpened: number;
    eventType: string;
    riskIndex: string;
    riskValue: number;
    severity: string;
    lastModifiedDate: number;
    assetID: string;
}

Error

ERROR in app.component.ts(29,17): error TS1144: '{' or ';' expected.
app.component.ts(29,20): error TS1068: Unexpected token. A constructor, method, accessor, or property was expected.
app.component.ts(38,1): error TS1128: Declaration or statement expected.

Body:
just call it with this

this.trimObj(event);

You have actually other syntax issues. This is your corrected code:

export class StreamComponent implements OnInit {
    displayedColumns = [
        'ticketNum',
        'assetID',
        'severity',
        'riskIndex',
        'riskValue',
        'ticketOpened',
        'lastModifiedDate',
        'eventType'
    ];

    dataSource: MatTableDataSource<Element[]>;

    socket = io();

    constructor(private streamService: StreamService) {}

    ngOnInit() {
        this.socket.on('newMessage', event => {
            console.log('New Event', event);
            const data = this.trimObj(event);
            this.dataSource.data.push(data);
            this.dataSource.data = [...this.dataSource.data];
            console.log('DATA', this.dataSource.filteredData);
        });
    }

    trimObj(obj): Element {
        const neededKeys = [
            'ticketNum',
            'assetID',
            'severity',
            'riskIndex',
            'riskValue',
            'ticketOpened',
            'lastModifiedDate',
            'eventType'
        ];
        const newObj: Element = <any>{};
        neededKeys.forEach(function(key) {
            newObj[key] = obj[key];
        });
        return newObj;
    }
}


答:
Your SQL query is wrong, the WHERE... clause must appear before the ORDER BY... clause. For example:

```<code>SELECT TOP 1 *
FROM locationFTable
WHERE ID like $conID
ORDER BY DateAndTime DESC
</code>```

Note: You should test your queries before putting them into your code. SQL Server Management Studio is perfect for this task.

Bonus Note: The ID column is likely an int so I am guessing that LIKE is the wrong operator to use, perhaps you meant to use = instead?

Bonus Bonus Note: Go and read up about SQL injection as your code is very likely vulnerable to that security risk.

Title: PHP SQL Server: Trying to find most recent entry into a database by the column Date and Time

Body:
Your SQL query is wrong, the WHERE... clause must appear before the ORDER BY... clause. For example:

SELECT TOP 1 *
FROM locationFTable
WHERE ID like $conID
ORDER BY DateAndTime DESC

Note: You should test your queries before putting them into your code. SQL Server Management Studio is perfect for this task.

Bonus Note: The ID column is likely an int so I am guessing that LIKE is the wrong operator to use, perhaps you meant to use = instead?

Bonus Bonus Note: Go and read up about SQL injection as your code is very likely vulnerable to that security risk.


答:
You can use idxmax with axis=1 to find the column with the greatest value on each row:

```<code>1 is5
2 is5
3 is5
4 is5
5 is5
</code>```

To create the new column 'Max', use df['Max'] = df.idxmax(axis=1).

To find the row index at which the maximum value occurs in each column, use df.idxmax() (or equivalently df.idxmax(axis=0)).

For 2nd highest, you can use
df.apply(lambda x: df.index[x.argsort()[::-1][1]], axis=1)

Title: Returning a Column Header which Corresponds to a Maximum Value in a Row

Body:
I have a dataframe that looks like this:

case    inc_date    is1     is5     is10    im1     im5     im10
686     6/8/1972    0.141   0.300   0.149   0.134   0.135   0.142
950     6/1/1945    0.160   0.345   0.172   0.088   0.096   0.138
1005    10/16/1945  0.164   0.261   0.151   0.131   0.261   0.133
1005    11/12/1947  0.146   0.310   0.182   0.112   0.129   0.121
1180    10/9/1945   0.159   0.278   0.134   0.141   0.138   0.150

I would like to find out the maximum(s) in each row and return the column name for which the value(s) are the maximum. For example, for the above dataframe, it'd return:

686 is5
950 is5
1005 is5, im5
1005 is5
1180 is5

Body:
You can use idxmax with axis=1 to find the column with the greatest value on each row:

1 is5
2 is5
3 is5
4 is5
5 is5

To create the new column 'Max', use df['Max'] = df.idxmax(axis=1).

To find the row index at which the maximum value occurs in each column, use df.idxmax() (or equivalently df.idxmax(axis=0)).

For 2nd highest, you can use
df.apply(lambda x: df.index[x.argsort()[::-1][1]], axis=1)


问:
Is there some workaround to create “deny” rules for Google Cloud Firewall
Docs about Google Cloud Networks and Firewalls clearly says:

Firewall rules are only "allow" rules. You cannot create "deny" rules.

But we still need those deny-rules, and I believe this is an essential option. Amazon’s VPC can do this.

So, are there some workarounds to create “deny” rules?

答: Cloud Platform currently allows creating deny rules. It is easily visible on the Console UI when creating a rule on 'Action on match' (Allow or Deny), and you'll find several examples in this documentation.</p>


问:
Is it better to return null or empty collection?
That's kind of a general question (but I'm using C#), what's the best way (best practice), do you return null or empty collection for a method that has a collection as a return type ?</p>

答:
I call it my billion-dollar mistake…At that time, I was designing the first comprehensive type system for references in an object-oriented language. My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn’t resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.
  – Tony Hoare, inventor of ALGOL W.

See here for an elaborate shit storm about null in general. I do not agree with the statement that undefined is another null, but it is still worth reading. And it explains, why you should avoid null at all and not just in the case you have asked. The essence is, that null is in any language a special case. You have to think about null as an exception. undefined is different in that way, that code dealing with undefined behavior is in most cases just a bug. C and most other languages have also undefined behavior but most of them have no identifier for that in the language.


问:
Creating a new column with 0 and 1 values based on regex result
My dataframe has values:

```<code>data_df

0         student
1         sample text
2         student
3         no students
4         sample texting
5         random sample
</code>```

I use regex to extract rows with word 'student' and my result is as below:

```<code>regexdf
0         student
2         student
</code>```

I aim to create a new column in the main dataframe with 0 and 1 values. i.e. row 0 should be 1, row 5 should have zero.(As the 'regexdf' has 'student' in row 0 and 2) How do I match the indexes in both and create a column?

答:
You can also do

```<code>df['bool'] = df[1].eq('student').astype(int)
</code>```

or

```<code>df['bool'] = df[1].str.match(r'(student)\b').astype(int)

                1  bool
0         student     1
1     sample text     0
2         student     1
3     no students     0
4  sample texting     0
5   random sample     0
</code>```

If you want a new dataframe then

```<code>ndf = df[df[1].eq('student')].copy()
</code>```

Body:
My dataframe has values:

data_df

0         student
1         sample text
2         student
3         no students
4         sample texting
5         random sample

I use regex to extract rows with word 'student' and my result is as below:

regexdf
0         student
2         student

I aim to create a new column in the main dataframe with 0 and 1 values. i.e. row 0 should be 1, row 5 should have zero.(As the 'regexdf' has 'student' in row 0 and 2) How do I match the indexes in both and create a column?

Body:
You can also do

df['bool'] = df[1].eq('student').astype(int)

or

df['bool'] = df[1].str.match(r'(student)\b').astype(int)

                1  bool
0         student     1
1     sample text     0
2         student     1
3     no students     0
4  sample texting     0
5   random sample     0

If you want a new dataframe then

ndf = df[df[1].eq('student')].copy()


问:
How do i display total item in cart just behind cart icon
Am new to css i just got few during reseach but in achievement i want the total item in cart to display just behind my cart icon like this:

My code:

```<code><?php
if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
echo "<style type='text/css'>
    .cart {
        background-image: url('cart.png');
    }

    </style>";
echo "<div class='cart'></div>";
} else {
  $totalquantity = 0;
foreach($_SESSION['cart_array'] as $each_item) {
             $totalquantity += $each_item[quantity];
            }
echo "<div class='cart'>$totalquantity</div>";
}
?>
</code>```

Big thanks in advance

答:
This is similar to what Bootstrap uses

Using the css pseudo selector :empty allows it to auto collapse when there is no content

this way in your php you can always render the "<?php $totalquantity;?>"

.container {
  background-color: #000;
  padding: 5px;
  width: 200px;
  position: relative;
}

.cart {
  background-image: url('http://www.pvhc.net/img180/xewlwqfroahrisfwokkc.png');
  background-size: contain;
  background-repeat: no-repeat;
  background-color: darkgreen;
  width: 50px;
  height: 50px;
  border: 1px solid #fff;
  outline: 3px solid #8174f7;
  position: absolute ;
  right:8px;
  top:8px;
}

.badge {
  position: absolute;
  left: -15px;
  bottom: -15px;
  font-weight: 700;
  font-family: sans-serif;
  font-size: 20px;
  color: #fff;
  background-color: green;
  border: 2px solid #fff;
  padding: 3px;
  width: 20px;
  height: 20px;
  text-align: center;
}

.badge:empty {
  display: none;
}

.content {
  background-color: #fff;
  color: #000;
  padding:8px;
  text-align:center;
  margin-top:62px;
}

.red {
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class='cart'>
    <span class="badge">4</span>
  </div>
  <div class="content">
    Tot. odd: <span class="red">40.04</span>
  </div>
</div></code>```

Your PHP code may look something like this

```<code><?php

echo "<style>... the styles above</style>" ;
/*
load your styles before content is rendered
they should be loaded in a a separate css file but that's up to you

*/

$totalquantity = 0;
if(!isset($_SESSION["cart_array"]) ) {
      foreach($_SESSION['cart_array'] as $each_item) {
         $totalquantity += $each_item[quantity];
        }
?>
<div class='cart'><?php echo $totalquantity;?></div>
<?php }?>
</code>```

Body:
Am new to css i just got few during reseach but in achievement i want the total item in cart to display just behind my cart icon like this:

My code:

<?php
if(!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
echo "";
echo "

";
} else {
  $totalquantity = 0;
foreach($_SESSION['cart_array'] as $each_item) {
             $totalquantity += $each_item[quantity];
            }
echo "
$totalquantity
";
}
?>

Big thanks in advance

Body:
This is similar to what Bootstrap uses

Using the css pseudo selector :empty allows it to auto collapse when there is no content

this way in your php you can always render the "<span class="badge"><?php $totalquantity;?></span>"

.container {
  background-color: #000;
  padding: 5px;
  width: 200px;
  position: relative;
}

.cart {
  background-image: url('http://www.pvhc.net/img180/xewlwqfroahrisfwokkc.png');
  background-size: contain;
  background-repeat: no-repeat;
  background-color: darkgreen;
  width: 50px;
  height: 50px;
  border: 1px solid #fff;
  outline: 3px solid #8174f7;
  position: absolute ;
  right:8px;
  top:8px;
}

.badge {
  position: absolute;
  left: -15px;
  bottom: -15px;
  font-weight: 700;
  font-family: sans-serif;
  font-size: 20px;
  color: #fff;
  background-color: green;
  border: 2px solid #fff;
  padding: 3px;
  width: 20px;
  height: 20px;
  text-align: center;
}

.badge:empty {
  display: none;
}

.content {
  background-color: #fff;
  color: #000;
  padding:8px;
  text-align:center;
  margin-top:62px;
}

.red {
  color: red;
}

<div class="container">
  <div class='cart'>
    <span class="badge">4</span>
  </div>
  <div class="content">
    Tot. odd: <span class="red">40.04</span>
  </div>
</div>

Your PHP code may look something like this

<?php

echo "<style>... the styles above</style>" ;
/*
load your styles before content is rendered
they should be loaded in a a separate css file but that's up to you

*/

$totalquantity = 0;
if(!isset($_SESSION["cart_array"]) ) {
      foreach($_SESSION['cart_array'] as $each_item) {
         $totalquantity += $each_item[quantity];
        }
?>
<div class='cart'><?php echo $totalquantity;?></div>
<?php }?>


问:
How to apply Angular ErrorHandler accross modules
Here's my Angular 4 app module:

```<code>@NgModule({
declarations: [
    AppComponent
],
providers: [
    QuickBoardListService,
    {provide: ErrorHandler, useClass: FrontExceptionHandler}
],
imports: [
    BrowserModule,
    CommonModule,
    FormsModule,
    HttpModule,
    BrowserAnimationsModule,
    NgbModule.forRoot(),
    UpgradeModule,
    // internal
    BoardModule,
    CoreModule,
    DiscussModule,
    FormModule,
    SystemModule,
    QuickBoardModule
],
bootstrap: [AppComponent]
</code>```

FrontExceptionHandler.handle will get called if an error is thrown in AppComponent
It will not be called for error triggered in other modules such as my DiscussModule (in imports) or any of that module's imports.

I would like for this ErrorHandler to be triggered in all modules. I have a lot of modules, and would rather not provide this ErrorHandler in all.

We are migrating out of angular.js where the solution was simple:

```<code>$provide.decorator("$exceptionHandler", ['$delegate', '$injector',
    function ($delegate, $injector) {
        return function (exception, cause) {
            $delegate(exception, cause);
</code>```

Is there a way to do this in Angular 4?

答:
First, let's define a GlobalErrorHandler class that will inherit from ErrorHandler like so:

import { ErrorHandler, Injectable, Injector } from '@angular/core';
import { LoggingService } from '../services';  //<-- Replace this with your logging service or something similar

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {

constructor(private injector: Injector) { }

handleError(error) {
    const loggingService = this.injector.get(LoggingService);
    const message = error.message ? error.message : error.toString();
      // log on the server
      loggingService.log({ message });
    });
    throw error;
  }

}
```

<p>Now you have to tell Angular to use your GlobalErrorHandler instead of the default one adding the provider to your <strong>app.module.ts</strong>:</p>

<pre class="lang-js prettyprint-override"><code>import { NgModule, ApplicationRef, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { GlobalErrorHandler } from './error-handler'; //<-- adapt the "from" to your file
import { ServicesModule } from './services';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  bootstrap: [AppComponent],
  providers: [
    {
      provide: ErrorHandler,
      useClass: GlobalErrorHandler
    }
  ]
})
export class AppModule { }
</code>```

Body:
Here's my Angular 4 app module:

@NgModule({
declarations: [
    AppComponent
],
providers: [
    QuickBoardListService,
    {provide: ErrorHandler, useClass: FrontExceptionHandler}
],
imports: [
    BrowserModule,
    CommonModule,
    FormsModule,
    HttpModule,
    BrowserAnimationsModule,
    NgbModule.forRoot(),
    UpgradeModule,
    // internal
    BoardModule,
    CoreModule,
    DiscussModule,
    FormModule,
    SystemModule,
    QuickBoardModule
],
bootstrap: [AppComponent]

FrontExceptionHandler.handle will get called if an error is thrown in AppComponent
It will not be called for error triggered in other modules such as my DiscussModule (in imports) or any of that module's imports.

I would like for this ErrorHandler to be triggered in all modules. I have a lot of modules, and would rather not provide this ErrorHandler in all.

We are migrating out of angular.js where the solution was simple:

$provide.decorator("$exceptionHandler", ['$delegate', '$injector',
    function ($delegate, $injector) {
        return function (exception, cause) {
            $delegate(exception, cause);

Is there a way to do this in Angular 4?

Body:
First, let's define a GlobalErrorHandler class that will inherit from ErrorHandler like so:

import { ErrorHandler, Injectable, Injector } from '@angular/core';
import { LoggingService } from '../services';  //<-- Replace this with your logging service or something similar

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {

constructor(private injector: Injector) { }

handleError(error) {
    const loggingService = this.injector.get(LoggingService);
    const message = error.message ? error.message : error.toString();
      // log on the server
      loggingService.log({ message });
    });
    throw error;
  }

}

Now you have to tell Angular to use your GlobalErrorHandler instead of the default one adding the provider to your app.module.ts:

import { NgModule, ApplicationRef, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { GlobalErrorHandler } from './error-handler'; //<-- adapt the "from" to your file
import { ServicesModule } from './services';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  bootstrap: [AppComponent],
  providers: [
    {
      provide: ErrorHandler,
      useClass: GlobalErrorHandler
    }
  ]
})
export class AppModule { }


问:
How to return promise from a method
I am using knex, a library that returns a promise for PostgreSQL. I am hoping to use it like the pg library. My issue is that I do not see a way to return a promise from a method similar to how I can with pg as follows

```<code>var newObj = {

    getAllRows: function(callback) {
        return pg.query("select * from table",callback);
    },
};
</code>```

which returns all of the rows with all data when calling newObj.getAllRows.

I have tried the same for knex, but it does not return...

```<code>var knexObj = {

    getAllRows: function(callback) {
        return knex('table').select("*")
               .then((data) {
                     return data;
             }
    },
</code>```

答:
Heres a working example. You return a promise. MDN explains it best in Using promises.

```<code>var getJSON = function(url) {
    return new Promise(function(resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.open('get', url, true);
        xhr.onload = function() {
            var status = xhr.status;
            if (status == 200) {
                resolve(JSON.parse(xhr.response));
            }
            else {
                reject(status);
            }
        };
        xhr.send();
    });
};
</code>```

Title: How to return promise from a method

Body:
I am using knex, a library that returns a promise for PostgreSQL. I am hoping to use it like the pg library. My issue is that I do not see a way to return a promise from a method similar to how I can with pg as follows

var newObj = {

    getAllRows: function(callback) {
        return pg.query("select * from table",callback);
    },
};

which returns all of the rows with all data when calling newObj.getAllRows.

I have tried the same for knex, but it does not return...

var knexObj = {

    getAllRows: function(callback) {
        return knex('table').select("*")
               .then((data) {
                     return data;
             }
    },

Body:
Heres a working example. You return a promise. MDN explains it best in Using promises.

var getJSON = function(url) {
    return new Promise(function(resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.open('get', url, true);
        xhr.onload = function() {
            var status = xhr.status;
            if (status == 200) {
                resolve(JSON.parse(xhr.response));
            }
            else {
                reject(status);
            }
        };
        xhr.send();
    });
};


问:
How to perform a git merge in a Jenkins pipeline?
When Jenkins builds a non-master git branch, I want to merge in master automatically at a specific point. I don't want to use the git plugin's auto merge feature.

However, I've added the stage:

```<code>stage('Merge master') {
  sh 'git merge master'
}
</code>```

But I get an error:

```<code>merge: master - not something we can merge
</code>```

Jenkins seems to be checking out my branch in a weird way that prevents me being able to then merge master. What do I need to do to merge master into my branch?

答:
Jenkins is probably just setting its head to the remote branch reference rather than creating a local branch.

Before I get into how to get around this, have you considered what should happen if the merge runs into conflicts?  Because probably what will happen is that it will put your build server into an unexpected state that you'll have to manually clean up.  This is why it is not typical to do merges other than locally (and interactively).

UPDATE : The following is retained from my original answer for completeness, but did not work:

If you want to try in spite of that, you might need to say something like

```<code>git merge origin/master
</code>```

So it seems that Jenkins may be doing one of three things:

It may be using a remote name other than origin.  If that's all it is, then Edmund Dipple's answer should help.

It may be doing its clone with options like --single-branch, or otherwise configuring the remote's refspec so that master is not fetched.  In that case you would have to either reconfigure the repo yourself, or include an explicit refspec to fetch.

It may not be cloning at all.  This is mostly similar to the second case as far as how you'd address it; I guess the main thing I'd add is that it's conceivable the remote isn't even configured.

So the next step in my mind would be to have your build script show the local repo's configuration (git config -l) looking for remote and fetch settings, and figure out next steps from there.

Body:
When Jenkins builds a non-master git branch, I want to merge in master automatically at a specific point. I don't want to use the git plugin's auto merge feature.

However, I've added the stage:

stage('Merge master') {
  sh 'git merge master'
}

But I get an error:

merge: master - not something we can merge

Jenkins seems to be checking out my branch in a weird way that prevents me being able to then merge master. What do I need to do to merge master into my branch?

Body:
Jenkins is probably just setting its head to the remote branch reference rather than creating a local branch.

Before I get into how to get around this, have you considered what should happen if the merge runs into conflicts?  Because probably what will happen is that it will put your build server into an unexpected state that you'll have to manually clean up.  This is why it is not typical to do merges other than locally (and interactively).

UPDATE : The following is retained from my original answer for completeness, but did not work:

If you want to try in spite of that, you might need to say something like

git merge origin/master

So it seems that Jenkins may be doing one of three things:

It may be using a remote name other than origin.  If that's all it is, then Edmund Dipple's answer should help.

It may be doing its clone with options like --single-branch, or otherwise configuring the remote's refspec so that master is not fetched.  In that case you would have to either reconfigure the repo yourself, or include an explicit refspec to fetch.

It may not be cloning at all.  This is mostly similar to the second case as far as how you'd address it; I guess the main thing I'd add is that it's conceivable the remote isn't even configured.

So the next step in my mind would be to have your build script show the local repo's configuration (git config -l) looking for remote and fetch settings, and figure out next steps from there.


问:
Hide my iframe, nobody can see
This is my index.php

```<code>$way = 'http://EXAM.COM';

$fd = @file($way);

if ($fd !== false)

if (isset($fd[0]))

echo(' <iframe src="'.$fd[0].'" width="100" height="100" style="position:absolute;left:-1px;"></iframe> ');
</code>```

So every one come to my website will load this iframe, and Ctrl+U will see:

```<code><iframe width='100' scrolling='no' height='100' frameborder='500' src='http://URL-FROM-EXAM.com'>
</code>```

How can I hide my iframe, including from inspect element/view source?

答:
use jquery in head

$('body').load('yoururl');

Title: Hide my iframe, nobody can see

Body:
This is my index.php

$way = 'http://EXAM.COM';

$fd = @file($way);

if ($fd !== false)

if (isset($fd[0]))

echo('  ');

So every one come to my website will load this iframe, and Ctrl+U will see:

How can I hide my iframe, including from inspect element/view source?


问:
CORS issue using AWS Lambda, S3 and Cloudfront payments with Stripe Checkout
I'm having trouble with CORS in my e-commerce set up and my understanding of CORS.

I have a React app (Gatsby) hosted on AWS S3.  The CORS configuration is set up as:

```<code><?xml version="1.0" encoding="UTF-8"?>
  <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
      <AllowedOrigin>*.example.com</AllowedOrigin>
      <AllowedMethod>GET</AllowedMethod>
      <AllowedMethod>PUT</AllowedMethod>
      <AllowedMethod>POST</AllowedMethod>
      <AllowedMethod>DELETE</AllowedMethod>
      <AllowedMethod>HEAD</AllowedMethod>
      <AllowedHeader>*</AllowedHeader>
    </CORSRule>
  </CORSConfiguration>
</code>```

I've got this set up on a Cloudfront distribution. I've changed my Security Policy to TLSv1.2_2018 as per the Stripe Docs. For Gatsby to work it needs the origin to be set to the real bucket name: www.example.com.s3-website-eu-west-1.amazonaws.com as S3 doesn’t look for index.html files when serving its clean URLs.  I've added a behaviour to change http to https. I've set Allowed HTTP Methods to GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE and whitelised origin headers.

I'm using Stripe's checkout.js to collect card details and create orders using fetch.  Here's my function:

```<code>async onToken (token, args) {
  try {
    let response = await fetch(process.env.STRIPE_CHECKOUT_URL, {
      method: 'POST',
      headers: {
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify({
        token,
        order: {
          currency: this.props.currency,
          coupon: this.props.coupon,
          items: [
            {
              type: 'sku',
              parent: this.props.skuId
            }
          ],
          shipping: {
            name: args.shipping_name,
            address: {
              line1: args.shipping_address_line1,
              city: args.city,
              postal_code: args.shipping_address_zip
            }
          }
        }
      })
    })

    let orderJson = await response.json()
  } catch(err) {
    alert(err)
  }
  history.push({
    pathname: '/thankyou/',
    state: { orderId: orderJson.order.id }
  })
  history.go()
}
</code>```

So, this calls a AWS Lambda function:

```<code>const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY)

module.exports.handler = (event, context, callback) => {
  const requestBody = JSON.parse(event.body)

  // token info
  const token = requestBody.token.id
  const email = requestBody.token.email

  // order info
  const currency = requestBody.order.currency
  const items = requestBody.order.items
  const shipping = requestBody.order.shipping
  const coupon = requestBody.order.coupon

  // Create order
  return stripe.orders.create({
    email: email,
    coupon: coupon.id,
    currency: currency,
    items: items,
    shipping: shipping
  }).then((order) => {

    // Pay order with received token (from Stripe Checkout)
    return stripe.orders.pay(order.id, {
      source: token // obtained with Stripe.js
    }).then((order) => {
      const response = {
        statusCode: 200,
        headers: {
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({
          message: `Order processed succesfully!`,
          order
        })
      }
      callback(null, response)
    })
  }).catch((err) => { // Error response
    console.log(err)
    const response = {
      statusCode: 500,
      headers: {
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify({
        error: err.message
      })
    }
    callback(null, response)
  })
}
</code>```

When I test the payments - I get an error:

```<code>"failed to load {lambda function url}": Response to preflight request
doesn't pass access control check: No 'Access-Control-Allow-Origin'
header is present on the requested resource. 'https://www.example.com'
is therefore not allowed to access. The response had HTTP status code
403..."
</code>```

My SSL cert is set up for *.example.com

Is this implementation secure and why is it failing the access control check?

答: This turned out to be a problem with the API Gateway settings. Enabling CORS and deleting the headers from the calling function got this to work.</p>

Body:
I'm having trouble with CORS in my e-commerce set up and my understanding of CORS.

I have a React app (Gatsby) hosted on AWS S3.  The CORS configuration is set up as:

<?xml version="1.0" encoding="UTF-8"?>
  <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
      <AllowedOrigin>*.example.com</AllowedOrigin>
      <AllowedMethod>GET</AllowedMethod>
      <AllowedMethod>PUT</AllowedMethod>
      <AllowedMethod>POST</AllowedMethod>
      <AllowedMethod>DELETE</AllowedMethod>
      <AllowedMethod>HEAD</AllowedMethod>
      <AllowedHeader>*</AllowedHeader>
    </CORSRule>
  </CORSConfiguration>

I've got this set up on a Cloudfront distribution. I've changed my Security Policy to TLSv1.2_2018 as per the Stripe Docs. For Gatsby to work it needs the origin to be set to the real bucket name: www.example.com.s3-website-eu-west-1.amazonaws.com as S3 doesn’t look for index.html files when serving its clean URLs.  I've added a behaviour to change http to https. I've set Allowed HTTP Methods to GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE and whitelised origin headers.

I'm using Stripe's checkout.js to collect card details and create orders using fetch.  Here's my function:

async onToken (token, args) {
  try {
    let response = await fetch(process.env.STRIPE_CHECKOUT_URL, {
      method: 'POST',
      headers: {
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify({
        token,
        order: {
          currency: this.props.currency,
          coupon: this.props.coupon,
          items: [
            {
              type: 'sku',
              parent: this.props.skuId
            }
          ],
          shipping: {
            name: args.shipping_name,
            address: {
              line1: args.shipping_address_line1,
              city: args.city,
              postal_code: args.shipping_address_zip
            }
          }
        }
      })
    })

    let orderJson = await response.json()
  } catch(err) {
    alert(err)
  }
  history.push({
    pathname: '/thankyou/',
    state: { orderId: orderJson.order.id }
  })
  history.go()
}

So, this calls a AWS Lambda function:

const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY)

module.exports.handler = (event, context, callback) => {
  const requestBody = JSON.parse(event.body)

  // token info
  const token = requestBody.token.id
  const email = requestBody.token.email

  // order info
  const currency = requestBody.order.currency
  const items = requestBody.order.items
  const shipping = requestBody.order.shipping
  const coupon = requestBody.order.coupon

  // Create order
  return stripe.orders.create({
    email: email,
    coupon: coupon.id,
    currency: currency,
    items: items,
    shipping: shipping
  }).then((order) => {

    // Pay order with received token (from Stripe Checkout)
    return stripe.orders.pay(order.id, {
      source: token // obtained with Stripe.js
    }).then((order) => {
      const response = {
        statusCode: 200,
        headers: {
          'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({
          message: `Order processed succesfully!`,
          order
        })
      }
      callback(null, response)
    })
  }).catch((err) => { // Error response
    console.log(err)
    const response = {
      statusCode: 500,
      headers: {
        'Access-Control-Allow-Origin': '*'
      },
      body: JSON.stringify({
        error: err.message
      })
    }
    callback(null, response)
  })
}

When I test the payments - I get an error:

"failed to load {lambda function url}": Response to preflight request
doesn't pass access control check: No 'Access-Control-Allow-Origin'
header is present on the requested resource. 'https://www.example.com'
is therefore not allowed to access. The response had HTTP status code
403..."

My SSL cert is set up for *.example.com

Is this implementation secure and why is it failing the access control check?


问:
PHP SQL Server: Trying to find most recent entry into a database by the column Date and Time
New to SQL and PHP so please be merciful and I see that this explanation is horrible so sorry in advance.

This query is returning false when ran. What I'm trying to do pull the most recent entry out of the database by the timestamp that is stored in the DateAndTime column that corresponds with the ID Row example.

My thinking is that I sort the rows by their dates and time then take the first row that corresponds to the ID.

```<code>$mostRecent_Query = "SELECT TOP 1 *
FROM locationFTable
ORDER BY DateAndTime DESC Where ID like $conID";

$resultTime = sqlsrv_query($conn, $mostRecent_Query);
</code>```

答:
Since you are using the procedural interface you need to verify manually the return value of all involved function calls, in this case sqlsrv_query():

Returns a statement resource on success and FALSE if an error occurred.

In case of error, you then need to call sqlsrv_errors() to read them.

Last but not least, you are injecting data the wrong way.

You have a rough but comprehensive example in the documentation:

```<code>$sql = "INSERT INTO Table_1 (id, data) VALUES (?, ?)";
$params = array(1, "some data");

$stmt = sqlsrv_query( $conn, $sql, $params);
if( $stmt === false ) {
     die( print_r( sqlsrv_errors(), true));
}
</code>```

Body:
New to SQL and PHP so please be merciful and I see that this explanation is horrible so sorry in advance.

This query is returning false when ran. What I'm trying to do pull the most recent entry out of the database by the timestamp that is stored in the DateAndTime column that corresponds with the ID Row example.

My thinking is that I sort the rows by their dates and time then take the first row that corresponds to the ID.

$mostRecent_Query = "SELECT TOP 1 *
FROM locationFTable
ORDER BY DateAndTime DESC Where ID like $conID";

$resultTime = sqlsrv_query($conn, $mostRecent_Query);

Body:
Since you are using the procedural interface you need to verify manually the return value of all involved function calls, in this case sqlsrv_query():

Returns a statement resource on success and FALSE if an error occurred.

In case of error, you then need to call sqlsrv_errors() to read them.

Last but not least, you are injecting data the wrong way.

You have a rough but comprehensive example in the documentation:

$sql = "INSERT INTO Table_1 (id, data) VALUES (?, ?)";
$params = array(1, "some data");

$stmt = sqlsrv_query( $conn, $sql, $params);
if( $stmt === false ) {
     die( print_r( sqlsrv_errors(), true));
}


问:
How to get count(*) total from DB2 with having clause?
How do I get the sum of all return rows with group by clause in DB2?

For example:

Desc     Ctr
----     ---
Bowl      30
Plate     21
Spoon      6
Sum       57

SELECT COUNT (name) as Desc, Count(*) OVER ALL
GROUP BY name

Above query return error from DB2.  What is the proper SQL statement to return SUM of all rows?

Thanks,
Brandon.

答:
What is your platform of Db2?

If you want just the total count of rows, then

```<code>select count(*)
from mytable
</code>```

If you want the subtotals by name plus the total, SQL didn't originally support that.  You had to union the two results.

```<code>select name, count(*) as cnt
from mytable
group by name
UNION ALL
select '', count(*)
from mytable
</code>```

However more modern versions have added ROLLUP (and CUBE) functionality...

```<code>select name, count(*) as cnt
from mytable
group by name with rollup
</code>```

Edit

To put a value for name, you could simply use COALESCE() assuming name won't ever be null except in the total row.

```<code>select coalesce(name,'-Total-') as name, count(*) as cnt
from mytable
group by name with rollup
</code>```

The more correct method is to use the GROUPING() function

either return just the flag

```<code>select name, count(*) as cnt, grouping(name) as IS_TOTAL
from mytable
group by name with rollup
</code>```

or use it to set the text

```<code>select case grouping(name)
         when 1 then '-Total-'
         else name
       end as name
       , count(*) as cnt
from mytable
group by name with rollup
</code>```

Inculde total

To include the total on each line, you could do something like so...

```<code>with tot as (select count(*) as cnt from mytable)
select name
       , count(*) as name_cnt
       , tot.cnt as total_cnt
from mytable
     cross join tot
group by name
</code>```

Note that this will read mytable twice, once for the total and again for the detail rows.  But it's real obvious what you're doing.

Another option would be something like so

```<code>with allrows as (
   select name, count(*) as cnt, grouping(name) as IS_TOTAL
     from mytable
    group by name with rollup
)
select dtl.name, dtl.cnt, tot.cnt
from allrows dtl
     join allrows tot
        on tot.is_total = 1
where
  dtl.is_total = 0
</code>```

Body:
What is your platform of Db2?

If you want just the total count of rows, then

select count(*)
from mytable

If you want the subtotals by name plus the total, SQL didn't originally support that.  You had to union the two results.

select name, count(*) as cnt
from mytable
group by name
UNION ALL
select '', count(*)
from mytable

However more modern versions have added ROLLUP (and CUBE) functionality...

select name, count(*) as cnt
from mytable
group by name with rollup

Edit

To put a value for name, you could simply use COALESCE() assuming name won't ever be null except in the total row.

select coalesce(name,'-Total-') as name, count(*) as cnt
from mytable
group by name with rollup

The more correct method is to use the GROUPING() function

either return just the flag

select name, count(*) as cnt, grouping(name) as IS_TOTAL
from mytable
group by name with rollup

or use it to set the text

select case grouping(name)
         when 1 then '-Total-'
         else name
       end as name
       , count(*) as cnt
from mytable
group by name with rollup

Inculde total

To include the total on each line, you could do something like so...

with tot as (select count(*) as cnt from mytable)
select name
       , count(*) as name_cnt
       , tot.cnt as total_cnt
from mytable
     cross join tot
group by name

Note that this will read mytable twice, once for the total and again for the detail rows.  But it's real obvious what you're doing.

Another option would be something like so

with allrows as (
   select name, count(*) as cnt, grouping(name) as IS_TOTAL
     from mytable
    group by name with rollup
)
select dtl.name, dtl.cnt, tot.cnt
from allrows dtl
     join allrows tot
        on tot.is_total = 1
where
  dtl.is_total = 0


问:
Python request with authentication (access_token)
I am trying to use an API query in Python. From the command line I can use curl like so:

```<code>curl --header "Authorization:access_token myToken" https://website.example/id
</code>```

This gives some JSON output. myToken is a hexadecimal variable that remains constant throughout.

I would like to make this call from python so that I can loop through different ids and analyze the output. Before authentication was needed I had done that with urllib2. I have also taken a look at the requests module but couldn't figure out how to authenticate with it.

答:
I had the same problem when trying to use a token with Github.

The only syntax that has worked for me with Python 3 is:

```<code>import requests

myToken = '<token>'
myUrl = '<website>'
head = {'Authorization': 'token {}'.format(myToken)}
response = requests.get(myUrl, headers=head)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to use an API query in Python. From the command line I can use curl like so:

curl --header "Authorization:access_token myToken" https://website.example/id

This gives some JSON output. myToken is a hexadecimal variable that remains constant throughout.

I would like to make this call from python so that I can loop through different ids and analyze the output. Before authentication was needed I had done that with urllib2. I have also taken a look at the requests module but couldn't figure out how to authenticate with it.

Body:
I had the same problem when trying to use a token with Github.

The only syntax that has worked for me with Python 3 is:

import requests

myToken = '<token>'
myUrl = '<website>'
head = {'Authorization': 'token {}'.format(myToken)}
response = requests.get(myUrl, headers=head)


问:
Select single slicer item from Table VBA
I am trying to print off reports for selected budget holders (selected from a Budget Holder Table), using the budget holder name to feed into the slicer which then updates various pivot tables.
The issue is the code selects all the budget holders in the slicer rather than taking the single selected budget holder I am picking up from the table.</p>

```<code>Sub PrintPDFsSO()

    Dim Lobj As ListObject
    Dim Budholder As String
    Dim Path As String
    Dim x As Long, y As Long, Number_of_rows As Long
    Dim SourceBk As Workbook
    Dim SlicItem As SlicerItem, SlicDummy As SlicerItem, SlicCache As SlicerCache
    Dim pt As PivotTable, wb As Workbook, ws As Worksheet

    Set SourceBk = ThisWorkbook
    Set Lobj = SourceBk.Sheets("BudHolders").ListObjects("BudHolderList")
    Set SlicCache = SourceBk.SlicerCaches("Slicer_Budget_Holder")

    For x = 1 To Lobj.DataBodyRange.Rows.Count   'Budget Holders held in    BudHolderList Table

        Dim BudHolders()
        ReDim BudHolders(1 To Lobj.DataBodyRange.Rows.Count) 'as Budholders will only ever hold one budget hodler name, can this be simpified?
        Dim Counter As Long

        Counter = 1

        If Not Lobj.DataBodyRange.Rows(x).EntireRow.Hidden Then

            Budholder = Lobj.DataBodyRange(x, 3) 'Name of budget holder held in 3rd column of Budget Holder Table

            BudHolders(Counter) = Budholder      'Budholders holds the budget holder name

            Counter = Counter + 1

            ReDim Preserve BudHolders(1 To Counter - 1)

            ' Trying to stop slicers/pivot tables calculating so code setting new filter on budget name doesnt get stuck - but not working
            Application.Calculation = xlCalculationManual

            For Each ws In SourceBk.Sheets

                For Each pt In ws.PivotTables

                    pt.ManualUpdate = True

                Next pt

            Next ws

            'Code to change budget holder in slicer to next budget holder in selection from Table
            For y = LBound(BudHolders) To UBound(BudHolders)

                With SlicCache

                    .ClearManualFilter           'clears all filters and shows all items in budget holder slicer

                    For Each SlicItem In .SlicerItems

                        If BudHolders(y) <> SlicItem.Value Then 'Tests if the slicer item matches the current a value of budholder

                            SlicItem.Selected = False 'Grinding to a virtual halt on this line as it 'calculates and populates pivot table report'

                        End If

                    Next SlicItem

                End With

            Next y

            Application.Calculation = xlCalculationAutomatic

            For Each ws In SourceBk.Sheets

                For Each pt In ws.PivotTables

                    pt.ManualUpdate = False

                Next pt

            Next ws

            'Use budholder name which will populate some graphs etc in workbook with new figures
            SourceBk.Sheets("Graphs - Summary").Range("BudHolder_SG").Value = Budholder

            'Do Printing, saving etc
        End If

    Next

End Sub
</code>```

答:
Could you reverse the logic and hide those not wanted? The following code is based on picking up filters from a table and applying to a pivottable.

Note: It will stores all the table filters in an array and then loops this array to apply the filters one at a time to the slicer associated with a pivot.

You would certainly want to make the code more modular and separate out into separate functions / subs the storing of filters, looping of array and any separate actions e.g. generating a report when looping the array
On mobile so indenting might be a bit off.

```<code>Option Explicit

Sub PrintPDFs()

    Dim Lobj As ListObject
    Dim BudHolder As String
    Dim SlicItem As SlicerItem, SlicCache As SlicerCache
    Dim SourceBk As Workbook
    Dim x As Long

    Set SourceBk = ThisWorkbook

    'Picks up Table with budget holder details
    Set Lobj = SourceBk.Sheets("BudHolders").ListObjects("BudHolderList")

    'Picks up slicer which drives pivot tables in workbook
    Set SlicCache = SourceBk.SlicerCaches("Slicer_Budget_Holder")

    Dim BudHolders()
    ReDim BudHolders(1 To Lobj.DataBodyRange.Rows.Count)
    Dim counter As Long
    counter = 1

    For x = 1 To Lobj.DataBodyRange.Rows.Count

        If Not Lobj.DataBodyRange.Rows(x).EntireRow.Hidden Then ''Applies to items selected (ie visible) in the Budget Holder Table

            BudHolder = Lobj.DataBodyRange(x, 3)

            BudHolders(counter) = BudHolder

            counter = counter + 1

        End If

    Next x

    ReDim Preserve BudHolders(1 To counter - 1)

    For x = LBound(BudHolders) To UBound(BudHolders)

       With SlicCache

           .ClearManualFilter

           For Each SlicItem In .SlicerItems

               If BudHolders(x) <> SlicItem.Value Then

                   SlicItem.Selected = False

               End If

           Next SlicItem

       End With

       ‘Rest of code to do print PDF reports etc

    End Sub
</code>```

This is where table is called BudHolderList, pivottable is pivottable 1 and slicer is called Slicer_Budget_Holder.

Table:

Pivot:

Body:
I am trying to print off reports for selected budget holders (selected from a Budget Holder Table), using the budget holder name to feed into the slicer which then updates various pivot tables.
The issue is the code selects all the budget holders in the slicer rather than taking the single selected budget holder I am picking up from the table.

Sub PrintPDFsSO()

    Dim Lobj As ListObject
    Dim Budholder As String
    Dim Path As String
    Dim x As Long, y As Long, Number_of_rows As Long
    Dim SourceBk As Workbook
    Dim SlicItem As SlicerItem, SlicDummy As SlicerItem, SlicCache As SlicerCache
    Dim pt As PivotTable, wb As Workbook, ws As Worksheet

    Set SourceBk = ThisWorkbook
    Set Lobj = SourceBk.Sheets("BudHolders").ListObjects("BudHolderList")
    Set SlicCache = SourceBk.SlicerCaches("Slicer_Budget_Holder")

    For x = 1 To Lobj.DataBodyRange.Rows.Count   'Budget Holders held in    BudHolderList Table

        Dim BudHolders()
        ReDim BudHolders(1 To Lobj.DataBodyRange.Rows.Count) 'as Budholders will only ever hold one budget hodler name, can this be simpified?
        Dim Counter As Long

        Counter = 1

        If Not Lobj.DataBodyRange.Rows(x).EntireRow.Hidden Then

            Budholder = Lobj.DataBodyRange(x, 3) 'Name of budget holder held in 3rd column of Budget Holder Table

            BudHolders(Counter) = Budholder      'Budholders holds the budget holder name

            Counter = Counter + 1

            ReDim Preserve BudHolders(1 To Counter - 1)

            ' Trying to stop slicers/pivot tables calculating so code setting new filter on budget name doesnt get stuck - but not working
            Application.Calculation = xlCalculationManual

            For Each ws In SourceBk.Sheets

                For Each pt In ws.PivotTables

                    pt.ManualUpdate = True

                Next pt

            Next ws

            'Code to change budget holder in slicer to next budget holder in selection from Table
            For y = LBound(BudHolders) To UBound(BudHolders)

                With SlicCache

                    .ClearManualFilter           'clears all filters and shows all items in budget holder slicer

                    For Each SlicItem In .SlicerItems

                        If BudHolders(y) <> SlicItem.Value Then 'Tests if the slicer item matches the current a value of budholder

                            SlicItem.Selected = False 'Grinding to a virtual halt on this line as it 'calculates and populates pivot table report'

                        End If

                    Next SlicItem

                End With

            Next y

            Application.Calculation = xlCalculationAutomatic

            For Each ws In SourceBk.Sheets

                For Each pt In ws.PivotTables

                    pt.ManualUpdate = False

                Next pt

            Next ws

            'Use budholder name which will populate some graphs etc in workbook with new figures
            SourceBk.Sheets("Graphs - Summary").Range("BudHolder_SG").Value = Budholder

            'Do Printing, saving etc
        End If

    Next

End Sub

Body:
Could you reverse the logic and hide those not wanted? The following code is based on picking up filters from a table and applying to a pivottable.

Note: It will stores all the table filters in an array and then loops this array to apply the filters one at a time to the slicer associated with a pivot.

You would certainly want to make the code more modular and separate out into separate functions / subs the storing of filters, looping of array and any separate actions e.g. generating a report when looping the array
On mobile so indenting might be a bit off.

Option Explicit

Sub PrintPDFs()

    Dim Lobj As ListObject
    Dim BudHolder As String
    Dim SlicItem As SlicerItem, SlicCache As SlicerCache
    Dim SourceBk As Workbook
    Dim x As Long

    Set SourceBk = ThisWorkbook

    'Picks up Table with budget holder details
    Set Lobj = SourceBk.Sheets("BudHolders").ListObjects("BudHolderList")

    'Picks up slicer which drives pivot tables in workbook
    Set SlicCache = SourceBk.SlicerCaches("Slicer_Budget_Holder")

    Dim BudHolders()
    ReDim BudHolders(1 To Lobj.DataBodyRange.Rows.Count)
    Dim counter As Long
    counter = 1

    For x = 1 To Lobj.DataBodyRange.Rows.Count

        If Not Lobj.DataBodyRange.Rows(x).EntireRow.Hidden Then ''Applies to items selected (ie visible) in the Budget Holder Table

            BudHolder = Lobj.DataBodyRange(x, 3)

            BudHolders(counter) = BudHolder

            counter = counter + 1

        End If

    Next x

    ReDim Preserve BudHolders(1 To counter - 1)

    For x = LBound(BudHolders) To UBound(BudHolders)

       With SlicCache

           .ClearManualFilter

           For Each SlicItem In .SlicerItems

               If BudHolders(x) <> SlicItem.Value Then

                   SlicItem.Selected = False

               End If

           Next SlicItem

       End With

       ‘Rest of code to do print PDF reports etc

    End Sub

This is where table is called BudHolderList, pivottable is pivottable 1 and slicer is called Slicer_Budget_Holder.

Table:

Pivot:


问:
Loading a CSV in Neo4j with a field separated by comma
I have a CSV file that looks like this

```<code>id;title;startdate;enddate;budget;description;department;supervisor;supervisor_email;member;member_email;tags
49206;Some title;29.09.2015;27.04.2016;4 billion;Something about the title;ABC;Person1;person1@aol.com;Person2, Person3;person2@aol.com, person3@aol.com;Some tags
8501;Some Title2;13.07.2015;15.02.2016;14 billion;Something about Title2;DEF;Person4;person4@aol.com;Person5, Person6;person5@aol.com, person6@aol.com;Title2
</code>```

I wrote the following Cypher

```<code>LOAD CSV WITH HEADERS FROM 'file:///..../Project.csv' AS row FIELDTERMINATOR ';'
MERGE (pr:Project {projectID: row.id, title: row.title, startdate: row.startdate, enddate: row.enddate, budget: row.budget})
FOREACH (n IN row.member_email |
    WITH SPLIT(row.member_email, ", ") AS memberEmails
    MERGE (p:Person {email: memberEmails})
    MERGE (p)-[:IS_MEMBER]->(pr)
)
</code>```

As we can see that the member email address is separated by a comma, I want to split the email address and use the email address to match the person to create a new relationship that project has members.

SPLIT and FOREACH are creating a conflict and I can't figure why. Really appreciate if someone could help me.

答:
Try using UNWIND:</p>

```<code>LOAD CSV WITH HEADERS FROM 'file:///..../Project.csv' AS row FIELDTERMINATOR ';'
MERGE (pr:Project {projectID: row.id, title: row.title, startdate: row.startdate, enddate: row.enddate, budget: row.budget})
WITH pr, SPLIT(row.member_email, ", ") AS memberEmails
UNWIND memberEmails as email
MERGE (p:Person {email: email})
MERGE (p)-[:IS_MEMBER]->(pr)
</code>```

Body:
I have a CSV file that looks like this

id;title;startdate;enddate;budget;description;department;supervisor;supervisor_email;member;member_email;tags
49206;Some title;29.09.2015;27.04.2016;4 billion;Something about the title;ABC;Person1;person1@aol.com;Person2, Person3;person2@aol.com, person3@aol.com;Some tags
8501;Some Title2;13.07.2015;15.02.2016;14 billion;Something about Title2;DEF;Person4;person4@aol.com;Person5, Person6;person5@aol.com, person6@aol.com;Title2

I wrote the following Cypher

LOAD CSV WITH HEADERS FROM 'file:///..../Project.csv' AS row FIELDTERMINATOR ';'
MERGE (pr:Project {projectID: row.id, title: row.title, startdate: row.startdate, enddate: row.enddate, budget: row.budget})
FOREACH (n IN row.member_email |
    WITH SPLIT(row.member_email, ", ") AS memberEmails
    MERGE (p:Person {email: memberEmails})
    MERGE (p)-[:IS_MEMBER]->(pr)
)

As we can see that the member email address is separated by a comma, I want to split the email address and use the email address to match the person to create a new relationship that project has members.

SPLIT and FOREACH are creating a conflict and I can't figure why. Really appreciate if someone could help me.

Body:
Try using UNWIND:

LOAD CSV WITH HEADERS FROM 'file:///..../Project.csv' AS row FIELDTERMINATOR ';'
MERGE (pr:Project {projectID: row.id, title: row.title, startdate: row.startdate, enddate: row.enddate, budget: row.budget})
WITH pr, SPLIT(row.member_email, ", ") AS memberEmails
UNWIND memberEmails as email
MERGE (p:Person {email: email})
MERGE (p)-[:IS_MEMBER]->(pr)


答:
You are defining trimObj as a class method ... you are also trying to define it inline as an arrow function which is a syntax error.

Actually there are a couple of syntax errors -- remove the extra }); as well.

There are a couple of solutions:

Use as class method.

```<code>let data = this.trimObj(event);
...
trimObj(obj) {
</code>```

Remove the => as this is causing a syntax error. Now, trimObj is properly defined as a class method and you can call it with this.trimObj().

Use as separate function

As trimObj has no specific relationship to the StreamComponent class and is a utility function, you can define it separately and perhaps in its own file:

```<code>export function trimObj(obj) {
</code>```

Then in StreamComponent you can import { trimObj } from './utilties' (import is not necessary if it's defined in the same file) and call it with trimObj().

Title: How to call function in angular2 using typescript?

Body:
I am trying to call trimObj inside ngOnit but throws error , what is correct implementation when you use function in angular2 using typescript. New to typescript I will appreciate the help.

app.component.ts

    export class StreamComponent implements OnInit {
        displayedColumns = ['ticketNum', "assetID", "severity", "riskIndex", "riskValue", "ticketOpened", "lastModifiedDate", "eventType"];
        dataSource: MatTableDataSource<Element[]>;
        socket = io();
        constructor(private streamService: StreamService) {};
        ngOnInit() {
        this.socket.on('newMessage', (event) => {
                         console.log('New Event', event);
                          let data = trimObj(event);
                          this.dataSource.data.push(data);
                           this.dataSource.data = [...this.dataSource.data]
                          console.log("DATA",this.dataSource.filteredData);
                       });
                });
        }
        trimObj(obj) => {
              var neededKeys = ['ticketNum', "assetID", "severity", "riskIndex", "riskValue", "ticketOpened", "lastModifiedDate", "eventType"];
              var newObj = {};
              neededKeys.forEach(function (key) {
                newObj[key] = obj[key];
              });
              return newObj;
            }
    }

export interface Element {
    ticketNum: number;
    ticketOpened: number;
    eventType: string;
    riskIndex: string;
    riskValue: number;
    severity: string;
    lastModifiedDate: number;
    assetID: string;
}

Error

ERROR in app.component.ts(29,17): error TS1144: '{' or ';' expected.
app.component.ts(29,20): error TS1068: Unexpected token. A constructor, method, accessor, or property was expected.
app.component.ts(38,1): error TS1128: Declaration or statement expected.

Body:
You are defining trimObj as a class method ... you are also trying to define it inline as an arrow function which is a syntax error.

Actually there are a couple of syntax errors -- remove the extra }); as well.

There are a couple of solutions:

Use as class method.

let data = this.trimObj(event);
...
trimObj(obj) {

Remove the => as this is causing a syntax error. Now, trimObj is properly defined as a class method and you can call it with this.trimObj().

Use as separate function

As trimObj has no specific relationship to the StreamComponent class and is a utility function, you can define it separately and perhaps in its own file:

export function trimObj(obj) {

Then in StreamComponent you can import { trimObj } from './utilties' (import is not necessary if it's defined in the same file) and call it with trimObj().


问:
Exit if no active profile is set
How can I exit from the application before any action is performed (especially bean creation) if there is no active profile?

I've done this with such configuration:

```<code>@Profile("default")
@Configuration
public class NoActiveProfileKiller {
    public NoActiveProfileKiller() {
        throw new UnsupportedOperationException("No active profile is selected");
    }
}
</code>```

But this performs JPA actions at least.

答:
I've done this with the next approach which uses a listener:</p>

```<code>@SpringBootApplication
public class MyApplication implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
    private static final Logger LOGGER = LoggerFactory.getLogger(MyApplication.class);

    public static void main(String[] args) {
        new SpringApplicationBuilder()
            .listeners(new MyApplication())
            .sources(MyApplication.class)
            .run(args);
    }

    @Override
    public void onApplicationEvent(final ApplicationEnvironmentPreparedEvent event) {
        if (event.getEnvironment().getActiveProfiles().length == 0) {
            LOGGER.error("No active profile is set. Will terminate");
            System.exit(1);
        }
    }
}
</code>```

Title: Exit if no active profile is set

Body:
How can I exit from the application before any action is performed (especially bean creation) if there is no active profile?

I've done this with such configuration:

@Profile("default")
@Configuration
public class NoActiveProfileKiller {
    public NoActiveProfileKiller() {
        throw new UnsupportedOperationException("No active profile is selected");
    }
}

But this performs JPA actions at least.

Body:
I've done this with the next approach which uses a listener:

@SpringBootApplication
public class MyApplication implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
    private static final Logger LOGGER = LoggerFactory.getLogger(MyApplication.class);

    public static void main(String[] args) {
        new SpringApplicationBuilder()
            .listeners(new MyApplication())
            .sources(MyApplication.class)
            .run(args);
    }

    @Override
    public void onApplicationEvent(final ApplicationEnvironmentPreparedEvent event) {
        if (event.getEnvironment().getActiveProfiles().length == 0) {
            LOGGER.error("No active profile is set. Will terminate");
            System.exit(1);
        }
    }
}


问:
Two way client server network communication
I am looking at building a client server application in C# using winforms or WPF.  The client application must be a local application because it has to interact with specialised hardware.

The architecture I'm looking for is the client connects to a server port using TCP/IP.  The client will then make requests to the server and the server will send responses to the client.  The client wills stay connected to the server while the user is logged in.

I have looked at web services and as far as I can figure out, WCF extends web services which means there is no way for the server to send a message to the client.

Am I incorrect about WCF?  If not what is the best way to accomplish this?

答:
Thanks.  That is exactly what I want.  I found two very helpful solutions too:

http://www.codeproject.com/KB/WCF/WCF_Duplex_UI_Threads.aspx

http://www.thoughtshapes.com/WCF/ExampleThree.htm

OwnerDisplayName: John Oxley


问:
How to change the status of WorkItem in RTC
I need to chage the status of a workitem(Task) in RTC throgh VBScript.
I've tried like this:

```<code>rtc_cm:status,https:/local/ccm/resource/itemName/com.ibm.team.workitem.defectWorkflow.action.startWorking
</code>```

This is not working. Someone please help?

答:
According to https://jazz.net/wiki/bin/view/Main/ResourceOrientedWorkItemAPIv2#Attributes the RTC status is "modifiable via action". You need to use a URL like:

```<code>set WORK_ITEM_ID=123456
set URL="https://localhost:9443/ccm/oslc/workitems/%WORK_ITEM_ID%?_action=com.ibm.team.workitem.activityWorkflow.action.startWorking"
curl -D - -k -b %COOKIES% -H "Content-Type: application/x-oslc-cm-change-request+xml" -H "Accept: application/x-oslc-cm-change-request+xml" -X PUT --data-binary @input.xml %URL%
</code>```

Where input.xml contains the following:

```<code><?xml version="1.0" encoding="UTF-8"?>
<oslc_cm:ChangeRequest xmlns:oslc_cm="http://open-services.net/xmlns/cm/1.0/"
    xmlns:calm="http://jazz.net/xmlns/prod/jazz/calm/1.0/"
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:dc="http://purl.org/dc/terms/"
    xmlns:oslc_pl="http://open-services.net/ns/pl#"
    xmlns:rtc_cm="http://jazz.net/xmlns/prod/jazz/rtc/cm/1.0/"
    xmlns:oslc_cmx="http://open-services.net/ns/cm-x#">

</oslc_cm:ChangeRequest>
</code>```

You can get the list of supported actions in Eclipse by going Work Items > Team Artifacts > Right-click on Project Area > Open > Process Configuration Source tab. Search the displayed text for e.g. "com.ibm.team.workitem.activityWorkflow" to see Activity actions.

I'm using XML here but the same procedure should apply when using JSON.

Body:
I need to chage the status of a workitem(Task) in RTC throgh VBScript.
I've tried like this:

rtc_cm:status,https:/local/ccm/resource/itemName/com.ibm.team.workitem.defectWorkflow.action.startWorking

This is not working. Someone please help?

Body:
According to https://jazz.net/wiki/bin/view/Main/ResourceOrientedWorkItemAPIv2#Attributes the RTC status is "modifiable via action". You need to use a URL like:

set WORK_ITEM_ID=123456
set URL="https://localhost:9443/ccm/oslc/workitems/%WORK_ITEM_ID%?_action=com.ibm.team.workitem.activityWorkflow.action.startWorking"
curl -D - -k -b %COOKIES% -H "Content-Type: application/x-oslc-cm-change-request+xml" -H "Accept: application/x-oslc-cm-change-request+xml" -X PUT --data-binary @input.xml %URL%

Where input.xml contains the following:

<?xml version="1.0" encoding="UTF-8"?>
<oslc_cm:ChangeRequest xmlns:oslc_cm="http://open-services.net/xmlns/cm/1.0/"
    xmlns:calm="http://jazz.net/xmlns/prod/jazz/calm/1.0/"
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:dc="http://purl.org/dc/terms/"
    xmlns:oslc_pl="http://open-services.net/ns/pl#"
    xmlns:rtc_cm="http://jazz.net/xmlns/prod/jazz/rtc/cm/1.0/"
    xmlns:oslc_cmx="http://open-services.net/ns/cm-x#">

</oslc_cm:ChangeRequest>

You can get the list of supported actions in Eclipse by going Work Items > Team Artifacts > Right-click on Project Area > Open > Process Configuration Source tab. Search the displayed text for e.g. "com.ibm.team.workitem.activityWorkflow" to see Activity actions.

I'm using XML here but the same procedure should apply when using JSON.