问:
Verify that clicks are coming from own website
I have a file go.php on my website that tracks the clicks on certain links and I want to count only the clicks that are made on my website and not on other sites that copy that link (site.com/go.php?id=). I have tried with this code

```<code>if($_SERVER[HTTP_REFERER] && !preg_match("/site\.com/", $_SERVER[HTTP_REFERER])) {
    header("Location: http:// www .site.com");
    die();
}
</code>```

but is not working properly, clicks from other sites are counted. Is there any way to count only the clicks made on my website?

EDIT: I formatted the code, but I left the spaces near http:// and www. -gore

答:
I think you're on to the right idea here.  In my opinion, working with regexes can be kind of a pain, so perhaps this would be simpler:

```<code><?php

//make sure to use !== rather than != with strpos
if(strpos($_SERVER['HTTP_REFERER'], 'site.com') !== false){
    //if you're here, you've got a match for site.com
}

?>
</code>```

I hope that's helpful.

Body:
I have a file go.php on my website that tracks the clicks on certain links and I want to count only the clicks that are made on my website and not on other sites that copy that link (site.com/go.php?id=). I have tried with this code

if($_SERVER[HTTP_REFERER] && !preg_match("/site\.com/", $_SERVER[HTTP_REFERER])) {
    header("Location: http:// www .site.com");
    die();
}

but is not working properly, clicks from other sites are counted. Is there any way to count only the clicks made on my website?

EDIT: I formatted the code, but I left the spaces near http:// and www. -gore

Body:
I think you're on to the right idea here.  In my opinion, working with regexes can be kind of a pain, so perhaps this would be simpler:

<?php

//make sure to use !== rather than != with strpos
if(strpos($_SERVER['HTTP_REFERER'], 'site.com') !== false){
    //if you're here, you've got a match for site.com
}

?>

I hope that's helpful.


来源: stackexchange

问:
How to create Charts using c# Bot Framework?
I am trying to create some charts(line graph etc.,) in a bot. I have the data available from an online source (finance.Yahoo.com)

I am not sure what library I should be using for this purpose

1. What chart library?

2. What type of Card (Hero Card, Adaptive Card ...) should I use?

3. My current solution which is connecting to external site (Yahoo) is a web api and I am using C# bot framework?

Could anyone share an example on how can I achieve this?

I have tried to use UI.Visualization.Chart library but I wasn't successful in getting the solution. Hence I am looking for some help in this area

答:
Interactive charts are not currently supported in BotFramework, you can use some third-party libs as @Peter Bons suggested or on-line services to generate your chart, but you will need to try to render it as an image file and attach this file to your message using HeroCard/ AdaptiveCard in bot.

Since your data is in finance.Yahoo.com, I'm not sure if Yahoo supports to generate chart image, if not, you will need to get the data from Yahoo and then try to find an online-service or third-party lib to draw the chart image first.

After the image is rendered, you can send it as image attachment
 for example like this:

```<code>[Serializable]
public class RootDialog : IDialog<object>
{
    public Task StartAsync(IDialogContext context)
    {
        context.Wait(MessageReceivedAsync);

        return Task.CompletedTask;
    }

    private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
    {
        var activity = await result as Activity;

        var card = CreateHeroCard();
        Attachment attachment = card.ToAttachment();
        var message = context.MakeMessage();
        message.Attachments.Add(attachment);

        await context.PostAsync(message);

        context.Wait(MessageReceivedAsync);
    }

    private HeroCard CreateHeroCard()
    {
        List<CardImage> cardImages = new List<CardImage>();
        cardImages.Add(new CardImage("your chart image url goes here"));
        var card = new HeroCard()
        {
            Title = "Months with Numbers Bar Chart",
            Subtitle = "Using a Chart as Image service...",
            Text = "Build and connect intelligent bots that have charts rendered as images.",
            Images = cardImages
        };

        return card;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Interactive charts are not currently supported in BotFramework, you can use some third-party libs as @Peter Bons suggested or on-line services to generate your chart, but you will need to try to render it as an image file and attach this file to your message using HeroCard/ AdaptiveCard in bot.

Since your data is in finance.Yahoo.com, I'm not sure if Yahoo supports to generate chart image, if not, you will need to get the data from Yahoo and then try to find an online-service or third-party lib to draw the chart image first.

After the image is rendered, you can send it as image attachment
 for example like this:

[Serializable]
public class RootDialog : IDialog<object>
{
    public Task StartAsync(IDialogContext context)
    {
        context.Wait(MessageReceivedAsync);

        return Task.CompletedTask;
    }

    private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result)
    {
        var activity = await result as Activity;

        var card = CreateHeroCard();
        Attachment attachment = card.ToAttachment();
        var message = context.MakeMessage();
        message.Attachments.Add(attachment);

        await context.PostAsync(message);

        context.Wait(MessageReceivedAsync);
    }

    private HeroCard CreateHeroCard()
    {
        List<CardImage> cardImages = new List<CardImage>();
        cardImages.Add(new CardImage("your chart image url goes here"));
        var card = new HeroCard()
        {
            Title = "Months with Numbers Bar Chart",
            Subtitle = "Using a Chart as Image service...",
            Text = "Build and connect intelligent bots that have charts rendered as images.",
            Images = cardImages
        };

        return card;
    }
}


问:
How to use stanford word tokenizer in NLTK?
I am searching way to use stanford word tokenizer in nltk, I want to use because when I compare results of stanford and nltk word tokenizer, they both are different. I know there might be way to use stanford tokenizer, like we can stanford POS Tagger and NER in NLTK.

Is it possible to do use stanford tokenizer without running server?

Thanks

答:
Outside of NLTK, you can use the official Python interface that's recently release by Stanford NLP:

Install

```<code>cd ~
wget http://nlp.stanford.edu/software/stanford-corenlp-full-2016-10-31.zip
unzip stanford-corenlp-full-2016-10-31.zip && cd stanford-corenlp-full-2016-10-31
pip3 install -U https://github.com/stanfordnlp/python-stanford-corenlp/archive/master.zip
</code>```

Setup Environment

```<code># On Mac
export CORENLP_HOME=/Users/<username>/stanford-corenlp-full-2016-10-31/

# On linux
export CORENLP_HOME=/home/<username>/stanford-corenlp-full-2016-10-31/
</code>```

In Python

```<code>>>> import corenlp
>>> with corenlp.client.CoreNLPClient(annotators="tokenize ssplit".split()) as client:
...     ann = client.annotate(text)
...
[pool-1-thread-4] INFO CoreNLP - [/0:0:0:0:0:0:0:1:55475] API call w/annotators tokenize,ssplit
Chris wrote a simple sentence that he parsed with Stanford CoreNLP.
>>> sentence = ann.sentence[0]
>>>
>>> [token.word for token in sentence.token]
['Chris', 'wrote', 'a', 'simple', 'sentence', 'that', 'he', 'parsed', 'with', 'Stanford', 'CoreNLP', '.']
</code>```

Body:
Outside of NLTK, you can use the official Python interface that's recently release by Stanford NLP:

Install

cd ~
wget http://nlp.stanford.edu/software/stanford-corenlp-full-2016-10-31.zip
unzip stanford-corenlp-full-2016-10-31.zip && cd stanford-corenlp-full-2016-10-31
pip3 install -U https://github.com/stanfordnlp/python-stanford-corenlp/archive/master.zip

Setup Environment

# On Mac
export CORENLP_HOME=/Users/<username>/stanford-corenlp-full-2016-10-31/

# On linux
export CORENLP_HOME=/home/<username>/stanford-corenlp-full-2016-10-31/

In Python

>>> import corenlp
>>> with corenlp.client.CoreNLPClient(annotators="tokenize ssplit".split()) as client:
...     ann = client.annotate(text)
...
[pool-1-thread-4] INFO CoreNLP - [/0:0:0:0:0:0:0:1:55475] API call w/annotators tokenize,ssplit
Chris wrote a simple sentence that he parsed with Stanford CoreNLP.
>>> sentence = ann.sentence[0]
>>>
>>> [token.word for token in sentence.token]
['Chris', 'wrote', 'a', 'simple', 'sentence', 'that', 'he', 'parsed', 'with', 'Stanford', 'CoreNLP', '.']


问:
Designing for "Pretty" URLs
I'm aware of mod_rewrite methods to convert ugly URLs to pretty. My question is preceding this conversion.

I have not yet developed my website. I would like to design all pages such that the pretty URLs are also pretty on the server side.

I would like to come up with a general rule for ALL pages. Normally all pages are slightly different...

```<code>/news/12345                        =>    /news.php?id=1234
/members/Mikhail                   =>    /members.php?name=Mikhail
/subsection/page/banned-members    =>    /subsection/page.php?view=banned-members
</code>```

In the three examples above the GET variable name is different for each case, and the third example could ALSO be developed to be interpreted as /subsection.php?file=page&view=banned-members

So my question is: What can I do, from the design point, do have an elegant solution on the client AND server side to create pretty URLs?

Thanks!

答: In PHP, one possible solution is to have a central PHP file that processes all the URLs of the site. This script processes the whole URL strings and loads the relevant content. It allows all kinds of rewriting or redirecting to be done in PHP.</p>

ContentLicense: CC BY-SA 2.5

Title: Designing for "Pretty" URLs

Body:
I'm aware of mod_rewrite methods to convert ugly URLs to pretty. My question is preceding this conversion.

I have not yet developed my website. I would like to design all pages such that the pretty URLs are also pretty on the server side.

I would like to come up with a general rule for ALL pages. Normally all pages are slightly different...

/news/12345                        =>    /news.php?id=1234
/members/Mikhail                   =>    /members.php?name=Mikhail
/subsection/page/banned-members    =>    /subsection/page.php?view=banned-members

In the three examples above the GET variable name is different for each case, and the third example could ALSO be developed to be interpreted as /subsection.php?file=page&view=banned-members

So my question is: What can I do, from the design point, do have an elegant solution on the client AND server side to create pretty URLs?

Thanks!


问:
Create panel with two columns
I am trying to create a template that has two columns in a panel. I am using plainBootstrap v3.3.7. Below you can find what I tried:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

Overview

                    #

                    Product

                    Payment Taken

                    Status

                    1

                    TB - Monthly

                    01/04/2012

                    Default

                  Section 1

                  Section 2

                    I'm in Section 1.

                    Howdy, I'm in Section 2.

```

However, my panel look like the following on my screen:

As you can see, in my panel the two columns inside overlap.

Any suggestions why my table and the section overlap so much?

I appreciate your replies!

答:
The problem is your columns, wrap both the table and the section in
In the bootstrap grid system when you define

, This is a full grid (bootstrap maximum grid) so in order to get two equal columns out of this, you just define two columns with

. Reference

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

                    Overview

                                        #

                                        Product

                                        Payment Taken

                                        Status

                                        1

                                        TB - Monthly

                                        01/04/2012

                                        Default

                                        Section 1

                                        Section 2

                                        I'm in Section 1.

                                        Howdy, I'm in Section 2.

```

Note: Run the snippet as Full page

Title: Create panel with two columns

Body:
I am trying to create a template that has two columns in a panel. I am using plainBootstrap v3.3.7. Below you can find what I tried:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

Overview

                    #

                    Product

                    Payment Taken

                    Status

                    1

                    TB - Monthly

                    01/04/2012

                    Default

                  Section 1

                  Section 2

                    I'm in Section 1.

                    Howdy, I'm in Section 2.

However, my panel look like the following on my screen:

As you can see, in my panel the two columns inside overlap.

Any suggestions why my table and the section overlap so much?

I appreciate your replies!

Body:
The problem is your columns, wrap both the table and the section in  <div class="col-md-6">In the bootstrap grid system when you define <div class="col-md-12"></div>, This is a full grid (bootstrap maximum grid) so in order to get two equal columns out of this, you just define two columns with <div class="col-md-6"></div>. Reference

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="panel panel-default">
                <div class="panel-heading">
                    Overview
                </div>
                <div class="panel-body">
                </div>
                <div class="container-fluid">
                    <div class="col-md-6">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>
                                        #
                                    </th>
                                    <th>
                                        Product
                                    </th>
                                    <th>
                                        Payment Taken
                                    </th>
                                    <th>
                                        Status
                                    </th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>
                                        1
                                    </td>
                                    <td>
                                        TB - Monthly
                                    </td>
                                    <td>
                                        01/04/2012
                                    </td>
                                    <td>
                                        Default
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <div class="col-md-6">
                        <div class="tabbable" id="tabs-305570">
                            <ul class="nav nav-tabs">
                                <li class="active">
                                    <a href="#panel-495769" data-toggle="tab">
                                        Section 1
                                    </a>
                                </li>
                                <li>
                                    <a href="#panel-207616" data-toggle="tab">
                                        Section 2
                                    </a>
                                </li>
                            </ul>
                            <div class="tab-content">
                                <div class="tab-pane active" id="panel-495769">
                                    <p>
                                        I'm in Section 1.
                                    </p>
                                </div>
                                <div class="tab-pane" id="panel-207616">
                                    <p>
                                        Howdy, I'm in Section 2.
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </div>

Note: Run the snippet as Full page


问:
.Net MemoryCache AbsoluteExpiration documentation is confusing
When adding cache entry to System.Runtime.Caching.MemoryCache, you can specify CacheItemPolicy with AbsoluteExpiration. According to documentation (https://msdn.microsoft.com/en-us/library/Dd780607(v=VS.110,d=hv.2).aspx), AbsoluteExpiration is "The period of time that must pass before a cache entry is evicted".

Yes that's what I want - to specify "the period of time" after which my cache entry will expire. But AbsoluteExpiration is of type DateTimeOffset not TimeSpan, so it's a "point in time" not "period of time". How should I set it then? E.g. if I want the entry to expire in 60 sec, should I be setting AbsoluteExpiration to DateTimeOffset.UtcNow.AddSeconds(60)? Will I get the same result if I set it to DateTimeOffset.Now.AddSeconds(60)? Any reason to use one or the other?

答:
Well yes, the phrase "after a specified duration" in documentation is a little bit confusing but DateTimeOffset type and AbsoluteExpiration property name leave no doubt.

As regards the way how to construct instance of a DateTimeOffset: there is no actually any difference in this case. DateTimeOffset.UtcNow.AddSeconds(60) and DateTimeOffset.Now.AddSeconds(60) will point to the same absolute time. These datetimes will differ by time zones but the moment of cache entry expiration will be the same in both cases. So there is no any reason to prefer one or another.


问:
DebugElement is undefined in angular2 test
I am trying angular2 testing first time.

```<code>  let component: AlertButtonComponent;
  let fixture: ComponentFixture<AlertButtonComponent>;
  let de:DebugElement;

  it('should have an H1 tag of `Alert Button`' ,() => {
    console.log('debug element',de)
    expect(de.query(By.css('h1')).nativeElement.innerText).toBe('lert Button')
  })
</code>```

I am getting error typeError: Cannot read property 'query' of undefined also de is undefined.

Please help

答:
Check here : https://angular.io/guide/testing - testing in angular

Checked on angular website that you need to setup as below , if you are testing component BannerComponent, id dont see that kind of setup in you code

```<code> let comp:    BannerComponent;
  let fixture: ComponentFixture<BannerComponent>;
  let de:      DebugElement;
  let el:      HTMLElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [ BannerComponent ], // declare the test component
    });

fixture = TestBed.createComponent(BannerComponent);
comp = fixture.componentInstance; // BannerComponent test instance
// query for the title <h1> by CSS element selector
de = fixture.debugElement.query(By.css('h1'));
</code>```

Well error says that  let de:DebugElement; is undefined means you need to initialize it. something like

```<code> let de:DebugElement = new DebugElement();
</code>```

or  you have to pass service reference if you are using.

ContentLicense: CC BY-SA 4.0

Body:
I am trying angular2 testing first time.

  let component: AlertButtonComponent;
  let fixture: ComponentFixture<AlertButtonComponent>;
  let de:DebugElement;

  it('should have an H1 tag of `Alert Button`' ,() => {
    console.log('debug element',de)
    expect(de.query(By.css('h1')).nativeElement.innerText).toBe('lert Button')
  })

I am getting error typeError: Cannot read property 'query' of undefined also de is undefined.

Please help

Body:
Check here : https://angular.io/guide/testing - testing in angular

Checked on angular website that you need to setup as below , if you are testing component BannerComponent, id dont see that kind of setup in you code

 let comp:    BannerComponent;
  let fixture: ComponentFixture<BannerComponent>;
  let de:      DebugElement;
  let el:      HTMLElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [ BannerComponent ], // declare the test component
    });

fixture = TestBed.createComponent(BannerComponent);
comp = fixture.componentInstance; // BannerComponent test instance
// query for the title <h1> by CSS element selector
de = fixture.debugElement.query(By.css('h1'));

Well error says that  let de:DebugElement; is undefined means you need to initialize it. something like

 let de:DebugElement = new DebugElement();

or  you have to pass service reference if you are using.


问:
Unable to fetch Stream of Strings and pass it as a parameter to another method which returns int
```<code>public class JavaStreamMultIterator {

    public static void main(String[] args) {
    }

    private void iterateStringList() {
        List<String> stringList = Arrays.asList("one", "two", "three");

        List<Integer> intList = new ArrayList<>();
        intList = stringList
                .stream()
                .forEach(s - > {intForString(s));
                .collect(Collectors.toList());
    }

    private Integer intForString(String s) {

        switch (s) {
            case "one":
                return 1;
            case "two":
                return 2;
            case "three":
                return 3;
            default:
                return 15;
        }
    }
}
</code>```

I have a List<String> and I want to iterate through this list, fetch the String and pass it as a parameter to method.

That method will return an Integer and I want to add it to a List<Integer>.

```<code>intList = stringList
            .stream()
            .forEach(s - > {intForString(s));
            .collect(Collectors.toList());
</code>```

答:
Try use map

```<code>stringList.stream()
            .map(s->intForString(s))
            .collect(Collectors.toList());
</code>```

Body:
public class JavaStreamMultIterator {

    public static void main(String[] args) {
    }

    private void iterateStringList() {
        List<String> stringList = Arrays.asList("one", "two", "three");

        List<Integer> intList = new ArrayList<>();
        intList = stringList
                .stream()
                .forEach(s - > {intForString(s));
                .collect(Collectors.toList());
    }

    private Integer intForString(String s) {

        switch (s) {
            case "one":
                return 1;
            case "two":
                return 2;
            case "three":
                return 3;
            default:
                return 15;
        }
    }
}

I have a List<String> and I want to iterate through this list, fetch the String and pass it as a parameter to method.

That method will return an Integer and I want to add it to a List<Integer>.

intList = stringList
            .stream()
            .forEach(s - > {intForString(s));
            .collect(Collectors.toList());

Body:
Try use map

stringList.stream()
            .map(s->intForString(s))
            .collect(Collectors.toList());


问:
Node.js MYSQLparse error
I have the following code

```<code>db.query("SELECT * FROM ?", [req.params.Tables_in_my_db], function(error, rows, fields) {
    if (error)
        throw error;

    //code...

    db.end();
});
</code>```

When I run this code I get the following error

Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Copy'' at line 1

However, if I log in the console req.params.Tables_in_my_db, I get the String Copy. How can I solve this issue?

Thank you.

答:
I guess "?" will only work with values to be substituted, (SELECT * FROM table_name WHERE column_name=?), if you want to have a dynamic table, use if statement and concatenate your desired table to the string, then pass that string to the first param of db.query().</p>

```<code>var query = "SELECT * FROM";
if (req.params.table_code == 1) {
     query += " your_desired_table";
} else if (req.params.table_code == 2) {
     query += " another_desired_table";
} else {
     //return an error here to avoid sql injection, use a code for each of
     //the table you only want to use
}

db.query(query, ....
</code>```

Title: Node.js MYSQLparse error

Body:
I have the following code

db.query("SELECT * FROM ?", [req.params.Tables_in_my_db], function(error, rows, fields) {
    if (error)
        throw error;

    //code...

    db.end();
});

When I run this code I get the following error

Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Copy'' at line 1

However, if I log in the console req.params.Tables_in_my_db, I get the String Copy. How can I solve this issue?

Thank you.

Body:
I guess "?" will only work with values to be substituted, (SELECT * FROM table_name WHERE column_name=?), if you want to have a dynamic table, use if statement and concatenate your desired table to the string, then pass that string to the first param of db.query().

var query = "SELECT * FROM";
if (req.params.table_code == 1) {
     query += " your_desired_table";
} else if (req.params.table_code == 2) {
     query += " another_desired_table";
} else {
     //return an error here to avoid sql injection, use a code for each of
     //the table you only want to use
}

db.query(query, ....


问:
Using glmnet to predict a continuous variable in a dataset
I have this data set.
wbh

I wanted to use the R package glmnet to determine which predictors would be useful in predicting fertility. However, I have been unable to do so, most likely due to not having a full understanding of the package. The fertility variable is SP.DYN.TFRT.IN. I want to see which predictors in the data set give the most predictive power for fertility. I wanted to use LASSO or ridge regression to shrink the number of coefficients, and I know this package can do that. I'm just having some trouble implementing it.

I know there are no code snippets which I apologize for but I am rather lost on how I would code this out.

Any advice is appreciated.

Thank you for reading

答:
Here is an example on how to run glmnet:

```<code>library(glmnet)
library(tidyverse)
</code>```

df is the data set your provided.

select y variable:

```<code>y <- df$SP.DYN.TFRT.IN
</code>```

select numerical variables:

```<code>df %>%
  select(-SP.DYN.TFRT.IN, -region, -country.code) %>%
  as.matrix() -> x
</code>```

select factor variables and convert to dummy variables:

```<code>df %>%
  select(region, country.code) %>%
  model.matrix( ~ .-1, .) -> x_train
</code>```

run model(s), several parameters here can be tweaked I suggest checking the documentation. Here I just run 5-fold cross validation to determine the best lambda

```<code>cv_fit <- cv.glmnet(x, y, nfolds = 5) #just with numeric variables

cv_fit_2 <- cv.glmnet(cbind(x ,x_train), y, nfolds = 5) #both factor and numeric variables

par(mfrow = c(2,1))
plot(cv_fit)
plot(cv_fit_2)
</code>```

best lambda:

```<code>cv_fit$lambda[which.min(cv_fit$cvm)]
</code>```

coefficients at best lambda

```<code>coef(cv_fit, s = cv_fit$lambda[which.min(cv_fit$cvm)])
</code>```

equivalent to:

```<code>coef(cv_fit, s = "lambda.min")
</code>```

after running coef(cv_fit, s = "lambda.min") all features with - in the resulting table are dropped from the model. This situation corresponds to the left lambda depicted with the left vertical dashed line on the plots.

I suggest reading the linked documentation - elastic nets are quite easy to grasp if you know a bit of linear regression and the package is quite intuitive. I also suggest reading ISLR, at least the part with L1 / L2 regularization. and these videos: 1, 2, 3 4, 5, 6, first three are about estimating model performance via test error and the last three are about the question at hand. This one is how to implement these models in R. By the way these guys on the videos invented LASSO and made glment.

Also check the glmnetUtils library which provides a formula interface and other nice things like in built mixing parameter (alpha) selection. Here is the vignette.

Body:
Here is an example on how to run glmnet:

library(glmnet)
library(tidyverse)

df is the data set your provided.

select y variable:

y <- df$SP.DYN.TFRT.IN

select numerical variables:

df %>%
  select(-SP.DYN.TFRT.IN, -region, -country.code) %>%
  as.matrix() -> x

select factor variables and convert to dummy variables:

df %>%
  select(region, country.code) %>%
  model.matrix( ~ .-1, .) -> x_train

run model(s), several parameters here can be tweaked I suggest checking the documentation. Here I just run 5-fold cross validation to determine the best lambda

cv_fit <- cv.glmnet(x, y, nfolds = 5) #just with numeric variables

cv_fit_2 <- cv.glmnet(cbind(x ,x_train), y, nfolds = 5) #both factor and numeric variables

par(mfrow = c(2,1))
plot(cv_fit)
plot(cv_fit_2)

best lambda:

cv_fit$lambda[which.min(cv_fit$cvm)]

coefficients at best lambda

coef(cv_fit, s = cv_fit$lambda[which.min(cv_fit$cvm)])

equivalent to:

coef(cv_fit, s = "lambda.min")

after running coef(cv_fit, s = "lambda.min") all features with - in the resulting table are dropped from the model. This situation corresponds to the left lambda depicted with the left vertical dashed line on the plots.

I suggest reading the linked documentation - elastic nets are quite easy to grasp if you know a bit of linear regression and the package is quite intuitive. I also suggest reading ISLR, at least the part with L1 / L2 regularization. and these videos: 1, 2, 3 4, 5, 6, first three are about estimating model performance via test error and the last three are about the question at hand. This one is how to implement these models in R. By the way these guys on the videos invented LASSO and made glment.

Also check the glmnetUtils library which provides a formula interface and other nice things like in built mixing parameter (alpha) selection. Here is the vignette.


问:
Add a single field to model using raw SQL
I'm developing an extension for TYPO3 CMS 8.7.8. I'm using query->statement() to select all fields from a single table, plus 1 field from another table. I get a QueryResult with the proper models and I would like to have that 1 extra field added to them. Is that possible?

答:
You can use JOIN in your sql statments like below.

```<code>$query = $this->createQuery();
$sql = 'SELECT single.*,another.field_anme AS fields_name
        FROM
           tx_single_table_name single
        JOIN
           tx_another_table_name another
        ON
           single.fields = another.uid
        WHERE
           O.deleted = 0
        AND O.hidden=0
        AND O.uid=' . $orderId;
return $query->statement($sql)->execute();
</code>```

Body:
You can use JOIN in your sql statments like below.

$query = $this->createQuery();
$sql = 'SELECT single.*,another.field_anme AS fields_name
        FROM
           tx_single_table_name single
        JOIN
           tx_another_table_name another
        ON
           single.fields = another.uid
        WHERE
           O.deleted = 0
        AND O.hidden=0
        AND O.uid=' . $orderId;
return $query->statement($sql)->execute();


问:
Encoding of three way inclusive-or type in Scala
I have some data that consists of three fields, let's say a String, an Int, and a Double.

They are all optional, but the whole thing must contain at least one of those fields.

I've tried cats.data.Ior, like type MyType = String Ior Int Ior Double. It works, but it feels a little bit clumsy when actually doing stuffs with it. Creating a case class with three Options and throwing an exception at the constructor if they are all None should kinda work too, but I don't like the idea.

I'm curious to know if there might be some other way to do this (preferably, by encoding the whole information only in the types like Ior but with less complexity so that using values of the type is not as complicated). Suggestions to use any other libraries are also welcome.

答:
You probably thought of this idea as well, but what about something like this:

```<code>class StringOrIntOrDouble private(val first: Option[String], val second: Option[Int], val third: Option[Double]) {
  def this(first: String) = this(Some(first), None, None)

  def this(second: Int) = this(None, Some(second), None)

  def this(third: Double) = this(None, None, Some(third))

  def this(first: String, second: Int) = this(Some(first), Some(second), None)

  def this(second: Int, third: Double) = this(None, Some(second), Some(third))

  def this(first: String, third: Double) = this(Some(first), None, Some(third))

  def this(first: String, second: Int, third: Double) = this(Some(first), Some(second), Some(third))

}
</code>```

The main constructor is private so you can't create an empty instance. Obviously you could extend it with implementation of Product and equals, hashCode, toString and other useful things as case classes do (but beware of copy that might easily break the invariant).

Unfortunately, if you want a generic version (or you have the same type in two places) you have to move all the "subset" constructors to a named methods to a companion object or it would not compile because of type erasure.

```<code>class TripleIor[+A, +B, +C] private(val first: Option[A], val second: Option[B], val third: Option[C]) {

}

object TripleIor {
  def first[A](first: A) = new TripleIor[A, Nothing, Nothing](Some(first), None, None)

  def second[B](second: B) = new TripleIor[Nothing, B, Nothing](None, Some(second), None)

  def third[C](third: C) = new TripleIor[Nothing, Nothing, C](None, None, Some(third))

  def firstAndSecond[A, B](first: A, second: B) = new TripleIor[A, B, Nothing](Some(first), Some(second), None)

  def secondAndThird[B, C](second: B, third: C) = new TripleIor[Nothing, B, C](None, Some(second), Some(third))

  def firstAndThird[A, C](first: A, third: C) = new TripleIor[A, Nothing, C](Some(first), None, Some(third))

  def apply[A, B, C](first: A, second: B, third: C) = new TripleIor[A, B, C](Some(first), Some(second), Some(third))
}
</code>```

A more radical way would be to implement the same idea as a sealed trait and 7 subclasses but I don't think they would be much easier to use. Also it will let you to implement copy in a type-safe way but a the cost of a lot of typing (not shown here).

```<code>sealed trait TripleIor[A, B, C] extends Product {
  def firstOption: Option[A]

  def secondOption: Option[B]

  def thirdOption: Option[C]
}

object TripleIor {

  final case class First[A](first: A) extends TripleIor[A, Nothing, Nothing] {
    override def firstOption: Option[A] = Some(first)

    override def secondOption: Option[Nothing] = None

    override def thirdOption: Option[Nothing] = None
  }

  final case class Second[B](second: B) extends TripleIor[Nothing, B, Nothing] {
    override def firstOption: Option[Nothing] = None

    override def secondOption: Option[B] = Some(second)

    override def thirdOption: Option[Nothing] = None
  }

  final case class Third[C](third: C) extends TripleIor[Nothing, Nothing, C] {
    override def firstOption: Option[Nothing] = None

    override def secondOption: Option[Nothing] = None

    override def thirdOption: Option[C] = Some(third)
  }

  final case class FirstSecond[A, B](first: A, second: B) extends TripleIor[A, B, Nothing] {
    override def firstOption: Option[A] = Some(first)

    override def secondOption: Option[B] = Some(second)

    override def thirdOption: Option[Nothing] = None
  }

  final case class SecondThird[B, C](second: B, third: C) extends TripleIor[Nothing, B, C] {
    override def firstOption: Option[Nothing] = None

    override def secondOption: Option[B] = Some(second)

    override def thirdOption: Option[C] = Some(third)
  }

  final case class FirstThird[A, C](first: A, third: C) extends TripleIor[A, Nothing, C] {
    override def firstOption: Option[A] = Some(first)

    override def secondOption: Option[Nothing] = None

    override def thirdOption: Option[C] = Some(third)
  }

  final case class All[A, B, C](first: A, second: B, third: C) extends TripleIor[A, B, C] {
    override def firstOption: Option[A] = Some(first)

    override def secondOption: Option[B] = Some(second)

    override def thirdOption: Option[C] = Some(third)
  }
}
</code>```

P.S. Beware that all examples here are just sketches to illustrate the idea that don't implement many useful or even required things

Body:
You probably thought of this idea as well, but what about something like this:

class StringOrIntOrDouble private(val first: Option[String], val second: Option[Int], val third: Option[Double]) {
  def this(first: String) = this(Some(first), None, None)

  def this(second: Int) = this(None, Some(second), None)

  def this(third: Double) = this(None, None, Some(third))

  def this(first: String, second: Int) = this(Some(first), Some(second), None)

  def this(second: Int, third: Double) = this(None, Some(second), Some(third))

  def this(first: String, third: Double) = this(Some(first), None, Some(third))

  def this(first: String, second: Int, third: Double) = this(Some(first), Some(second), Some(third))

}

The main constructor is private so you can't create an empty instance. Obviously you could extend it with implementation of Product and equals, hashCode, toString and other useful things as case classes do (but beware of copy that might easily break the invariant).

Unfortunately, if you want a generic version (or you have the same type in two places) you have to move all the "subset" constructors to a named methods to a companion object or it would not compile because of type erasure.

class TripleIor[+A, +B, +C] private(val first: Option[A], val second: Option[B], val third: Option[C]) {

}

object TripleIor {
  def first[A](first: A) = new TripleIor[A, Nothing, Nothing](Some(first), None, None)

  def second[B](second: B) = new TripleIor[Nothing, B, Nothing](None, Some(second), None)

  def third[C](third: C) = new TripleIor[Nothing, Nothing, C](None, None, Some(third))

  def firstAndSecond[A, B](first: A, second: B) = new TripleIor[A, B, Nothing](Some(first), Some(second), None)

  def secondAndThird[B, C](second: B, third: C) = new TripleIor[Nothing, B, C](None, Some(second), Some(third))

  def firstAndThird[A, C](first: A, third: C) = new TripleIor[A, Nothing, C](Some(first), None, Some(third))

  def apply[A, B, C](first: A, second: B, third: C) = new TripleIor[A, B, C](Some(first), Some(second), Some(third))
}

A more radical way would be to implement the same idea as a sealed trait and 7 subclasses but I don't think they would be much easier to use. Also it will let you to implement copy in a type-safe way but a the cost of a lot of typing (not shown here).

sealed trait TripleIor[A, B, C] extends Product {
  def firstOption: Option[A]

  def secondOption: Option[B]

  def thirdOption: Option[C]
}

object TripleIor {

  final case class First[A](first: A) extends TripleIor[A, Nothing, Nothing] {
    override def firstOption: Option[A] = Some(first)

    override def secondOption: Option[Nothing] = None

    override def thirdOption: Option[Nothing] = None
  }

  final case class Second[B](second: B) extends TripleIor[Nothing, B, Nothing] {
    override def firstOption: Option[Nothing] = None

    override def secondOption: Option[B] = Some(second)

    override def thirdOption: Option[Nothing] = None
  }

  final case class Third[C](third: C) extends TripleIor[Nothing, Nothing, C] {
    override def firstOption: Option[Nothing] = None

    override def secondOption: Option[Nothing] = None

    override def thirdOption: Option[C] = Some(third)
  }

  final case class FirstSecond[A, B](first: A, second: B) extends TripleIor[A, B, Nothing] {
    override def firstOption: Option[A] = Some(first)

    override def secondOption: Option[B] = Some(second)

    override def thirdOption: Option[Nothing] = None
  }

  final case class SecondThird[B, C](second: B, third: C) extends TripleIor[Nothing, B, C] {
    override def firstOption: Option[Nothing] = None

    override def secondOption: Option[B] = Some(second)

    override def thirdOption: Option[C] = Some(third)
  }

  final case class FirstThird[A, C](first: A, third: C) extends TripleIor[A, Nothing, C] {
    override def firstOption: Option[A] = Some(first)

    override def secondOption: Option[Nothing] = None

    override def thirdOption: Option[C] = Some(third)
  }

  final case class All[A, B, C](first: A, second: B, third: C) extends TripleIor[A, B, C] {
    override def firstOption: Option[A] = Some(first)

    override def secondOption: Option[B] = Some(second)

    override def thirdOption: Option[C] = Some(third)
  }
}

P.S. Beware that all examples here are just sketches to illustrate the idea that don't implement many useful or even required things


问:
display:none property not working in firefox and chrome
```<code><tr style="height:5px" id="TRRSHeaderTrialBar" name="TRRSHeaderTrialBar" style='display:none'>
<tr id="TREmail" name="TREmail"  style="height:1px;" nowrap style='display:none'>
</code>```

i use the above code to hide the bar and it is working fine in IE but not in firefox and chrome
so i used

```<code>document.getElementById("TREmail").style.display = "none";
document.getElementById("TRRSHeaderTrialBar").style.display = "none";
</code>```

TRRSHeaderTrialBar contains tabpages and TREmail contain two buttons.
When the page loads, TRRSHeaderTrialBar works fine but TREmail shows the buttons when the page starts loading. After loading is finished, it hides.

I want to hide that buttons when page is loading.

答:
```<code>varvalidated = document.forms(0).validated.value;

if(varvalidated == 0)
{
    document.getElementById("k1").style.display = "none";
}
else
{
    document.getElementById("t1").style.display = "none";
}
</code>```

Body:
i use the above code to hide the bar and it is working fine in IE but not in firefox and chrome
so i used

document.getElementById("TREmail").style.display = "none";
document.getElementById("TRRSHeaderTrialBar").style.display = "none";

TRRSHeaderTrialBar contains tabpages and TREmail contain two buttons.
When the page loads, TRRSHeaderTrialBar works fine but TREmail shows the buttons when the page starts loading. After loading is finished, it hides.

I want to hide that buttons when page is loading.


问:
Extended Search
So I've got a big text file which looks like the following:

```<code>text;text;text;text;text - 5 words
text;text;text;text;text;text - 6 words
text;text;text;text;text;text;text - 7 words
</code>```

How i can search lines with 6, 7,... words?

I try search with (.*);(.*);(.*);(.*);(.*);(.*); but not work :(

答: Don't abuse the *. If you are trying to match at least one character, .+ is less ambiguous. In fact, if ; is the separator, you can try [^;]+ to be even more pedantic.</p>

Title: Extended Search

Body:
So I've got a big text file which looks like the following:

text;text;text;text;text - 5 words
text;text;text;text;text;text - 6 words
text;text;text;text;text;text;text - 7 words

How i can search lines with 6, 7,... words?

I try search with (.*);(.*);(.*);(.*);(.*);(.*); but not work :(


问:
Overloaded method value udf with alternatives
I am trying to register a table in Databricks Community Edition using the following code:

```<code>import org.apache.spark.sql.functions.udf

val getDataUDF(url: String):Unit = udf(getData(url: String):Unit)
</code>```

However, I get an error:

overloaded method value udf with alternatives:

答:
Your UDF syntax looks a bit strange, you shouldn't define the type when calling getData(). In addtion, the input to the UDF should be inside the method itself.

For example, you have a method getData like this (it should have a return value):

```<code>def getData(url: String): String = {...}
</code>```

To make it into an udf, there are two ways:

Rewrite getData as a function

```<code>val getData: (String => String) = {...}
val getDataUDF = udf(getData)
</code>```

Call the getData method inside the udf

```<code>val getDataUDF = udf((url: String) => {
  getData(url)
})
</code>```

Both of these ways should work, personally I think method 1 looks a bit better.

Body:
I am trying to register a table in Databricks Community Edition using the following code:

import org.apache.spark.sql.functions.udf

val getDataUDF(url: String):Unit = udf(getData(url: String):Unit)

However, I get an error:

overloaded method value udf with alternatives:

Body:
Your UDF syntax looks a bit strange, you shouldn't define the type when calling getData(). In addtion, the input to the UDF should be inside the method itself.

For example, you have a method getData like this (it should have a return value):

def getData(url: String): String = {...}

To make it into an udf, there are two ways:

Rewrite getData as a function

val getData: (String => String) = {...}
val getDataUDF = udf(getData)

Call the getData method inside the udf

val getDataUDF = udf((url: String) => {
  getData(url)
})

Both of these ways should work, personally I think method 1 looks a bit better.


问:
Uploaded image name need to change
After Uploading image it shows date in the name of image in uploadfolder.Instead

need to show ward number which is posted in $ward.The commentline was i changed

but its not working.please help me.

```<code>$image_name = "img_"."_".date("Y-m-d-H-m-s").".png";

// $image_name = "img_"."_".$ward.".png";
</code>```

答:
Try following code</p>

```<code>$ward = $_POST['ward'];
$tmp_name = $_FILES["image"]["tmp_name"];//name of your input file name
$uploads_dir = "Your Upload idrectory path";
$image_name = "img__".$ward.".png";

move_uploaded_file($tmp_name, "$uploads_dir/$image_name");
</code>```

Title: Uploaded image name need to change

Body:
After Uploading image it shows date in the name of image in uploadfolder.Instead

need to show ward number which is posted in $ward.The commentline was i changed

but its not working.please help me.

$image_name = "img_"."_".date("Y-m-d-H-m-s").".png";

// $image_name = "img_"."_".$ward.".png";

Body:
Try following code

$ward = $_POST['ward'];
$tmp_name = $_FILES["image"]["tmp_name"];//name of your input file name
$uploads_dir = "Your Upload idrectory path";
$image_name = "img__".$ward.".png";

move_uploaded_file($tmp_name, "$uploads_dir/$image_name");


问:
Angularjs clear filter for ng-repeat
I have this ng-repeat condition:

```<code><tr ng-repeat="(k, v) in loanapps | filter:{LoanStatus:SelectedStatus}:true track by $index">
    <td>
        {{v.Id}}
    </td>
    <td>
        {{v.Name}}
    </td>
</tr>
</code>```

Filtering works fine when I have SelectedStatus value. Now I also want to reset the filter and display all the results.

I have this button click function:

```<code>$scope.ResetStatusFilter = function() {
    $scope.SelectedStatus = null;
}
</code>```

I also tried:

```<code>$scope.ResetStatusFilter = function() {
    $scope.SelectedStatus = '';
}
</code>```

But what this is doing is clearing out all the results.

Is there anyway how can I display all the results and exclude the filter once the button is clicked?

The select list is this one:

```<code><select ng-model="SelectedStatus">
    <option value="Under Review">Under Review</option>
    <option value="Waiting for Meeting">Waiting for Meeting</option>
    <option value="Processing">Processing</option>
</select>
</code>```

答:
instead of using  filter:{LoanStatus:SelectedStatus}:true to  filter:SelectedStatus.

you can clear your filter by using

```<code>$scope.SelectedStatus ={}
</code>```

it will clear the filter

Title: Angularjs clear filter for ng-repeat

Body:
I have this ng-repeat condition:

        {{v.Id}}

        {{v.Name}}

Filtering works fine when I have SelectedStatus value. Now I also want to reset the filter and display all the results.

I have this button click function:

$scope.ResetStatusFilter = function() {
    $scope.SelectedStatus = null;
}

I also tried:

$scope.ResetStatusFilter = function() {
    $scope.SelectedStatus = '';
}

But what this is doing is clearing out all the results.

Is there anyway how can I display all the results and exclude the filter once the button is clicked?

The select list is this one:

<select ng-model="SelectedStatus">
    <option value="Under Review">Under Review</option>
    <option value="Waiting for Meeting">Waiting for Meeting</option>
    <option value="Processing">Processing</option>
</select>

Body:
instead of using  filter:{LoanStatus:SelectedStatus}:true to  filter:SelectedStatus.

you can clear your filter by using

$scope.SelectedStatus ={}

it will clear the filter


问:
Wcf Service Failed to found the End Point on Local Host
I am consuming the wcf Rest Service into Angular JS Application . I created several methods to perform the operation. First I have the wcf service with class library project and i created another wcf service project to host it in local IIS.
When i run the wcf service on local host its works fine but the problem is with the url when i typed the method name its throws exceptions that the End point not found . For example   http://localhost:52098/HalifaxIISService.svc/GetCustomers// Error the end point not found .

Here is my interface..

```<code>  [OperationContract]

        [WebInvoke(Method = "POST",
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        UriTemplate = "/GetCustomers")]
        string GetCustomers(string prefix);

        [OperationContract]
       [WebInvoke(Method = "POST",
       RequestFormat = WebMessageFormat.Json,
       ResponseFormat = WebMessageFormat.Json,
       UriTemplate = "/GetAccountDetails")]
        bool GetAccountDetails(string Account_Number);
</code>```

Here is app.cong file in class library project .

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>

    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="DBCS" connectionString="Data Source=;Initial Catalog=HalifaxDatabase;Integrated Security=True" providerName="System.Data.SqlClient" />
  <add name="HalifaxDatabaseEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=;initial catalog=HalifaxDatabase;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /></connectionStrings>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service name="HalifaxWCFProject.HalifaxService">
        <endpoint address="" binding="webHttpBinding" contract="HalifaxWCFProject.IHalifaxService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8733/Design_Time_Addresses/HalifaxWCFProject/HalifaxService/" />
          </baseAddresses>
        </host>
      </service>
    </services>
  </system.serviceModel>

  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>
</code>```

Here is service.svc code for IIS  .

```<code><%@ ServiceHost Language="C#" Debug="true" Service="HalifaxWCFProject.HalifaxService"%>
</code>```

Here is the web.config for .svc file..

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="DBCS" connectionString="Data Source=;Initial Catalog=HalifaxDatabase;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="HalifaxDatabaseEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=;initial catalog=HalifaxDatabase;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
  </connectionStrings>
  <system.serviceModel>
    <services>
      <service name="HalifaxWCFProject.HalifaxService" behaviorConfiguration="mexBehaviour">
        <endpoint address="" binding="webHttpBinding" bindingConfiguration="" behaviorConfiguration="REST" contract="HalifaxWCFProject.IHalifaxService" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="mexBehaviour">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="REST">
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>
</code>```

Here is the screen shot .

I have defined the end point in web.config file . I am wondering i got this error the End point not Found .

答:
You receive the "endpoint not found" error because you've defined HTTP Post endpoints.  Therefore, you cannot test them in a web browser since it sends an HTTP Get request.

If you wish the test your service without writing any code, use Fiddler's Composer feature to send an HTTP Post request.

Fiddler Screenshot

Or change the WebInvoke attribute to allow an HTTP Get request.

```<code>[WebInvoke(Method = "GET",
  RequestFormat = WebMessageFormat.Json,
  ResponseFormat = WebMessageFormat.Json,
  UriTemplate = "/GetCustomers")]
</code>```

Body:
I am consuming the wcf Rest Service into Angular JS Application . I created several methods to perform the operation. First I have the wcf service with class library project and i created another wcf service project to host it in local IIS.
When i run the wcf service on local host its works fine but the problem is with the url when i typed the method name its throws exceptions that the End point not found . For example   http://localhost:52098/HalifaxIISService.svc/GetCustomers// Error the end point not found .

Here is my interface..

  [OperationContract]

        [WebInvoke(Method = "POST",
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        UriTemplate = "/GetCustomers")]
        string GetCustomers(string prefix);

        [OperationContract]
       [WebInvoke(Method = "POST",
       RequestFormat = WebMessageFormat.Json,
       ResponseFormat = WebMessageFormat.Json,
       UriTemplate = "/GetAccountDetails")]
        bool GetAccountDetails(string Account_Number);

Here is app.cong file in class library project .

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>

  </configSections>
  <connectionStrings>
    <add name="DBCS" connectionString="Data Source=;Initial Catalog=HalifaxDatabase;Integrated Security=True" providerName="System.Data.SqlClient" />
  <add name="HalifaxDatabaseEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=;initial catalog=HalifaxDatabase;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /></connectionStrings>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service name="HalifaxWCFProject.HalifaxService">
        <endpoint address="" binding="webHttpBinding" contract="HalifaxWCFProject.IHalifaxService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8733/Design_Time_Addresses/HalifaxWCFProject/HalifaxService/" />
          </baseAddresses>
        </host>
      </service>
    </services>
  </system.serviceModel>

  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

Here is service.svc code for IIS  .

<%@ ServiceHost Language="C#" Debug="true" Service="HalifaxWCFProject.HalifaxService"%>

Here is the web.config for .svc file..

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="DBCS" connectionString="Data Source=;Initial Catalog=HalifaxDatabase;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="HalifaxDatabaseEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=;initial catalog=HalifaxDatabase;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
  </connectionStrings>
  <system.serviceModel>
    <services>
      <service name="HalifaxWCFProject.HalifaxService" behaviorConfiguration="mexBehaviour">
        <endpoint address="" binding="webHttpBinding" bindingConfiguration="" behaviorConfiguration="REST" contract="HalifaxWCFProject.IHalifaxService" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="mexBehaviour">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="REST">
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

Here is the screen shot .

I have defined the end point in web.config file . I am wondering i got this error the End point not Found .

Body:
You receive the "endpoint not found" error because you've defined HTTP Post endpoints.  Therefore, you cannot test them in a web browser since it sends an HTTP Get request.

If you wish the test your service without writing any code, use Fiddler's Composer feature to send an HTTP Post request.

Fiddler Screenshot

Or change the WebInvoke attribute to allow an HTTP Get request.

[WebInvoke(Method = "GET",
  RequestFormat = WebMessageFormat.Json,
  ResponseFormat = WebMessageFormat.Json,
  UriTemplate = "/GetCustomers")]


问:
jQuery UI: Delay Loading AJAX Content Until Tab is Selected
I'd like to know if there's a way to prevent content from loading until a tab is selected when loading the content via AJAX.

I'm not sure if this is already the case and if it is then great! That means no extra work!

Any help or answers are very much appreciated :)

答: Yes there is an option for exactly that: http://jqueryui.com/demos/tabs/#ajax</p>


问:
Error: Could not find or load main class ... in Spring Boot 1.5.9 version but not in 1.4.7

I was trying to generate a starting spring boot project from https://start.spring.io/

When I use Spring Boot 1.5.9 version to generate the project I am getting the following

```<code>Error: Could not find or load main class com.example.demo120417.Demo120417Application
</code>```

However; changing the version to Spring Boot 1.4.7 loads and runs the main class with no error.

I have actuator, security, thymeleaf, devtools, h2 in the dependency.

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>
<artifactId>demo120417</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>demo120417</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</project>
</code>```

What could be the root cause for this? I spent almost 1 day trying to figure out if I had issue with build path. Usually having red exclamation mark on the project points me to the library issue.

答:
I had the same problem. Try this :

```<code>Right Click the project -> Maven -> Update Project
</code>```

Then Re-run the project.

Body:
I was trying to generate a starting spring boot project from https://start.spring.io/

When I use Spring Boot 1.5.9 version to generate the project I am getting the following

Error: Could not find or load main class com.example.demo120417.Demo120417Application

However; changing the version to Spring Boot 1.4.7 loads and runs the main class with no error.

I have actuator, security, thymeleaf, devtools, h2 in the dependency.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>
<artifactId>demo120417</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>demo120417</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
    <relativePath/>
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</project>

What could be the root cause for this? I spent almost 1 day trying to figure out if I had issue with build path. Usually having red exclamation mark on the project points me to the library issue.

Body:
I had the same problem. Try this :

Right Click the project -> Maven -> Update Project

Then Re-run the project.


问:
FROM_DAYS() not giving expected output[MySQL]
The official documentation says that FROM_DAYS returns a valid date given number of days N.

Then why is this happening ?

Should it not display the valid dates for days less than a year, like
from_days(5) = 0000-01-05 ?

Edit : I was solving a question which went as "Find the period an employee has worked given their date of joining and report the duration in the format years,months,days"

And I was using the following query :

```<code>select Emp_Name,
date_format(from_days(datediff(curdate(),Date_of_Join)),"%y") as year,
date_format(from_days(datediff(curdate(),Date_of_Join)),"%m") as month,
date_format(from_days(datediff(curdate(),Date_of_Join)),"%d") as day
from EMPLOYEE;
</code>```

It was in these results that I discovered this discrepancy.

答:
As the MySql manual reports:

The function is not designed for use with dates before the advent of
  the Gregorian calendar in October 1582. Results will not be reliable
  since it doesn't account for the lost days when the calendar changed
  from the Julian calendar.

So, if you set the argument of this function with a small number (around N < 1582*365), it is not reliable.

Body:
The official documentation says that FROM_DAYS returns a valid date given number of days N.

Then why is this happening ?

Should it not display the valid dates for days less than a year, like
from_days(5) = 0000-01-05 ?

Edit : I was solving a question which went as "Find the period an employee has worked given their date of joining and report the duration in the format years,months,days"

And I was using the following query :

select Emp_Name,
date_format(from_days(datediff(curdate(),Date_of_Join)),"%y") as year,
date_format(from_days(datediff(curdate(),Date_of_Join)),"%m") as month,
date_format(from_days(datediff(curdate(),Date_of_Join)),"%d") as day
from EMPLOYEE;

It was in these results that I discovered this discrepancy.


问:
What is my DCOS master hostname?
In the nginx tutorial for DC/OS:

https://dcos.io/docs/1.7/usage/tutorials/nginx/

There is repeated reference to this URL:

http://YOUR-DCOS-MASTER-HOSTNAME/service/nginx

However, I cannot find any mention of what my dcos master hostname is anywhere in the documentation.

I can access the nginx service via going onto m1.dcos/mesos, finding the IP address of the service, and typing that into the browser.

However, I feel like that is not the point of the tutorial and that there is some missing information in the documentation as to what YOUR-DCOS-MASTER-HOSTNAME actually refers to.

How do I find out what my DCOS-MASTER-HOSTNAME is?

答:
It’s the Hostname or IP address of the node on which you installed the master on. Simple as that.

Also, please be aware that you are referring to very outdated docs. The current release is 1.10, and not 1.7

Title: What is my DCOS master hostname?


答:
I believe you are doing it for the first time . you need to fill up the fields than leaving them to default
eg:

Group

```<code>com.myapp
</code>```

Artifact

```<code>myapp
</code>```

you need to fill there fields before genearting the project

Title: Error: Could not find or load main class ... in Spring Boot 1.5.9 version but not in 1.4.7

Body:
I believe you are doing it for the first time . you need to fill up the fields than leaving them to default
eg:

Group

com.myapp

Artifact

myapp

you need to fill there fields before genearting the project


问:
How to update ListView without freezing the program
So I have a list of strings (ISBNs), and I need to fill a listview with the objects (Book objects) associated with these strings. The problem is that the function I have to get the Book object using the string takes time, and so to get, say 30 books, the wait approaches 4 or 5 seconds.

One approach I've thought of is to get the Book objects one at a time, and to add them to the list as I get them. But this process will freeze the UI until it's done adding them all. If I try to put this process in a new thread, it won't let me add to the any UI objects (since it's from another thread). If I try to put it in an AsyncTask, I can't access the ListView since it's in the MainActivity class.

There must be a way to dynamically update a UI element, I'm sure I've seen it done. Any suggestions?

EDIT:

This is the code I'm using to actually add items to the list:

```<code>//List view and adapter setup
listView = (ListView) findViewById(R.id.listViewCheckout);
bookAdapter = new SearchBookAdapter(getApplicationContext(), R.layout.search_row_layout);
listView.setAdapter(bookAdapter);

for(int i = 0; i < searches.size(); i++) {

    //Get the book
    Book book = BackendFunctions.getBookFromISBN(fbSnapshot, searches.get(i));

    //Assign data to the adapter variables
    Bitmap cover = book.getCover();
    String title = book.getTitle();
    String author = book.getAuthor();

    //Add data to the adapter and set the list
    SearchBookDataProvider dataProvider = new SearchBookDataProvider(cover, title, author);
    bookAdapter.add(dataProvider);
    bookAdapter.notifyDataSetChanged();
}
</code>```

答:
Step 1: Declare a Executer service

```<code> private ExecutorService mExecuterService = null;
</code>```

Step 2:Declare a class for your list iteration and view update

```<code>  class ListViewUpdater implements Runnable{

            public ListViewUpdater(/* if you need you can pass list params here */){

            }

            @Override
            public void run() {
                for(int i = 0; i < searches.size(); i++) {

                    //Get the book
                    Book book = BackendFunctions.getBookFromISBN(fbSnapshot, searches.get(i));

                    //Assign data to the adapter variables
                    Bitmap cover = book.getCover();
                    String title = book.getTitle();
                    String author = book.getAuthor();

                }
//below code is important for Updating UI ,you should run UI Updates in UI thread
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        bookAdapter.notifyDataSetChanged();
                    }
                });
            }
        }
</code>```

Step 3: Initilize and call below methods

```<code>//Add data to the adapter and set the list
    SearchBookDataProvider dataProvider = new SearchBookDataProvider(cover, title, author);
   bookAdapter.add(dataProvider);
    mExecuterService = Executors.newSingleThreadExecutor()
    mExecuterService.execute(new ListViewUpdater());
</code>```

It may solve your problems.

Body:
So I have a list of strings (ISBNs), and I need to fill a listview with the objects (Book objects) associated with these strings. The problem is that the function I have to get the Book object using the string takes time, and so to get, say 30 books, the wait approaches 4 or 5 seconds.

One approach I've thought of is to get the Book objects one at a time, and to add them to the list as I get them. But this process will freeze the UI until it's done adding them all. If I try to put this process in a new thread, it won't let me add to the any UI objects (since it's from another thread). If I try to put it in an AsyncTask, I can't access the ListView since it's in the MainActivity class.

There must be a way to dynamically update a UI element, I'm sure I've seen it done. Any suggestions?

EDIT:

This is the code I'm using to actually add items to the list:

//List view and adapter setup
listView = (ListView) findViewById(R.id.listViewCheckout);
bookAdapter = new SearchBookAdapter(getApplicationContext(), R.layout.search_row_layout);
listView.setAdapter(bookAdapter);

for(int i = 0; i < searches.size(); i++) {

    //Get the book
    Book book = BackendFunctions.getBookFromISBN(fbSnapshot, searches.get(i));

    //Assign data to the adapter variables
    Bitmap cover = book.getCover();
    String title = book.getTitle();
    String author = book.getAuthor();

    //Add data to the adapter and set the list
    SearchBookDataProvider dataProvider = new SearchBookDataProvider(cover, title, author);
    bookAdapter.add(dataProvider);
    bookAdapter.notifyDataSetChanged();
}

Body:
Step 1: Declare a Executer service

 private ExecutorService mExecuterService = null;

Step 2:Declare a class for your list iteration and view update

  class ListViewUpdater implements Runnable{

            public ListViewUpdater(/* if you need you can pass list params here */){

            }

            @Override
            public void run() {
                for(int i = 0; i < searches.size(); i++) {

                    //Get the book
                    Book book = BackendFunctions.getBookFromISBN(fbSnapshot, searches.get(i));

                    //Assign data to the adapter variables
                    Bitmap cover = book.getCover();
                    String title = book.getTitle();
                    String author = book.getAuthor();

                }
//below code is important for Updating UI ,you should run UI Updates in UI thread
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        bookAdapter.notifyDataSetChanged();
                    }
                });
            }
        }

Step 3: Initilize and call below methods

//Add data to the adapter and set the list
    SearchBookDataProvider dataProvider = new SearchBookDataProvider(cover, title, author);
   bookAdapter.add(dataProvider);
    mExecuterService = Executors.newSingleThreadExecutor()
    mExecuterService.execute(new ListViewUpdater());

It may solve your problems.


问:
Pic with output analog signal
I want to output a sinusoidal signal ( for example ) from a Pic micro controller .

Is  there any type of Pic micro controllers can output an analog signal (not DAC) and how ?

答:
Use can use the PWM module in the controller.
 Create a sine table(array) with required output frequency. Load the sine table values to the PWM as duty cycles and repeat the loop. on the PWM output pin You will be getting a pulse width modulated sine wave, fed to a RC filter to get a smooth sine wave.</p>

Title: Pic with output analog signal


问:
Str.Contains show only True values
I am using str.contains on a large dataframe and I need a way such that str.contains returns the records where my str.contains function is True.  (the dataframe is several thousand lines long and I am looking for 8 true responses).

Thanks!

```<code>aa = filtered_to_df.body.str.contains('AA')

aa.head(10)
Out[312]:
15864    False
18040    False
22576    False
28092    False
32800    False
33236    False
38027    False
41222    False
46647    False
87645    False
Name: body, dtype: bool
</code>```

答:
important distinction: str.contains does not actually filter your dataframe or series, it just returns a boolean vector of the same dimension as the series you applied it on.

e.g: if you have a series like this:

```<code>my_series = pd.Series(['hello world', 'hello', 'world'])

print(my_series)

0    hello world
1          hello
2          world
dtype: object
</code>```

using str.contains("hello") on this will return a series of size 3 since it will give you True / False for every cell in the series -- does that cell contain the word "hello"?

```<code>my_series = pd.Series(['hello world', 'hello', 'world'])

print(my_series.str.contains("hello"))

0     True
1     True
2    False
dtype: bool
</code>```

to actually filter the dataframe or series, you need to wrap around it with a slicing operation.

```<code>my_series[my_series.str.contains("hello")]

0    hello world
1          hello
dtype: object
</code>```

Title: Str.Contains show only True values

Body:
I am using str.contains on a large dataframe and I need a way such that str.contains returns the records where my str.contains function is True.  (the dataframe is several thousand lines long and I am looking for 8 true responses).

Thanks!

aa = filtered_to_df.body.str.contains('AA')

aa.head(10)
Out[312]:
15864    False
18040    False
22576    False
28092    False
32800    False
33236    False
38027    False
41222    False
46647    False
87645    False
Name: body, dtype: bool

Body:
important distinction: str.contains does not actually filter your dataframe or series, it just returns a boolean vector of the same dimension as the series you applied it on.

e.g: if you have a series like this:

my_series = pd.Series(['hello world', 'hello', 'world'])

print(my_series)

0    hello world
1          hello
2          world
dtype: object

using str.contains("hello") on this will return a series of size 3 since it will give you True / False for every cell in the series -- does that cell contain the word "hello"?

my_series = pd.Series(['hello world', 'hello', 'world'])

print(my_series.str.contains("hello"))

0     True
1     True
2    False
dtype: bool

to actually filter the dataframe or series, you need to wrap around it with a slicing operation.

my_series[my_series.str.contains("hello")]

0    hello world
1          hello
dtype: object


问:
but no declaration can be found for element 'mvc:bean'
i know this has been asked in so many queries. I am posting as I tried all options and still getting the error.

```<code><?xml version="1.0" encoding="UTF-8"?>
</code>```

http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd">

```<code><mvc:annotation-driven></mvc:annotation-driven>
<context:component-scan base-package="com.cts"></context:component-scan>
<mvc:bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp" />
    <property name="suffix" value=".jsp" />
</mvc:bean>
<mvc:bean id="messageSource"
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
</mvc:bean>
<bean id="validator"
    class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"></bean>
<mvc:interceptors>
    <bean class="org.springframework.web.,servlet.i18n.LocaleChangeInterceptor">
        <property name="paramName" value="locale"></property>
    </bean>
</mvc:interceptors>
</code>```

I am getting that

Description Resource    Path    Location    Type
cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'mvc:bean'.    spring-servlet.xml  /CATestSlotBooking_Skeleton/WebContent/WEB-INF  line 17 XML Problem

i am using Spring 4.01 release jars

答:
InternalResourceViewResolver & messageSource are wrongly defined in your xml. There is no such tag as mvc:bean. That's why a problem. Should be as follows.

```<code><bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp" />
    <property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource"
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
</bean>
</code>```

Body:
i know this has been asked in so many queries. I am posting as I tried all options and still getting the error.

<?xml version="1.0" encoding="UTF-8"?>

http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<mvc:annotation-driven></mvc:annotation-driven>
<context:component-scan base-package="com.cts"></context:component-scan>
<mvc:bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp" />
    <property name="suffix" value=".jsp" />
</mvc:bean>
<mvc:bean id="messageSource"
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
</mvc:bean>
<bean id="validator"
    class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"></bean>
<mvc:interceptors>
    <bean class="org.springframework.web.,servlet.i18n.LocaleChangeInterceptor">
        <property name="paramName" value="locale"></property>
    </bean>
</mvc:interceptors>

I am getting that

Description Resource    Path    Location    Type
cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'mvc:bean'.    spring-servlet.xml  /CATestSlotBooking_Skeleton/WebContent/WEB-INF  line 17 XML Problem

i am using Spring 4.01 release jars

Body:
InternalResourceViewResolver & messageSource are wrongly defined in your xml. There is no such tag as mvc:bean. That's why a problem. Should be as follows.

<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp" />
    <property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource"
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
</bean>


问:
Is there a way to use value from CUST_DDA port as input port for lookup?
I'm trying to use a Lookup transformation to extract ACCT_ID from ACCT table based on the port CUST_DDA which is an output port from an expression.
I'm using an sqloverride as below. The initial lookup condition :

```<code>SUBSTR_ACCT_ID = IN_CUST_DDA
</code>```

Override:

```<code>SELECT
ACCT.ACCT_ID as ACCT_ID,
ACCT.ALT_ACCT_ID as ALT_ACCT_ID,
substr(acct.acct_id,-1*(length(IN_CUST_DDA))) as SUBSTR_ACCT_ID
FROM ACCT
WHERE ACCT.ALT_ACCT_ID LIKE '%'||TO_CHAR(IN_CUST_DDA)
AND ACCT.ACCT_ID LIKE '%'||TO_CHAR(IN_CUST_DDA)
</code>```

The above sql override is failing due to the error : ORA-00904: "IN_CUST_DDA": invalid identifier

Is there a way to use the value from CUST_DDA port as an input port for the lookup. CUST_DDA is not a field that belongs to the ACCT table. Is there a way to do this.

Thanks.

答:
In order to use CUST_DDA(from source) in your lookup override. You need to join the lookup table with source with a common field in the override.

You cant use the port in the way you mentioned. When you run the workflow informatica integration service will run the lookup override query in the database and get the data into the cache file (that is the reason you are receiving the error  "IN_CUST_DDA": invalid identifier.) . Once the cache file is ready it will apply the conditions and then get the output for you.

Let me know if you are not clear on this

Regards
Raj

Body:
I'm trying to use a Lookup transformation to extract ACCT_ID from ACCT table based on the port CUST_DDA which is an output port from an expression.
I'm using an sqloverride as below. The initial lookup condition :

SUBSTR_ACCT_ID = IN_CUST_DDA

Override:

SELECT
ACCT.ACCT_ID as ACCT_ID,
ACCT.ALT_ACCT_ID as ALT_ACCT_ID,
substr(acct.acct_id,-1*(length(IN_CUST_DDA))) as SUBSTR_ACCT_ID
FROM ACCT
WHERE ACCT.ALT_ACCT_ID LIKE '%'||TO_CHAR(IN_CUST_DDA)
AND ACCT.ACCT_ID LIKE '%'||TO_CHAR(IN_CUST_DDA)

The above sql override is failing due to the error : ORA-00904: "IN_CUST_DDA": invalid identifier

Is there a way to use the value from CUST_DDA port as an input port for the lookup. CUST_DDA is not a field that belongs to the ACCT table. Is there a way to do this.

Thanks.


问:
Git code management with environmental differences
I'm starting to question if I'm following best practice on my Git strategy between master and dev since deployment is not as straight forward as it seems it should be.

I have a master and dev branch that have some environmental differences. In most places where it is a configuration difference (i.e. connection string, app setting, etc.) I have been able to abstract these different into environment configuration files which live outside of Git. When switching from master to dev, the developers on the team copy and paste in the correct environment configs and everything works correctly.

However, there are some places where the code itself differs between master and dev. The most concrete example of this is within the Ninject (DI) configuration file which differs between using the production Email Service and the development one so customers are never accidentally emailed.

We've considered using the #if DEBUG preprocessor but this wouldn't protect against a developer running the dev branch in "Release" mode.

This difference in code across branches becomes difficult to manage when merging dev into master because each time we find ourselves manually ensuring the master code is never overwritten. To aid in this we ended up creating a "merge" branch which is already set up with the production commits and ignores the conflicting dev commits.

The issues becomes keeping all these branches in sync and merging / issuing pull requests in the correct order to ensure the correct code is merged.

If possible, can someone suggest a better "strategy" on managing these branches so deployment is as simple as merging dev into master?

答:
For configuration files, you need to maintain several value files (value.master, value.branch1, ...) and one template file per config, in order to generate automatically the actual config file.

See "Do not overwrite config file on Azure using GIT": it uses a content filter driver.

For code, if you can, maintain different execution paths within the same code in order to avoid managing merges.


问:
jQuery: keyup for TAB-key?
So, i'm having some trouble getting my script to run IF the Tab key is pressed. After some quick googling, the charcode for Tab is 9. Also, while we're talking, is there any better ways of checking if a key is pressed without using charcodes? I'm asking because i keep getting the following Warning by firebug when using charcode:

The 'charCode' property of a keyup event should not be used. The value is meaningless.

Anyway, it still works, so that's not the problem. This is the code i use:

```<code>$('/* my inputs */').keyup(function(e) {
   console.log('keyup called');
   var code = e.keyCode || e.which;
   if (code == '9') {
     console.log('Tab pressed');
   }
});
</code>```

Using the above code the console is left blank, nothing is added (using Firebug). Of course i've tried actually doing stuff instead of logging text, but nothing  executes. So can anyone see why this isn't working? Is there a better way of checking if a key is pressed?

Thanks in advance.

答:
```<code>e = e || window.event;
if(e.keyCode == 9)
 alert("Tab pressed");
</code>```

Try this

Title: jQuery: keyup for TAB-key?

Body:
So, i'm having some trouble getting my script to run IF the Tab key is pressed. After some quick googling, the charcode for Tab is 9. Also, while we're talking, is there any better ways of checking if a key is pressed without using charcodes? I'm asking because i keep getting the following Warning by firebug when using charcode:

The 'charCode' property of a keyup event should not be used. The value is meaningless.

Anyway, it still works, so that's not the problem. This is the code i use:

$('/* my inputs */').keyup(function(e) {
   console.log('keyup called');
   var code = e.keyCode || e.which;
   if (code == '9') {
     console.log('Tab pressed');
   }
});

Using the above code the console is left blank, nothing is added (using Firebug). Of course i've tried actually doing stuff instead of logging text, but nothing  executes. So can anyone see why this isn't working? Is there a better way of checking if a key is pressed?

Thanks in advance.

Body:
e = e || window.event;
if(e.keyCode == 9)
 alert("Tab pressed");

Try this


问:
get the count for different data in single column as set
I am having table "Activation" with the columns account ID and email and product name

product name column is having data like this below

```<code> Platform
 Access
 Onboard
 OnGuard
 Platform
 Access
 Onboard
 OnGuard
</code>```

when user activated we will insert the data as a set like this ( Platform
     ,Access
     ,Onboard
     ,OnGuard)
and i need to give a warning to the user  if he is inserting more than one set (Platform,Access,Onboard,OnGuard)

I can get the count for single product name insertion like (platform or access), but i need to get the count for single set insertion here ..

Could any one please help on this query how to get count for single set insertion and i am using sql server as a DB for these insertions.

Many thanks in advance..

UPDATE

sorry for confusion i need to give a warning to user if  he inserted more than one time any of the product name defined in the set not as a single set ..

答:
You Can Use this In Trigger.</p>

```<code>DECLARE @Product_Name NVARCHAR(50)
IF EXISTS (SELECT 1
            FROM Activation WHERE productname = @Product_Name) BEGIN

    RAISERROR ('Product Name  Already Exists', 16, 1)

END
</code>```

Body:
I am having table "Activation" with the columns account ID and email and product name

product name column is having data like this below

 Platform
 Access
 Onboard
 OnGuard
 Platform
 Access
 Onboard
 OnGuard

when user activated we will insert the data as a set like this ( Platform
     ,Access
     ,Onboard
     ,OnGuard)
and i need to give a warning to the user  if he is inserting more than one set (Platform,Access,Onboard,OnGuard)

I can get the count for single product name insertion like (platform or access), but i need to get the count for single set insertion here ..

Could any one please help on this query how to get count for single set insertion and i am using sql server as a DB for these insertions.

Many thanks in advance..

UPDATE

sorry for confusion i need to give a warning to user if  he inserted more than one time any of the product name defined in the set not as a single set ..

Body:
You Can Use this In Trigger.

DECLARE @Product_Name NVARCHAR(50)
IF EXISTS (SELECT 1
            FROM Activation WHERE productname = @Product_Name) BEGIN

    RAISERROR ('Product Name  Already Exists', 16, 1)

END


问:
How to get Last sunday date in Bootstrap Datepicker?
I am using bootstrap Datepicker and I want to set the date for current/last Sunday.The code below is showing the content form   $date to $date1.

```<code>if (!isset($_POST['new-date'])){
    $date = date('Y-m-d H:i:s');// I want to set last/current sunday
    date here.
    $date1 = date("Y-m-d H:i:s", strtotime("$date +6 day"));
    $d = explode(" ",$date);
    $d1 = explode(" ",$date1);
} else {
    $d[0] = $_POST['new-date'];
    $d1[0] = date("Y-m-d", strtotime("$d[0] +6 day"));
}
$d[0] = $_POST['new-date'];
</code>```

The ['new-date'] may be any day/date from the calendar but It should select the last Sunday of that particular week.

答:
Your code seems to be written in PHP, rather than JavaScript, so I'm not sure how relevant the question title or tags are.

```<code>// Check if the day of the week is a Sunday. If yes, use today's date. If no, use last Sunday's date
$timestamp = date('N') == 7 ? strtotime('today') : strtotime('last sunday');
$date = date('Y-m-d H:i:s', $timestamp);

die($date);
</code>```

Edit

You asked in the comments how you can find last Sunday for any given date.

```<code>$timestamp = strtotime($_POST['date'] ?? 'today');
$sunday = (date('N', $timestamp) == 7) ? $timestamp : strtotime('last sunday', $timestamp);
$date = date('Y-m-d H:i:s', $sunday);

die($date);
</code>```

Body:
I am using bootstrap Datepicker and I want to set the date for current/last Sunday.The code below is showing the content form   $date to $date1.

if (!isset($_POST['new-date'])){
    $date = date('Y-m-d H:i:s');// I want to set last/current sunday
    date here.
    $date1 = date("Y-m-d H:i:s", strtotime("$date +6 day"));
    $d = explode(" ",$date);
    $d1 = explode(" ",$date1);
} else {
    $d[0] = $_POST['new-date'];
    $d1[0] = date("Y-m-d", strtotime("$d[0] +6 day"));
}
$d[0] = $_POST['new-date'];

The ['new-date'] may be any day/date from the calendar but It should select the last Sunday of that particular week.

Body:
Your code seems to be written in PHP, rather than JavaScript, so I'm not sure how relevant the question title or tags are.

// Check if the day of the week is a Sunday. If yes, use today's date. If no, use last Sunday's date
$timestamp = date('N') == 7 ? strtotime('today') : strtotime('last sunday');
$date = date('Y-m-d H:i:s', $timestamp);

die($date);

Edit

You asked in the comments how you can find last Sunday for any given date.

$timestamp = strtotime($_POST['date'] ?? 'today');
$sunday = (date('N', $timestamp) == 7) ? $timestamp : strtotime('last sunday', $timestamp);
$date = date('Y-m-d H:i:s', $sunday);

die($date);