问:
Qt: how to pass input values from on_pushButton_clicked() function to paintGL()
I am working on a mortgage calculator with QT.
When the user clicks the push button, the "on_pushButton_clicked()" function will get the inputs.

The Question is I am confused about how to pass the inputs from "on_pushButton_clicked()" to "paintGL()" function for drawing purpose.

My last resort is using global variables to solve this issue, but I really want to avoid something like that...so it will be more than welcome if someone can enlighten with better approaches.

My code are as followed:

mainwindow.h

```<code>#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "ui_mainwindow.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:

    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    template <class T>
    T inputcheck(QLineEdit *input, T output);
    //friend class GLwidget;
    double loan;
    int maturity;
    double rate1;
    double rate2;
    double rate3;
    int period2;
    int period3;

private slots:
    void on_pushButton_Calculate_clicked();

    void on_pushButton_Quit_clicked();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H
</code>```

mainwindow.cpp

```<code>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QCoreApplication>
#include <QDesktopWidget>
#include "glwidget.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

template <class T>
T MainWindow::inputcheck(QLineEdit *input, T output)
{
    bool ok;
    output = input->text().toDouble(&ok);
    if(TRUE && output > 0)
    {
        return output;
    }
    else
    {
        input->setText("ERR");
        return 0;
    }
}

void MainWindow::on_pushButton_Calculate_clicked()
{

    // getting inputs()
    loan = inputcheck(ui->lineEdit_loan, loan);
    maturity = inputcheck(ui->lineEdit_maturity, maturity);
    rate1 = inputcheck(ui->lineEdit_rate1, rate1);
    rate2 = inputcheck(ui->lineEdit_rate2, rate2);
    rate3 = inputcheck(ui->lineEdit_rate3, rate3);
    period2 = inputcheck(ui->lineEdit_period2, period2);
    period3 = inputcheck(ui->lineEdit_period3, period3);
    printf("loan:%f, maturity:%d,rate1:%f,rate2:%f,rate3:%f, period2:%d, period3:%d\n", loan, maturity, rate1, rate2, rate3, period2, period3);

}

void MainWindow::on_pushButton_Quit_clicked()
{
    QCoreApplication::quit();

}
</code>```

glwidget.h

```<code>#ifndef GLWIDGET_H
#define GLWIDGET_H

#include <QObject>
#include <QGLWidget>

class calculation;
class GLwidget : public QGLWidget
{
    Q_OBJECT
public:
    explicit GLwidget(QWidget *parent = 0);
    void initializeGL();
    void paintGL();
    void resizeGL(int width, int height);

private:

};

#endif // GLWIDGET_H
</code>```

glwidget.cpp

```<code>#include "glwidget.h"
#include <gl/GL.h>

GLwidget::GLwidget(QWidget *parent):QGLWidget(parent)
{
}

void GLwidget::initializeGL()
{
}

void GLwidget::paintGL()
{
**// I need the inputs to be here!!**
}

void GLwidget::resizeGL(int width, int height)
{
}
</code>```

Thanks for your help:)

答:
You can use qt's Signal/Slot mechanizm for it.

Create your own struct, with the needed fields from the input. You can pass it as a pointer through a signal.

Add to mainwindow.h

```<code>signals:
    void MySignal(MyStruct*);
</code>```

in the cpp:

```<code>void MainWindow::on_pushButton_Calculate_clicked(){

// getting inputs()
    loan = inputcheck(ui->lineEdit_loan, loan);
    maturity = inputcheck(ui->lineEdit_maturity, maturity);
    rate1 = inputcheck(ui->lineEdit_rate1, rate1);
    rate2 = inputcheck(ui->lineEdit_rate2, rate2);
    rate3 = inputcheck(ui->lineEdit_rate3, rate3);
    period2 = inputcheck(ui->lineEdit_period2, period2);
    period3 = inputcheck(ui->lineEdit_period3, period3);
    printf("loan:%f, maturity:%d,rate1:%f,rate2:%f,rate3:%f, period2:%d, period3:%d\n", loan, maturity, rate1, rate2, rate3, period2, period3);
    MyStruct* struct = new MyStruct();
    ... //add data to mystruct
    emit MySignal(struct);
}
</code>```

have a function like this:
    public slots:
        void saveData(MyStruct* param); //body should saves the data however you like it

And in possibly main.cpp, where you create the two main widget, have something like this.

```<code>MainWindow mainW();
GLWidget glW();
connect(&mainW, SIGNAL( MySignal(MyStruct*)), &glW, SLOT(saveData(MyStruct*)));
</code>```

It is a little rough around the edges, but i hope you get the basic idea. If not, check Qt documentation on Signal/Slot mechanizm.

Body:
I am working on a mortgage calculator with QT.
When the user clicks the push button, the "on_pushButton_clicked()" function will get the inputs.

The Question is I am confused about how to pass the inputs from "on_pushButton_clicked()" to "paintGL()" function for drawing purpose.

My last resort is using global variables to solve this issue, but I really want to avoid something like that...so it will be more than welcome if someone can enlighten with better approaches.

My code are as followed:

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "ui_mainwindow.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:

    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    template <class T>
    T inputcheck(QLineEdit *input, T output);
    //friend class GLwidget;
    double loan;
    int maturity;
    double rate1;
    double rate2;
    double rate3;
    int period2;
    int period3;

private slots:
    void on_pushButton_Calculate_clicked();

    void on_pushButton_Quit_clicked();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QCoreApplication>
#include <QDesktopWidget>
#include "glwidget.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

template <class T>
T MainWindow::inputcheck(QLineEdit *input, T output)
{
    bool ok;
    output = input->text().toDouble(&ok);
    if(TRUE && output > 0)
    {
        return output;
    }
    else
    {
        input->setText("ERR");
        return 0;
    }
}

void MainWindow::on_pushButton_Calculate_clicked()
{

    // getting inputs()
    loan = inputcheck(ui->lineEdit_loan, loan);
    maturity = inputcheck(ui->lineEdit_maturity, maturity);
    rate1 = inputcheck(ui->lineEdit_rate1, rate1);
    rate2 = inputcheck(ui->lineEdit_rate2, rate2);
    rate3 = inputcheck(ui->lineEdit_rate3, rate3);
    period2 = inputcheck(ui->lineEdit_period2, period2);
    period3 = inputcheck(ui->lineEdit_period3, period3);
    printf("loan:%f, maturity:%d,rate1:%f,rate2:%f,rate3:%f, period2:%d, period3:%d\n", loan, maturity, rate1, rate2, rate3, period2, period3);

}

void MainWindow::on_pushButton_Quit_clicked()
{
    QCoreApplication::quit();

}

glwidget.h

#ifndef GLWIDGET_H
#define GLWIDGET_H

#include <QObject>
#include <QGLWidget>

class calculation;
class GLwidget : public QGLWidget
{
    Q_OBJECT
public:
    explicit GLwidget(QWidget *parent = 0);
    void initializeGL();
    void paintGL();
    void resizeGL(int width, int height);

private:

};

#endif // GLWIDGET_H

glwidget.cpp

#include "glwidget.h"
#include <gl/GL.h>

GLwidget::GLwidget(QWidget *parent):QGLWidget(parent)
{
}

void GLwidget::initializeGL()
{
}

void GLwidget::paintGL()
{
**// I need the inputs to be here!!**
}

void GLwidget::resizeGL(int width, int height)
{
}

Thanks for your help:)

Body:
You can use qt's Signal/Slot mechanizm for it.

Create your own struct, with the needed fields from the input. You can pass it as a pointer through a signal.

Add to mainwindow.h

signals:
    void MySignal(MyStruct*);

in the cpp:

void MainWindow::on_pushButton_Calculate_clicked(){

// getting inputs()
    loan = inputcheck(ui->lineEdit_loan, loan);
    maturity = inputcheck(ui->lineEdit_maturity, maturity);
    rate1 = inputcheck(ui->lineEdit_rate1, rate1);
    rate2 = inputcheck(ui->lineEdit_rate2, rate2);
    rate3 = inputcheck(ui->lineEdit_rate3, rate3);
    period2 = inputcheck(ui->lineEdit_period2, period2);
    period3 = inputcheck(ui->lineEdit_period3, period3);
    printf("loan:%f, maturity:%d,rate1:%f,rate2:%f,rate3:%f, period2:%d, period3:%d\n", loan, maturity, rate1, rate2, rate3, period2, period3);
    MyStruct* struct = new MyStruct();
    ... //add data to mystruct
    emit MySignal(struct);
}

have a function like this:
    public slots:
        void saveData(MyStruct* param); //body should saves the data however you like it

And in possibly main.cpp, where you create the two main widget, have something like this.

MainWindow mainW();
GLWidget glW();
connect(&mainW, SIGNAL( MySignal(MyStruct*)), &glW, SLOT(saveData(MyStruct*)));

It is a little rough around the edges, but i hope you get the basic idea. If not, check Qt documentation on Signal/Slot mechanizm.


来源: stackexchange

问:
Azure VMSS with Application gateway
Usecase:
I need to launch VM with VMSS inside application gateway depending on CPU utilization .
In VMSS I need to execute once script if anyone has done this before please share the doc for same.

Thanks.

I have created a custom template but during deployment giving error:
{
  "status": "Failed",
  "error": {
    "code": "ResourceDeploymentFailure",
    "message": "The resource operation completed with terminal provisioning state 'Failed'.",
    "details": [
      {
        "code": "VMExtensionProvisioningError",
        "message": "VM has reported a failure when processing extension 'updatescriptextension'. Error message: \"Enable failed: failed to execute command: command terminated with exit status=1\"."
      }

Template: https://github.com/linuxgambler/azure/blob/master/vmss.json

答:
You could create a single Azure Resource Manager template that creates an App Gateway, scale set, and autoscale rules. I'm not aware of a single example, but there are examples of App Gateway VMSS templates here: https://github.com/Azure/azure-quickstart-templates/tree/master/201-vmss-ubuntu-app-gateway and here: https://github.com/Azure/azure-quickstart-templates/tree/master/201-vmss-windows-app-gateway
An example using autoscale rules for CPU usage is here: https://github.com/Azure/azure-quickstart-templates/tree/master/201-vmss-ubuntu-autoscale and here: https://github.com/Azure/azure-quickstart-templates/tree/master/201-vmss-windows-autoscale - you could take the autoscale rules from the latter examples and add them to an app gateway template.

If you create such a template you can script its deployment with PowerShell or CLI. If you are looking to imperatively create resources and add autoscale rules using PowerShell or CLI commands, you can do this too, though again I'm not aware of a one-stop example script, but you can build a script from other examples. For example, instructions for adding autoscale rules to a scale set using PowerShell can be found here: https://msftstack.wordpress.com/2017/03/05/how-to-add-autoscale-to-an-azure-vm-scale-set/

ContentLicense: CC BY-SA 3.0

Title: Azure VMSS with Application gateway


答:
With exact dates </p>

```<code>import pandas as pd
spring = range(80, 172)
summer = range(172, 264)
fall = range(264, 355)

def season(x):
    if x in spring:
        return 'Spring'
    if x in summer:
        return 'Summer'
    if x in fall:
        return 'Fall'
    else :
        return 'Winter'

df = pd.DataFrame({'_date' :pd.date_range(start=pd.datetime(2016,1,1), end=pd.datetime(2016,12,31), freq='D'),'impact' : range(0,366)})

df['SEASON'] = df['_date'].dt.dayofyear.apply(lambda x : season(x))
df.groupby('SEASON')['impact'].mean()
</code>```

Title: how to group data of 4 years seasonly using pandas

Body:
i have a csv file containing 4 years of data, i need to group my data per season over the 4 years : here's a look of my data :

timestamp,heure,lat,lon,impact,type
2006-01-01 00:00:00,13:58:43,33.837,-9.205,10.3,1
2006-01-02 00:00:00,00:07:28,34.5293,-10.2384,17.7,1
2007-02-01 00:00:00,23:01:03,35.0617,-1.435,-17.1,2
2007-02-02 00:00:00,01:14:29,36.5685,0.9043,36.8,1
2008-01-01 00:00:00,05:03:51,34.1919,-12.5061,-48.9,1
2008-01-02 00:00:00,05:03:51,34.1919,-12.5061,-48.9,1
....
2011-12-31 00:00:00,05:03:51,34.1919,-12.5061,-48.9,1

and here's my desired output :

winter     (the mean value of impacts)
summer     (the mean value of impacts)
autumn      ....
spring      .....

so i am expecting 4 rows summarizing all month in 4 seasons .
i started as below :

data['impact'] = data['impact'].abs()
yearly = data.groupby(data.index.month)['impact'].mean()

any ideas ??

Body:
With exact dates

import pandas as pd
spring = range(80, 172)
summer = range(172, 264)
fall = range(264, 355)

def season(x):
    if x in spring:
        return 'Spring'
    if x in summer:
        return 'Summer'
    if x in fall:
        return 'Fall'
    else :
        return 'Winter'

df = pd.DataFrame({'_date' :pd.date_range(start=pd.datetime(2016,1,1), end=pd.datetime(2016,12,31), freq='D'),'impact' : range(0,366)})

df['SEASON'] = df['_date'].dt.dayofyear.apply(lambda x : season(x))
df.groupby('SEASON')['impact'].mean()


问:
How to make Property Tax Calculator in Javascript
I am completely new to JavaScript and my employers would like me to create a Property Tax Calculator.

I know the calculation and I know some of the code I'll need (from researching this for 2 days), but I can't put them together to get it to work. I also need an input field on my page, as the client needs to input their own value to make the calculation work. The calculation is:

Fair Market Value X 45% = Portioned Assessment

Portioned Assessed value X 30.915/1000 = Gross Taxes

I know I need my function to look kind of like this:

```<code>function PortionedAssessment() {
    var GrossTax = var FMValue * .45 * .030915;
</code>```

My variables:

```<code>    var PortAssess;
    var GrossTax;
    var FMValue = document.getElementsByName("FMValue").value;
</code>```

And I have part of my form (no styling done yet, I'll do that afterwards):

```<code><form name="PropertyCalc">

    Enter your Fair Market Value: <input type="text" value="FMValue"> X 45% X 0.030915

    <input type="button" onclick="calculate(PortionedAssessment)" name="result"
    value="Calculate" class="calcButton">

    Gross Taxes = ;

</form>
</code>```

I'm not sure how to put the calculation together or how to input the answer into my form. How do you direct a console.log to a div? I know I'm missing a lot, but like I said, this is completely over my head and I don't know who else to ask.

答:
Your problem is when to call the calculate function. I refactored your code a bit. Is this what you want to achieve?

// grab the necessary elements
var input = document.getElementById('fm-input');
var button = document.getElementById('calculate-button');
var result = document.getElementById('result');

function calculate (fm) {
  return fm * .45 * .030915;
}

// listen for the 'click' event
button.addEventListener('click', function () {
  var gross = calculate(input.value); // calculate the gross taxes
  result.textContent = gross; // write the gross value in the  element
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  Enter your Fair Market Value: <input type="number" id="fm-input" placeholder="FMValue"> X 45% X 0.030915
</div>

<div>
  <button id="calculate-button">Calculate</button>
</div>

<div>
  Gross Taxes: <span id="result"></span>
</div></code>```

Body:
I am completely new to JavaScript and my employers would like me to create a Property Tax Calculator.

I know the calculation and I know some of the code I'll need (from researching this for 2 days), but I can't put them together to get it to work. I also need an input field on my page, as the client needs to input their own value to make the calculation work. The calculation is:

Fair Market Value X 45% = Portioned Assessment

Portioned Assessed value X 30.915/1000 = Gross Taxes

I know I need my function to look kind of like this:

function PortionedAssessment() {
    var GrossTax = var FMValue * .45 * .030915;

My variables:

    var PortAssess;
    var GrossTax;
    var FMValue = document.getElementsByName("FMValue").value;

And I have part of my form (no styling done yet, I'll do that afterwards):

<form name="PropertyCalc">

    Enter your Fair Market Value: <input type="text" value="FMValue"> X 45% X 0.030915

    <input type="button" onclick="calculate(PortionedAssessment)" name="result"
    value="Calculate" class="calcButton">

    Gross Taxes = ;

</form>

I'm not sure how to put the calculation together or how to input the answer into my form. How do you direct a console.log to a div? I know I'm missing a lot, but like I said, this is completely over my head and I don't know who else to ask.

Body:
Your problem is when to call the calculate function. I refactored your code a bit. Is this what you want to achieve?

// grab the necessary elements
var input = document.getElementById('fm-input');
var button = document.getElementById('calculate-button');
var result = document.getElementById('result');

function calculate (fm) {
  return fm * .45 * .030915;
}

// listen for the 'click' event
button.addEventListener('click', function () {
  var gross = calculate(input.value); // calculate the gross taxes
  result.textContent = gross; // write the gross value in the <span> element
});

<div>
  Enter your Fair Market Value: <input type="number" id="fm-input" placeholder="FMValue"> X 45% X 0.030915
</div>

<div>
  <button id="calculate-button">Calculate</button>
</div>

<div>
  Gross Taxes: <span id="result"></span>
</div>


问:
Entity framework transferred data in bytes
I'm using EF6

this is my class

```<code>public partial class tbl_Persons
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public byte Age { get; set; }
    }
</code>```

How much (bytes) will be transferred from the server to the client when used this code ?

```<code>using (var db = new testEntities())
{
    var q = db.tbl_Persons.FirstOrDefault(a => a.ID == 1234).Age;
}
</code>```

Just transferred {(Age)(1 byte)} or transferred all properties {(ID + Name + Age)(10 bytes)} then select Age on client ?

How can I transfer only (Age)(1 byte) ? (I need to transfer minimum data from server)

答:
The expression

```<code>var q = db.tbl_Persons.FirstOrDefault(a => a.ID == 1234).Age;
</code>```

is equivalent of

```<code>var person = db.tbl_Persons.FirstOrDefault(a => a.ID == 1234);
var age = person.Age;
</code>```

So you first retrieve and materialize a whole object (with all properties) from the database, and then take a single property (byte in your case) from the result.

In order to fetch just the property in question, you should use a not so concise, but more efficient Where + Select + FirstOrDefault (no predicate version):

```<code>var age = db.tbl_Persons.Where(p => p.ID == 1234).Select(p => p.Age).FirstOrDefault();
</code>```

or with query syntax

```<code>var age = (from p in db.tbl_Persons where p.ID == 1234 select p.Age).FirstOrDefault();
</code>```

Body:
I'm using EF6

this is my class

public partial class tbl_Persons
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public byte Age { get; set; }
    }

How much (bytes) will be transferred from the server to the client when used this code ?

using (var db = new testEntities())
{
    var q = db.tbl_Persons.FirstOrDefault(a => a.ID == 1234).Age;
}

Just transferred {(Age)(1 byte)} or transferred all properties {(ID + Name + Age)(10 bytes)} then select Age on client ?

How can I transfer only (Age)(1 byte) ? (I need to transfer minimum data from server)

Body:
The expression

var q = db.tbl_Persons.FirstOrDefault(a => a.ID == 1234).Age;

is equivalent of

var person = db.tbl_Persons.FirstOrDefault(a => a.ID == 1234);
var age = person.Age;

So you first retrieve and materialize a whole object (with all properties) from the database, and then take a single property (byte in your case) from the result.

In order to fetch just the property in question, you should use a not so concise, but more efficient Where + Select + FirstOrDefault (no predicate version):

var age = db.tbl_Persons.Where(p => p.ID == 1234).Select(p => p.Age).FirstOrDefault();

or with query syntax

var age = (from p in db.tbl_Persons where p.ID == 1234 select p.Age).FirstOrDefault();


问:
Can CSS3 Filter be applied to options inside <select> ?
I would like to blur the options inside a select dropdown when opened. I could blur the selected option but not the ones inside it.

```<code>select option {
    -webkit-filter: blur(5px);
    filter: blur(5px);
}
</code>```

Here's a codepen to test:

https://codepen.io/santalurr/pen/LLVWBB

答:
For now, you can't apply any styles to the HTML <option> with anything. You can apply some styles to the <select> itself, and you can entirely remove the default styles for the <select> using this CSS:

```<code>select {
  -webkit-appearance none;
  -moz-appearance: none;
  appearance: none;
}
</code>```

You may want to use a JQuery plugin: https://www.sitepoint.com/13-jquery-selectboxdrop-down-plugins/

if you want to style the <option>.

Body:
I would like to blur the options inside a select dropdown when opened. I could blur the selected option but not the ones inside it.

select option {
    -webkit-filter: blur(5px);
    filter: blur(5px);
}

Here's a codepen to test:

https://codepen.io/santalurr/pen/LLVWBB

Body:
For now, you can't apply any styles to the HTML <option> with anything. You can apply some styles to the <select> itself, and you can entirely remove the default styles for the <select> using this CSS:

select {
  -webkit-appearance none;
  -moz-appearance: none;
  appearance: none;
}

You may want to use a JQuery plugin: https://www.sitepoint.com/13-jquery-selectboxdrop-down-plugins/

if you want to style the <option>.


问:
How can I use a EaselJS.Bitmap instance to populate a HTMLImageElement?
I'm creating a help page for a game I've developed in CreateJS. The help page is done in plain html. I would like to populate some Image elements in the help page with data from EaselJS.bitmap instances originating in the game. What's the best approach for this?</p>

答:
The Bitmap instances use HTMLImageElements to draw.

If you already have Bitmap instances generated, you can access bmpInstance.image. This is probably the best approach if you create your Bitmaps with a string path.

```<code>var bmp = new createjs.Bitmap("path/to/image.jpg");
document.body.appendChild(bmp.image);
</code>```

If you are preloading using PreloadJS, you can get the result the same way as you use to populate a Bitmap:

```<code>var img = queue.getResult("imageId"); // <-- That is an image element
</code>```

Hope that helps!

Body:
The Bitmap instances use HTMLImageElements to draw.

If you already have Bitmap instances generated, you can access bmpInstance.image. This is probably the best approach if you create your Bitmaps with a string path.

var bmp = new createjs.Bitmap("path/to/image.jpg");
document.body.appendChild(bmp.image);

If you are preloading using PreloadJS, you can get the result the same way as you use to populate a Bitmap:

var img = queue.getResult("imageId"); // <-- That is an image element

Hope that helps!


问:
Why isn't my background color showing up on
?
I am confused why the background color is not showing up on this code. There is padding on the "1" class but there is no color even though the color is specified. Look in the container class for the problem.

Please help.

body {
  margin: 0px;
  background-color: #fff;
}

/*
font-family: 'Lato', sans-serif;
font-family: 'Fjalla One', sans-serif;
font-family: 'Gloria Hallelujah', cursive;
*/

.welcome {
  font-family: 'Gloria Hallelujah', sans-serif;
  font-size: 45;
  text-align: center;
  color: #000;
}

.sub1 {
  font-family: 'Lato', sans-serif;
  font-size: 30;
  color: #000;
  text-indent: 20;
}

.sub2 {
  font-family: 'Lato', sans-serif;
  font-size: 25;
  color: #000;
  text-indent: 20;
}

.container {
  position: relative;
  width: 100%;
  height: 600px;
}

/*.container img {
    position: absolute;
    width: 1800px;
    background-size: cover;*/

}
@-webkit-keyframes xfade {
  0% {
    opacity: 1;
  }

  33% {
    opacity: 1;
  }

  44% {
    opacity: 0;
  }

  89% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}
@keyframes xfade {
  0% {
    opacity: 1;
  }

  33% {
    opacity: 1;
  }

  44% {
    opacity: 0;
  }

  89% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}
.container p:nth-child(3) {
  -webkit-animation: xfade 45s 0s infinite;
  animation: xfade 45s 0s infinite;
}
.container p:nth-child(2) {
  -webkit-animation: xfade 45s 15s infinite;
  animation: xfade 45s 15s infinite;
}
.container p:nth-child(1) {
  -webkit-animation: xfade 25s 30s infinite;
  animation: xfade 25s 30s infinite;
}
.container {
  position: relative;
}
.container img {
  position: absolute;
}
.1 {
  width: 100%;
  height: 100%;
  padding: 100px;
  /*background-image: url(Pictures/cupcakes.jpg)*/

  background-color: #00FFFF;
  overflow: auto;
  background-size: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
  <title>JAM Bakery</title>
  <link rel="stylesheet" type="text/css" href="home.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <link href="https://fonts.googleapis.com/css?family=Fjalla+One|Gloria+Hallelujah|Lato" rel="stylesheet">
</head>

<body>
  <br>
  <div class="content">
    <h1 class="welcome">Welcome to JAM Bakery!</h1>
    <div class="slogan">
      <h2 class="sub1">Creamy, Sweet, Toasted</h2>
      <h2 class="sub2">Your Choice.</h2>

      <div class="container">
        <p class="1">1</p>
        <p class="2"></p>
        <p class="3"></p>
      </div>

    </div>
  </div>
</body>

</html></code>```

Please check for any other problems you might see. Thank you.

答:
CSS class names should not be numeric, and it should start with an alphabet or -(hyphen) or _(underscore)

body {
  margin: 0px;
  background-color: #fff;
}

/*
font-family: 'Lato', sans-serif;
font-family: 'Fjalla One', sans-serif;
font-family: 'Gloria Hallelujah', cursive;
*/

.welcome {
  font-family: 'Gloria Hallelujah', sans-serif;
  font-size: 45;
  text-align: center;
  color: #000;
}

.sub1 {
  font-family: 'Lato', sans-serif;
  font-size: 30;
  color: #000;
  text-indent: 20;
}

.sub2 {
  font-family: 'Lato', sans-serif;
  font-size: 25;
  color: #000;
  text-indent: 20;
}

.container {
  position: relative;
  width: 100%;
  height: 600px;
}

/*.container img {
    position: absolute;
    width: 1800px;
    background-size: cover;*/

}
@-webkit-keyframes xfade {
  0% {
    opacity: 1;
  }

  33% {
    opacity: 1;
  }

  44% {
    opacity: 0;
  }

  89% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}
@keyframes xfade {
  0% {
    opacity: 1;
  }

  33% {
    opacity: 1;
  }

  44% {
    opacity: 0;
  }

  89% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}
.container p:nth-child(3) {
  -webkit-animation: xfade 45s 0s infinite;
  animation: xfade 45s 0s infinite;
}
.container p:nth-child(2) {
  -webkit-animation: xfade 45s 15s infinite;
  animation: xfade 45s 15s infinite;
}
.container p:nth-child(1) {
  -webkit-animation: xfade 25s 30s infinite;
  animation: xfade 25s 30s infinite;
}
.container {
  position: relative;
}
.container img {
  position: absolute;
}
.t1 {
  width: 100%;
  height: 100%;
  padding: 100px;
  /*background-image: url(Pictures/cupcakes.jpg)*/

  background-color: #00FFFF;
  overflow: auto;
  background-size: cover;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
  <title>JAM Bakery</title>
  <link rel="stylesheet" type="text/css" href="home.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <link href="https://fonts.googleapis.com/css?family=Fjalla+One|Gloria+Hallelujah|Lato" rel="stylesheet">
</head>

<body>
  <br>
  <div class="content">
    <h1 class="welcome">Welcome to JAM Bakery!</h1>
    <div class="slogan">
      <h2 class="sub1">Creamy, Sweet, Toasted</h2>
      <h2 class="sub2">Your Choice.</h2>

      <div class="container">
        <p class="t1">1</p>
        <p class="t2"></p>
        <p class="t3"></p>
      </div>

    </div>
  </div>
</body>

</html></code>```

Title: Why isn't my background color showing up on <p>?

Body:
I am confused why the background color is not showing up on this code. There is padding on the "1" class but there is no color even though the color is specified. Look in the container class for the problem.

Please help.

body {
  margin: 0px;
  background-color: #fff;
}

/*
font-family: 'Lato', sans-serif;
font-family: 'Fjalla One', sans-serif;
font-family: 'Gloria Hallelujah', cursive;
*/

.welcome {
  font-family: 'Gloria Hallelujah', sans-serif;
  font-size: 45;
  text-align: center;
  color: #000;
}

.sub1 {
  font-family: 'Lato', sans-serif;
  font-size: 30;
  color: #000;
  text-indent: 20;
}

.sub2 {
  font-family: 'Lato', sans-serif;
  font-size: 25;
  color: #000;
  text-indent: 20;
}

.container {
  position: relative;
  width: 100%;
  height: 600px;
}

/*.container img {
    position: absolute;
    width: 1800px;
    background-size: cover;*/

}
@-webkit-keyframes xfade {
  0% {
    opacity: 1;
  }

  33% {
    opacity: 1;
  }

  44% {
    opacity: 0;
  }

  89% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}
@keyframes xfade {
  0% {
    opacity: 1;
  }

  33% {
    opacity: 1;
  }

  44% {
    opacity: 0;
  }

  89% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}
.container p:nth-child(3) {
  -webkit-animation: xfade 45s 0s infinite;
  animation: xfade 45s 0s infinite;
}
.container p:nth-child(2) {
  -webkit-animation: xfade 45s 15s infinite;
  animation: xfade 45s 15s infinite;
}
.container p:nth-child(1) {
  -webkit-animation: xfade 25s 30s infinite;
  animation: xfade 25s 30s infinite;
}
.container {
  position: relative;
}
.container img {
  position: absolute;
}
.1 {
  width: 100%;
  height: 100%;
  padding: 100px;
  /*background-image: url(Pictures/cupcakes.jpg)*/

  background-color: #00FFFF;
  overflow: auto;
  background-size: cover;
}

  <title>JAM Bakery</title>
  <link rel="stylesheet" type="text/css" href="home.css">

  <link href="https://fonts.googleapis.com/css?family=Fjalla+One|Gloria+Hallelujah|Lato" rel="stylesheet">

Welcome to JAM Bakery!

Creamy, Sweet, Toasted

Your Choice.

1

Please check for any other problems you might see. Thank you.

Body:
CSS class names should not be numeric, and it should start with an alphabet or -(hyphen) or _(underscore)

body {
  margin: 0px;
  background-color: #fff;
}

/*
font-family: 'Lato', sans-serif;
font-family: 'Fjalla One', sans-serif;
font-family: 'Gloria Hallelujah', cursive;
*/

.welcome {
  font-family: 'Gloria Hallelujah', sans-serif;
  font-size: 45;
  text-align: center;
  color: #000;
}

.sub1 {
  font-family: 'Lato', sans-serif;
  font-size: 30;
  color: #000;
  text-indent: 20;
}

.sub2 {
  font-family: 'Lato', sans-serif;
  font-size: 25;
  color: #000;
  text-indent: 20;
}

.container {
  position: relative;
  width: 100%;
  height: 600px;
}

/*.container img {
    position: absolute;
    width: 1800px;
    background-size: cover;*/

}
@-webkit-keyframes xfade {
  0% {
    opacity: 1;
  }

  33% {
    opacity: 1;
  }

  44% {
    opacity: 0;
  }

  89% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}
@keyframes xfade {
  0% {
    opacity: 1;
  }

  33% {
    opacity: 1;
  }

  44% {
    opacity: 0;
  }

  89% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}
.container p:nth-child(3) {
  -webkit-animation: xfade 45s 0s infinite;
  animation: xfade 45s 0s infinite;
}
.container p:nth-child(2) {
  -webkit-animation: xfade 45s 15s infinite;
  animation: xfade 45s 15s infinite;
}
.container p:nth-child(1) {
  -webkit-animation: xfade 25s 30s infinite;
  animation: xfade 25s 30s infinite;
}
.container {
  position: relative;
}
.container img {
  position: absolute;
}
.t1 {
  width: 100%;
  height: 100%;
  padding: 100px;
  /*background-image: url(Pictures/cupcakes.jpg)*/

  background-color: #00FFFF;
  overflow: auto;
  background-size: cover;
}

<html>

<head>
  <title>JAM Bakery</title>
  <link rel="stylesheet" type="text/css" href="home.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <link href="https://fonts.googleapis.com/css?family=Fjalla+One|Gloria+Hallelujah|Lato" rel="stylesheet">
</head>

<body>
  <br>
  <div class="content">
    <h1 class="welcome">Welcome to JAM Bakery!</h1>
    <div class="slogan">
      <h2 class="sub1">Creamy, Sweet, Toasted</h2>
      <h2 class="sub2">Your Choice.</h2>

      <div class="container">
        <p class="t1">1</p>
        <p class="t2"></p>
        <p class="t3"></p>
      </div>

    </div>
  </div>
</body>

</html>


问:
JQuery validation plugin re-enable submit after validation
I am having an issue with the JQuery Validation Plugin. I'm using it on a rails form, and I have validation working on clicking the submit button. The issue is that once the validation errors are fixed the submit button does not come back from being disabled, and even with the submitHandler as

$.validator.setDefaults({
    submitHandler: function(form) { form.submit(); }
});

the form won't submit. I know there's got to be something I'm missing. The form will submit if there are no validation issues. I've checked out some of the other messages here about this issue but the onclick and onkeyup stuff doesn't work.

答:
Try this </p>

```<code>var validator = $("#signupForm").validate({
    rules: {

    },
    messages:{

    },
    unhighlight: function( element, errorClass, validClass ) {
        $(element).removeClass(errorClass).addClass(validClass);
        if(validator.numberOfInvalids() == 0){
            $("#SubmitButton").attr("disabled","");
        }
    }

});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Try this

var validator = $("#signupForm").validate({
    rules: {

    },
    messages:{

    },
    unhighlight: function( element, errorClass, validClass ) {
        $(element).removeClass(errorClass).addClass(validClass);
        if(validator.numberOfInvalids() == 0){
            $("#SubmitButton").attr("disabled","");
        }
    }

});


问:
Do I need Indexing required in case of less data returned by DynamoDb
Say, the dynamo db has data of format:-

```<code>{
"id":"<id>",
"field-1":"<field-1-value>",
"field-2":"<field-2-value>",
"field-3":"<field-3-value>",
"field-4":"<field-4-value>",
"metadata":{
        "subfield-1":"<subfield-1-value>",
        "subfield-2":"<subfield-2-value>"
        }
}
</code>```

So, I have a partition key on id column and sort key on field-1 say. Now, say, I have a requirement that for the same id, if we want a search capability on subfield-1 value, so can that be easily done in Dynamo Db without creating any index. The max. number of rows that would be there for each id would be 70. So, looks like a small set of data.

Please let me know your views.

答:
Yes, this can be achieved without index. You can use FilterExpression to filter the data i.e. metadata.subfield-1.

Example:

```<code>var params = {
    TableName : 'yourTableName',
    KeyConditionExpression : 'id = :idval',
    FilterExpression : '#metadata = :subField1Val',
     ExpressionAttributeNames : {
        '#metadata' : 'metadata.subfield-1'
    },
    ExpressionAttributeValues : {
        ':idval' : '7',
        'subField1Val' : 'somevalue'

    }
};
</code>```

Body:
Say, the dynamo db has data of format:-

{
"id":"<id>",
"field-1":"<field-1-value>",
"field-2":"<field-2-value>",
"field-3":"<field-3-value>",
"field-4":"<field-4-value>",
"metadata":{
        "subfield-1":"<subfield-1-value>",
        "subfield-2":"<subfield-2-value>"
        }
}

So, I have a partition key on id column and sort key on field-1 say. Now, say, I have a requirement that for the same id, if we want a search capability on subfield-1 value, so can that be easily done in Dynamo Db without creating any index. The max. number of rows that would be there for each id would be 70. So, looks like a small set of data.

Please let me know your views.

Body:
Yes, this can be achieved without index. You can use FilterExpression to filter the data i.e. metadata.subfield-1.

Example:

var params = {
    TableName : 'yourTableName',
    KeyConditionExpression : 'id = :idval',
    FilterExpression : '#metadata = :subField1Val',
     ExpressionAttributeNames : {
        '#metadata' : 'metadata.subfield-1'
    },
    ExpressionAttributeValues : {
        ':idval' : '7',
        'subField1Val' : 'somevalue'

    }
};


问:
How to pass a variable from laravel 5.4 to vuejs
Is it possible to pass a variable from controller to vuejs? I have read some answers but nothing seems to work for me. I want to pass the variable $url to vue. I have tried some thing like this

var url = {!! $url !!}; this gives me syntax error: unexpected token in app.js

example url http://eventregistry.org/json/suggestConcepts?prefix=sam&lang=eng&callback=JSON_CALLBACK

Controller

```<code>class SearchCompanyName extends Controller
{
    public function getcompanyname($name)
    {
      return "http://eventregistry.org/json/suggestConcepts?prefix=" . $name . "&lang=eng&callback=JSON_CALLBACK";
    }

    public function index()
    {
       $url = $this->getcompanyname(Input::get("company_name_by_user"));
       return view('searchcompany', ['url' => $url]);

    }
}
</code>```

vue app.js

```<code>Vue.component('search', require('./components/Searchnames.vue'));
const search = new Vue({
    el: '#search',
    data: {
    },
    method: {
        getMessages: function(){
            console.log('I am here')
        }()
    }
});
</code>```

blade template

```<code>@section('content')
<div class="container">
{!! $url !!}
 <search></search>
</div>

@endsection
</code>```

答:
If you want to declare your javascript variable in a script tag within a blade file, you need to put the variable in quotes like so</p>

```<code><script>
  var url = '{{ $url }}';
</script>
</code>```

Body:
Is it possible to pass a variable from controller to vuejs? I have read some answers but nothing seems to work for me. I want to pass the variable $url to vue. I have tried some thing like this

var url = {!! $url !!}; this gives me syntax error: unexpected token in app.js

example url http://eventregistry.org/json/suggestConcepts?prefix=sam&lang=eng&callback=JSON_CALLBACK

Controller

class SearchCompanyName extends Controller
{
    public function getcompanyname($name)
    {
      return "http://eventregistry.org/json/suggestConcepts?prefix=" . $name . "&lang=eng&callback=JSON_CALLBACK";
    }

    public function index()
    {
       $url = $this->getcompanyname(Input::get("company_name_by_user"));
       return view('searchcompany', ['url' => $url]);

    }
}

vue app.js

Vue.component('search', require('./components/Searchnames.vue'));
const search = new Vue({
    el: '#search',
    data: {
    },
    method: {
        getMessages: function(){
            console.log('I am here')
        }()
    }
});

blade template

@section('content')

{!! $url !!}
 <search></search>

@endsection

Body:
If you want to declare your javascript variable in a script tag within a blade file, you need to put the variable in quotes like so

<script>
  var url = '{{ $url }}';
</script>


问:
Excel Extraction, taking out three numeric characters in a string
I am looking to find an excel formula or VB formula which would be able to extract specific data in excel.

For example we have the following in a cell:
Time spent in script:333

The above will always remain the same, however the time will be different and can range from 1 to 999 so 3 numeric characters max. However.. In some cells there maybe changes after the 3 characters and may come out like so:
Time spent in script:333Q1

So I need a formula which extracts 3 numeric characters after the semi colon but to ignore anything after the 3 characters.

答:
A1 being the cell you're referencing...

=MID(A1,22,3)

EDIT: Now works for digits 1-999

=IF(LEN(A1) = 26, MID(A1,22,3), IF(LEN(A1) = 25, MID(A1,22,2), IF(LEN(A1) = 24, MID(A1,22,1), "NA")))


问:
SQL - string combine based on id
Need suggestion to split string in table 1, match its Ids with table 2 and concatenate the values.

Table - 1

```<code>Id  Tbl1Col
1   2
2   2,4
3
4   6
5   3
</code>```

Table - 2

```<code>Id  Tbl2Col
1   E
2   F
3   M
4   U
5   P
6   C
7   N
8   G
</code>```

Query -

```<code>SELECT T2.Tbl2Col
FROM Table1 AS T1
LEFT JOIN Table2 AS T2 WHERE T1.Tbl1Col= T2.Id
WHERE T1.Id = @Id
</code>```

Now If @Id = 1, Output is F -- works fine

Now If @Id = 2, Output should be FU -- should not be F,U

答:
Follow the next approach:-

1) Turning a Comma Separated string into individual rows via using CROSS APPLY with XML

2) Join the two tables with left join.

3) Concatenate many rows with same id via using STUFF & FOR XML

4) Use Replace function for removing comma.

Demo:-

```<code>declare @MyTable table (id int , Tbl1Col varchar(10))
insert into @MyTable values (1,'2'),(2,'2,4'),(3,''),(4,'6'),(5,'3')

declare @MyTable2 table (id int , Tbl2Col varchar(10))
insert into @MyTable2 values (1,'E'),(2,'F'),(3,'M'),(4,'U'),(5,'P'),(6,'C'),(7,'N'),(8,'G')

select a.id , Tbl2Col
into #TestTable
from
(

SELECT A.id,
     Split.a.value('.', 'VARCHAR(100)') AS Tbl1Col
 FROM
 (
     SELECT id,
         CAST ('<M>' + REPLACE(Tbl1Col, ',', '</M><M>') + '</M>' AS XML) AS Data
     FROM  @MyTable
 ) AS A CROSS APPLY Data.nodes ('/M') AS Split(a) ) a

 left join @MyTable2 b
 on a.Tbl1Col = b.id

order by a.id

SELECT id, Tbl2Col =
    Replace(STUFF((SELECT DISTINCT ', ' + Tbl2Col
           FROM #TestTable b
           WHERE b.id = a.id
          FOR XML PATH('')), 1, 2, ''),',','')
FROM #TestTable a
GROUP BY id
</code>```

Output:-

```<code>1   F
2   F U
3   NULL
4   C
5   M
</code>```

References:-

Turning a Comma Separated string into individual rows

How to concatenate many rows with same id in sql?

Finally:-

Don't use this approach, and normalize your database instead , just use it as fun/training/trying .... etc code.

Title: SQL - string combine based on id

Body:
Need suggestion to split string in table 1, match its Ids with table 2 and concatenate the values.

Table - 1

Id  Tbl1Col
1   2
2   2,4
3
4   6
5   3

Table - 2

Id  Tbl2Col
1   E
2   F
3   M
4   U
5   P
6   C
7   N
8   G

Query -

SELECT T2.Tbl2Col
FROM Table1 AS T1
LEFT JOIN Table2 AS T2 WHERE T1.Tbl1Col= T2.Id
WHERE T1.Id = @Id

Now If @Id = 1, Output is F -- works fine

Now If @Id = 2, Output should be FU -- should not be F,U

Body:
Follow the next approach:-

1) Turning a Comma Separated string into individual rows via using CROSS APPLY with XML

2) Join the two tables with left join.

3) Concatenate many rows with same id via using STUFF & FOR XML

4) Use Replace function for removing comma.

Demo:-

declare @MyTable table (id int , Tbl1Col varchar(10))
insert into @MyTable values (1,'2'),(2,'2,4'),(3,''),(4,'6'),(5,'3')

declare @MyTable2 table (id int , Tbl2Col varchar(10))
insert into @MyTable2 values (1,'E'),(2,'F'),(3,'M'),(4,'U'),(5,'P'),(6,'C'),(7,'N'),(8,'G')

select a.id , Tbl2Col
into #TestTable
from
(

SELECT A.id,
     Split.a.value('.', 'VARCHAR(100)') AS Tbl1Col
 FROM
 (
     SELECT id,
         CAST ('<M>' + REPLACE(Tbl1Col, ',', '</M><M>') + '</M>' AS XML) AS Data
     FROM  @MyTable
 ) AS A CROSS APPLY Data.nodes ('/M') AS Split(a) ) a

 left join @MyTable2 b
 on a.Tbl1Col = b.id

order by a.id

SELECT id, Tbl2Col =
    Replace(STUFF((SELECT DISTINCT ', ' + Tbl2Col
           FROM #TestTable b
           WHERE b.id = a.id
          FOR XML PATH('')), 1, 2, ''),',','')
FROM #TestTable a
GROUP BY id

Output:-

1   F
2   F U
3   NULL
4   C
5   M

References:-

Turning a Comma Separated string into individual rows

How to concatenate many rows with same id in sql?

Finally:-

Don't use this approach, and normalize your database instead , just use it as fun/training/trying .... etc code.


问:
How to highlight ngram tokens in a word using elastic search
I would like to highlight just the ngrams which match, not the whole word.
Example:

```<code>term: "Wo"
highlight should be: "<em>Wo</em>nderfull world!"
currently it is: "<em>Wonderfull</em> world!"
</code>```

Mapping is:

```<code>{
  "global_search_1495732922733" : {
    "mappings" : {
      "meeting" : {
        "properties" : {
        ...
          "name" : {
            "type" : "text",
            "analyzer" : "meeteor_index_analyzer",
            "search_analyzer" : "meeteor_search_term_analyzer"
          },
          ...
        }
      }
    }
  }
}
</code>```

Analyzers are:

```<code>"analysis" : {
  "filter" : {
    "meeteor_stemmer" : {
      "name" : "english",
      "type" : "stemmer"
    },
    "meeteor_ngram" : {
      "type" : "nGram",
      "min_gram" : "2",
      "max_gram" : "15"
    }
  },
  "analyzer" : {
    "meeteor_search_term_analyzer" : {
      "filter" : [
        "lowercase",
        "asciifolding"
      ],
      "tokenizer" : "standard"
    },
    "meeteor_index_analyzer" : {
      "filter" : [
        "lowercase",
        "asciifolding",
        "meeteor_ngram"
      ],
      "tokenizer" : "standard"
    },
    "meeteor_project_id_analyzer" : {
      "tokenizer" : "standard"
    }
  }
},
</code>```

Concrete example:

```<code>curl -XGET 'localhost:9200/global_search/meeting/_search?pretty' -H 'Content-Type: application/json' -d'
{
    "query": {
        "match": {
            "name": "Me"
        }
    },
    "highlight":{
      "fields": {
        "name": {}
      }
    }
}
'
</code>```

The result is:

```<code> "...highlight" : {
          "name" : [
            "Sad <em>Meeting</em>"
          ]
        }
</code>```

答:
The correct way to achieve what you want is using ngram as tokenizer and not filter. You can do something like this:

```<code>"analysis" : {
  "filter" : {
    "meeteor_stemmer" : {
      "name" : "english",
      "type" : "stemmer"
    }
  },
  "tokenizer" : {
    "meeteor_ngram_tokenizer" : {
      "type" : "nGram",
      "min_gram" : "2",
      "max_gram" : "15"
    }
  },
  "analyzer" : {
    "meeteor_search_term_analyzer" : {
      "filter" : [
        "lowercase",
        "asciifolding"
      ],
      "tokenizer" : "standard"
    },
    "meeteor_index_analyzer" : {
      "filter" : [
        "lowercase",
        "asciifolding"
      ],
      "tokenizer" : "meeteor_ngram_tokenizer"
    },
    "meeteor_project_id_analyzer" : {
      "tokenizer" : "standard"
    }
  }
},
</code>```

It will generate the highlighting by ngram for you like this:

```<code> "...highlight" : {
          "name" : [
            "Sad <em>Me</em>eting"
          ]
        }
</code>```

Body:
I would like to highlight just the ngrams which match, not the whole word.
Example:

term: "Wo"
highlight should be: "Wonderfull world!"
currently it is: "Wonderfull world!"

Mapping is:

{
  "global_search_1495732922733" : {
    "mappings" : {
      "meeting" : {
        "properties" : {
        ...
          "name" : {
            "type" : "text",
            "analyzer" : "meeteor_index_analyzer",
            "search_analyzer" : "meeteor_search_term_analyzer"
          },
          ...
        }
      }
    }
  }
}

Analyzers are:

"analysis" : {
  "filter" : {
    "meeteor_stemmer" : {
      "name" : "english",
      "type" : "stemmer"
    },
    "meeteor_ngram" : {
      "type" : "nGram",
      "min_gram" : "2",
      "max_gram" : "15"
    }
  },
  "analyzer" : {
    "meeteor_search_term_analyzer" : {
      "filter" : [
        "lowercase",
        "asciifolding"
      ],
      "tokenizer" : "standard"
    },
    "meeteor_index_analyzer" : {
      "filter" : [
        "lowercase",
        "asciifolding",
        "meeteor_ngram"
      ],
      "tokenizer" : "standard"
    },
    "meeteor_project_id_analyzer" : {
      "tokenizer" : "standard"
    }
  }
},

Concrete example:

curl -XGET 'localhost:9200/global_search/meeting/_search?pretty' -H 'Content-Type: application/json' -d'
{
    "query": {
        "match": {
            "name": "Me"
        }
    },
    "highlight":{
      "fields": {
        "name": {}
      }
    }
}
'

The result is:

 "...highlight" : {
          "name" : [
            "Sad Meeting"
          ]
        }

Body:
The correct way to achieve what you want is using ngram as tokenizer and not filter. You can do something like this:

"analysis" : {
  "filter" : {
    "meeteor_stemmer" : {
      "name" : "english",
      "type" : "stemmer"
    }
  },
  "tokenizer" : {
    "meeteor_ngram_tokenizer" : {
      "type" : "nGram",
      "min_gram" : "2",
      "max_gram" : "15"
    }
  },
  "analyzer" : {
    "meeteor_search_term_analyzer" : {
      "filter" : [
        "lowercase",
        "asciifolding"
      ],
      "tokenizer" : "standard"
    },
    "meeteor_index_analyzer" : {
      "filter" : [
        "lowercase",
        "asciifolding"
      ],
      "tokenizer" : "meeteor_ngram_tokenizer"
    },
    "meeteor_project_id_analyzer" : {
      "tokenizer" : "standard"
    }
  }
},

It will generate the highlighting by ngram for you like this:

 "...highlight" : {
          "name" : [
            "Sad <em>Me</em>eting"
          ]
        }


问:
Power shell replace character Ž
I have a power shell script that basically replace specific characters e.g (TM) -- > '™' in all the files under a specific folder.

The script works perfectly. But it's not working when I tried to replace avŽ with avé. If I try to replace av with ac it works. So I am assuming replace is not working for grapheme Ž character. it will be great if you can provide some idea on this. Below is the sample code which replace the character:

```<code>$old = 'PavŽ'
$new = 'Pavé
$InputFiles = Get-Item "C:\..\..\*.txt"
Get-Item $InputFiles | ForEach {
        (Get-Content -Path $_.FullName).Replace($old,$new) | Set-Content -Path $_.FullName
    }
</code>```

Thanks in advance.

答:
Powershell replaces any character just fine. But there may be some other issues:

The encoding of your file may be the issue. (most likely).
If your file is encoded using a code page that doen't contain certain
characters, those characters won't get saved.
You may want to consider saving your files in a format that does, e.g. UTF-8.

You may not have write rights to some files.

In my small test, the replacement worked just fine. I used notepad to create a file containing 'PavŽ', and another containing 'Pavé'.

Your few lines of powershell replaced everything (and with $old en $new switched) back and forth just fine.

Title: Power shell replace character Ž

Body:
I have a power shell script that basically replace specific characters e.g (TM) -- > '™' in all the files under a specific folder.

The script works perfectly. But it's not working when I tried to replace avŽ with avé. If I try to replace av with ac it works. So I am assuming replace is not working for grapheme Ž character. it will be great if you can provide some idea on this. Below is the sample code which replace the character:

$old = 'PavŽ'
$new = 'Pavé
$InputFiles = Get-Item "C:\..\..\*.txt"
Get-Item $InputFiles | ForEach {
        (Get-Content -Path $_.FullName).Replace($old,$new) | Set-Content -Path $_.FullName
    }

Thanks in advance.


问:
How to turn a string of letters into integer?
Specifically, I'm taking a word that a user inputs, which is equivalent to a number (that the user wouldn't know).

my code:

```<code>animal = raw_input( > )  #and a user inputs cat
dog = 30
cat = 10
frog = 5
print 10 + int(animal) #with the hope that will output 20
</code>```

Not sure how to do it..

答:
```<code>animal = raw_input(>)
animal_dict = {'dog': 30, 'cat': 10, 'frog': 5}
number = animal_dict.get(animal, 0):
print 10+number
</code>```

Body:
Specifically, I'm taking a word that a user inputs, which is equivalent to a number (that the user wouldn't know).

my code:

animal = raw_input( > )  #and a user inputs cat
dog = 30
cat = 10
frog = 5
print 10 + int(animal) #with the hope that will output 20

Not sure how to do it..


问:
Create Setup/MSI installer in Visual Studio 2017
I have written an outlook add-in VSTO in Visual Studio Pro 2017 (VB.NET).  I have published it which creates a setup.exe which is OK but I would like to create a proper installer that copies the files locally and can be run silently etc.

How do I go about doing this?  When I go to create new project there is no installer project option.

答:
You need to install this extension to Visual Studio 2017/2019 in order to get access to the Installer Projects.

According to the page:

This extension provides the same functionality that currently exists in Visual Studio 2015 for Visual Studio Installer projects. To use this extension, you can either open the Extensions and Updates dialog, select the online node, and search for "Visual Studio Installer Projects Extension," or you can download directly from this page.

Once you have finished installing the extension and restarted Visual Studio, you will be able to open existing Visual Studio Installer projects, or create new ones.

ContentLicense: CC BY-SA 4.0


问:
Powershell force 5 digit format in a string pattern
So what I have now will (below) will search for XX-##-# and force it to XX-##-#0000.

How can I do this to return XX-##-0000#?

Is there a way to force 5 digits at the end, filling preceding 0s, to cover the other possibilities (XX-##-##, XX-##-###, XX-##-####)? As opposed to copying this 4 times, slightly adjusting for each.

```<code>$Pattern1 = '[a-zA-Z][a-zA-Z]-[0-9][0-9]-[0-9]'
Get-ChildItem 'C:\path\to\file\*.txt' -Recurse | ForEach {
     (Get-Content $_ |
     ForEach  { $_ -replace $Pattern1, ('$1'+'0000')}) |
     Set-Content $_
}
</code>```

Thanks.

EDIT: I would like to do the following

```<code>Search           Replacement
XX-##-#          XX-##-0000#
XX-##-##         XX-##-000##
XX-##-###        XX-##-00###
XX-##-####       XX-##-0####
</code>```

答:
Use a look-ahead:

```<code>$Pattern1 = '(?<=[a-zA-Z][a-zA-Z]-\d\d-)(?=\d)(?!\d\d)'
Get-ChildItem 'C:\path\to\file\*.txt' -Recurse | ForEach {
(Get-Content $_ |
ForEach  { $_ -replace $date_pattern1, ('000')}) |
Set-Content $_
</code>```

The look-ahead (?=\d) asserts, without consuming, that the next char is a digit.

The negative look-ahead '(!\d\d) asserts there are not 2 digits at the end, so you don't end up with XX-##-0000##.

Also note that \d (a "digit") is exactly the same as [0-9] (but easier to code.

I think you have to do the replacement 4 times.

Body:
So what I have now will (below) will search for XX-##-# and force it to XX-##-#0000.

How can I do this to return XX-##-0000#?

Is there a way to force 5 digits at the end, filling preceding 0s, to cover the other possibilities (XX-##-##, XX-##-###, XX-##-####)? As opposed to copying this 4 times, slightly adjusting for each.

$Pattern1 = '[a-zA-Z][a-zA-Z]-[0-9][0-9]-[0-9]'
Get-ChildItem 'C:\path\to\file\*.txt' -Recurse | ForEach {
     (Get-Content $_ |
     ForEach  { $_ -replace $Pattern1, ('$1'+'0000')}) |
     Set-Content $_
}

Thanks.

EDIT: I would like to do the following

Search           Replacement
XX-##-#          XX-##-0000#
XX-##-##         XX-##-000##
XX-##-###        XX-##-00###
XX-##-####       XX-##-0####

Body:
Use a look-ahead:

$Pattern1 = '(?<=[a-zA-Z][a-zA-Z]-\d\d-)(?=\d)(?!\d\d)'
Get-ChildItem 'C:\path\to\file\*.txt' -Recurse | ForEach {
(Get-Content $_ |
ForEach  { $_ -replace $date_pattern1, ('000')}) |
Set-Content $_

The look-ahead (?=\d) asserts, without consuming, that the next char is a digit.

The negative look-ahead '(!\d\d) asserts there are not 2 digits at the end, so you don't end up with XX-##-0000##.

Also note that \d (a "digit") is exactly the same as [0-9] (but easier to code.

I think you have to do the replacement 4 times.


问:
In Android, When I Play Audio and go to other activity, audio doesn't stop after coming back
I'm new in Android environment, my problem is while I Play audio file and go to other activity or press back button, and again open my application where I've played audio, it doesn't stop while i press stop button. it works when i press home button and try to stop. can anyone suggest me what to
 Here's the code of my activity</p>

```<code>package com.example.mudassar.myaudioapp;

import android.content.Intent;
import android.os.Environment;
import android.os.NetworkOnMainThreadException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    //MediaPlayer mp;
    Button playBtn, pauseBtn, stopBtn;
    SeekBar sb;
    Handler han = new Handler();
    MediaPlayer mp;// = MediaPlayer.create(MainActivity.this, R.raw.firefly);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        playBtn= (Button)findViewById(R.id.playBtn);
        pauseBtn= (Button)findViewById(R.id.pauseBtn);
        stopBtn=(Button) findViewById(R.id.stopBtn);

        try{
            //you can change the path, here path is external directory(e.g. sdcard) /Music/maine.mp3
            //mp.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/raw/.mp3");
            mp = MediaPlayer.create(MainActivity.this, R.raw.firefly);
            mp.prepare();
        }catch(Exception e){e.printStackTrace();}

        sb = (SeekBar)findViewById(R.id.seekBar);
        sb.setMax(mp.getDuration());

        SeekUpdation();

        playBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SeekUpdation();
                //if (mp == null)
                if(mp.isPlaying() == false)
                    mp = MediaPlayer.create(MainActivity.this, R.raw.firefly);
                mp.start();
                sb.setMax(mp.getDuration());
                sb.setProgress(mp.getCurrentPosition());
            }
        });

        pauseBtn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                if(mp.isPlaying() == false){
                    mp.start();
                    sb.setProgress(mp.getCurrentPosition());
                    Toast.makeText(MainActivity.this, "Playing", Toast.LENGTH_SHORT).show();
                }else if(mp.isPlaying() == true){
                    mp.pause();
                    sb.setProgress(mp.getCurrentPosition());
                    Toast.makeText(MainActivity.this, "Paused", Toast.LENGTH_SHORT).show();
                }

            }
        });

        stopBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //if (mp != null) {
                if(mp.isPlaying() == true){
                    mp.stop();
                    sb.setProgress(mp.getDuration());
                    //mp = null;
                }
                Toast.makeText(MainActivity.this, "Stoped", Toast.LENGTH_SHORT).show();
            }
        });

        sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
            @Override
            public void onStopTrackingTouch(SeekBar seekBar){
                //if(mp!=null){
                if(!mp.isPlaying()){
                    mp.seekTo(seekBar.getProgress());
                    mp.start();
                }
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar){
                //if(mp!=null)
                 if(mp.isPlaying()){
                     mp.pause();
                 }else
                     mp.start();
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){

            }
        });

        Button btn = (Button)findViewById(R.id.secondActivityButton);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, second.class));
            }
        });
    }

    public void MyOwnClick(View v){
        startActivity(new Intent(MainActivity.this, second.class));
    }

    public Runnable run = new Runnable() {
        @Override
        public void run() {
            SeekUpdation();
        }
    };

    public void SeekUpdation() {
        //if(mp!=null)
        if(mp.isPlaying() == true)
        {
            sb.setProgress(mp.getCurrentPosition());
            han.postDelayed(run, 1000);
            //Toast.makeText(MainActivity.this, "is Playing", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(MainActivity.this, "Seek", Toast.LENGTH_SHORT).show();
        }
    }
}
</code>```

答:
For a quick solution you can create a method like this:

```<code>void resetMediaPlayer() {
   if(mediaPlayer!=null) {
       try {
             mediaPlayer.reset();
       }
       catch(Exception e) {
           e.printStackTrace();
       }
   }
}
</code>```

Then override the onBackPressed method in your activity and call resetMediaPlayer :

```<code>@Override
public void onBackPressed(){
    super.onBackPressed();
  resetMediaPlayer()
}
</code>```

Or call it anywhere you need to stop your media player.

This is not a good way to stop media player though. for a better implementation you have to change your resetMediaPlayer method like this:

```<code>void resetMediaPlayer() {
    if(mediaPlayer!=null) {
        try {
            mediaPlayer.reset();
            mediaPlayer.release();
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

And whenever you want to start Media Player you have to create a new instance of Media Player for example:

```<code>void startMediaPlayer(int selectedSong) {
    try {
        mediaPlayer = MediaPlayer.create(activity, selectedSong);
        mediaPlayer.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

And also call resetMediaPlayer in onDestroy method of your activity:

```<code>@Override
protected void onDestroy() {
    super.onDestroy();
    resetPlayView();
}
</code>```

Body:
I'm new in Android environment, my problem is while I Play audio file and go to other activity or press back button, and again open my application where I've played audio, it doesn't stop while i press stop button. it works when i press home button and try to stop. can anyone suggest me what to
 Here's the code of my activity

package com.example.mudassar.myaudioapp;

import android.content.Intent;
import android.os.Environment;
import android.os.NetworkOnMainThreadException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    //MediaPlayer mp;
    Button playBtn, pauseBtn, stopBtn;
    SeekBar sb;
    Handler han = new Handler();
    MediaPlayer mp;// = MediaPlayer.create(MainActivity.this, R.raw.firefly);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        playBtn= (Button)findViewById(R.id.playBtn);
        pauseBtn= (Button)findViewById(R.id.pauseBtn);
        stopBtn=(Button) findViewById(R.id.stopBtn);

        try{
            //you can change the path, here path is external directory(e.g. sdcard) /Music/maine.mp3
            //mp.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/raw/.mp3");
            mp = MediaPlayer.create(MainActivity.this, R.raw.firefly);
            mp.prepare();
        }catch(Exception e){e.printStackTrace();}

        sb = (SeekBar)findViewById(R.id.seekBar);
        sb.setMax(mp.getDuration());

        SeekUpdation();

        playBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SeekUpdation();
                //if (mp == null)
                if(mp.isPlaying() == false)
                    mp = MediaPlayer.create(MainActivity.this, R.raw.firefly);
                mp.start();
                sb.setMax(mp.getDuration());
                sb.setProgress(mp.getCurrentPosition());
            }
        });

        pauseBtn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                if(mp.isPlaying() == false){
                    mp.start();
                    sb.setProgress(mp.getCurrentPosition());
                    Toast.makeText(MainActivity.this, "Playing", Toast.LENGTH_SHORT).show();
                }else if(mp.isPlaying() == true){
                    mp.pause();
                    sb.setProgress(mp.getCurrentPosition());
                    Toast.makeText(MainActivity.this, "Paused", Toast.LENGTH_SHORT).show();
                }

            }
        });

        stopBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //if (mp != null) {
                if(mp.isPlaying() == true){
                    mp.stop();
                    sb.setProgress(mp.getDuration());
                    //mp = null;
                }
                Toast.makeText(MainActivity.this, "Stoped", Toast.LENGTH_SHORT).show();
            }
        });

        sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
            @Override
            public void onStopTrackingTouch(SeekBar seekBar){
                //if(mp!=null){
                if(!mp.isPlaying()){
                    mp.seekTo(seekBar.getProgress());
                    mp.start();
                }
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar){
                //if(mp!=null)
                 if(mp.isPlaying()){
                     mp.pause();
                 }else
                     mp.start();
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){

            }
        });

        Button btn = (Button)findViewById(R.id.secondActivityButton);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, second.class));
            }
        });
    }

    public void MyOwnClick(View v){
        startActivity(new Intent(MainActivity.this, second.class));
    }

    public Runnable run = new Runnable() {
        @Override
        public void run() {
            SeekUpdation();
        }
    };

    public void SeekUpdation() {
        //if(mp!=null)
        if(mp.isPlaying() == true)
        {
            sb.setProgress(mp.getCurrentPosition());
            han.postDelayed(run, 1000);
            //Toast.makeText(MainActivity.this, "is Playing", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(MainActivity.this, "Seek", Toast.LENGTH_SHORT).show();
        }
    }
}

Body:
For a quick solution you can create a method like this:

void resetMediaPlayer() {
   if(mediaPlayer!=null) {
       try {
             mediaPlayer.reset();
       }
       catch(Exception e) {
           e.printStackTrace();
       }
   }
}

Then override the onBackPressed method in your activity and call resetMediaPlayer :

@Override
public void onBackPressed(){
    super.onBackPressed();
  resetMediaPlayer()
}

Or call it anywhere you need to stop your media player.

This is not a good way to stop media player though. for a better implementation you have to change your resetMediaPlayer method like this:

void resetMediaPlayer() {
    if(mediaPlayer!=null) {
        try {
            mediaPlayer.reset();
            mediaPlayer.release();
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
}

And whenever you want to start Media Player you have to create a new instance of Media Player for example:

void startMediaPlayer(int selectedSong) {
    try {
        mediaPlayer = MediaPlayer.create(activity, selectedSong);
        mediaPlayer.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

And also call resetMediaPlayer in onDestroy method of your activity:

@Override
protected void onDestroy() {
    super.onDestroy();
    resetPlayView();
}


问:
How can I disable a table in a SQL Server database from SSMS
I inherited a SQL Server database used with a C# client application. I know enough to be dangerous but I'm not a programmer. I know the previous programmer liked to play around in the live database and as a result I have a number of what I think are orphaned tables.

The application itself isn't super high-usage and can withstand the exceptions of tables not being there for a small time frame. I'd like to start turning off or disabling these tables to see they're being used anymore through trial and error.

Is there a way to turn them off without completely removing the data so that I can re-enable them quickly if needed? Or is there a more transparent way to discover whether those tables are needed?

答:
You could create a new db schema and transfer the tables to that schema

ALTER SCHEMA new schema TRANSFER dbo.your table

Then transfer them back again after testing.

https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-schema-transact-sql


问:
Best Practice setup for Parameter Sets
I'm trying to setup parameter sets but I'm unsure if that's the best practice approch to what I'm trying to do.  The setup I'm looking for is the following:

```<code>$FolderSetup - Not Manditory.  [ValidateSet("Yes", "No"] Default is "No"
    If "Yes" is used, then no following parameters should be able to be selected
$OSVersion - Manditory.  [ValidateSet("2008SP2", "2008R2", "2012R2", "2016", "All")].
    If "All" is used, then no following parameters should be able to be selected

$InputFile - Not Manditory - User inputs location of file
$OutputFolder - Not Manditory.  - User inputs desired output location
    $InputFile must be used before $OutputFolder can be used.
</code>```

Examples:

```<code>SinglePackage -FolderSetup 'Yes'
    #No Other Parameters can be used
SinglePackage -OSVersion 'All'
    #No Other Parameters can be used
SinglePackage -OSVersion '2008SP2'
SinglePackage -OSVersion '2008SP2' -InputFile 'C:\Temp\MyFile.txt'
SinglePackage -OSVersion '2008SP2' -InputFile 'C:\Temp\MyFile.txt' -OutputFolder 'C:\Temp\MyFolder'
SinglePackage -OSVersion '2008SP2' -OutputFolder 'C:\Temp\MyFolder'
    #Not Allowed.  Must have -InputFile if using -OutputFolder
</code>```

答:
I think the best way to do this would be to declare the parameter block as follows:

```<code>param(
    [Parameter(Mandatory=$true,ParameterSetName="Folder")]
    [switch]$FolderSetup,

    [Parameter(Mandatory=$true,ParameterSetName="AllVersions")]
    [Alias("AllOS")]
    [switch]$All,

    [Parameter(Mandatory=$true,ParameterSetName="OSSpecific")]
    [Parameter(Mandatory=$true,ParameterSetName="IOFolders")]
    [ValidateSet("2008SP2","2008R2", "2102R2", "2016")]
    [string]$OSVersion,

    [Parameter(Mandatory=$true,ParameterSetName="IOFolders")]
    [string]$InputFolder,

    [Parameter(ParameterSetName="IOFolders")]
    [string]$OutputFolder
)
</code>```

This forces the call to be in one of the valid forms you gave above, and prohibits the invalid combinations. If it can't figure out which set of parameters is being used, it will throw an error saying so - but that's a guarantee that an invalid combination of parameters was attempted.

It does have the constraint that you can't use -OSVersion "All"; use -All or -AllOS instead.

Title: Best Practice setup for Parameter Sets

Body:
I'm trying to setup parameter sets but I'm unsure if that's the best practice approch to what I'm trying to do.  The setup I'm looking for is the following:

$FolderSetup - Not Manditory.  [ValidateSet("Yes", "No"] Default is "No"
    If "Yes" is used, then no following parameters should be able to be selected
$OSVersion - Manditory.  [ValidateSet("2008SP2", "2008R2", "2012R2", "2016", "All")].
    If "All" is used, then no following parameters should be able to be selected

$InputFile - Not Manditory - User inputs location of file
$OutputFolder - Not Manditory.  - User inputs desired output location
    $InputFile must be used before $OutputFolder can be used.

Examples:

SinglePackage -FolderSetup 'Yes'
    #No Other Parameters can be used
SinglePackage -OSVersion 'All'
    #No Other Parameters can be used
SinglePackage -OSVersion '2008SP2'
SinglePackage -OSVersion '2008SP2' -InputFile 'C:\Temp\MyFile.txt'
SinglePackage -OSVersion '2008SP2' -InputFile 'C:\Temp\MyFile.txt' -OutputFolder 'C:\Temp\MyFolder'
SinglePackage -OSVersion '2008SP2' -OutputFolder 'C:\Temp\MyFolder'
    #Not Allowed.  Must have -InputFile if using -OutputFolder

Body:
I think the best way to do this would be to declare the parameter block as follows:

param(
    [Parameter(Mandatory=$true,ParameterSetName="Folder")]
    [switch]$FolderSetup,

    [Parameter(Mandatory=$true,ParameterSetName="AllVersions")]
    [Alias("AllOS")]
    [switch]$All,

    [Parameter(Mandatory=$true,ParameterSetName="OSSpecific")]
    [Parameter(Mandatory=$true,ParameterSetName="IOFolders")]
    [ValidateSet("2008SP2","2008R2", "2102R2", "2016")]
    [string]$OSVersion,

    [Parameter(Mandatory=$true,ParameterSetName="IOFolders")]
    [string]$InputFolder,

    [Parameter(ParameterSetName="IOFolders")]
    [string]$OutputFolder
)

This forces the call to be in one of the valid forms you gave above, and prohibits the invalid combinations. If it can't figure out which set of parameters is being used, it will throw an error saying so - but that's a guarantee that an invalid combination of parameters was attempted.

It does have the constraint that you can't use -OSVersion "All"; use -All or -AllOS instead.


问:
JSON Deserialize to generic type
I am writing tests for my controllers (ASP.NET Core), and am receiving back some JSON.  I would now like to deserialize it into the correct object so that I can do some assertions against the returned data.  There are no exceptions thrown during deserialization, but my Data variable is null.

Here is the code used for the deserialization:

```<code>var output = JsonConvert.DeserializeObject(responseString,
                typeof(CrudOperationResult<IEnumerable<ApiResource>>));
</code>```

This is the CrudOperationResult class:

```<code>public class CrudOperationResult<T>
{
    private CrudOperationResult()
    { }

    private CrudOperationResult(CrudResult result, string errorMessage, T data)
    {
        Result = result;
        ErrorMessage = errorMessage;
        Data = data;
    }

    [JsonIgnore]
    public CrudResult Result { get; private set; }

    public bool IsError
    {
        get
        {
            return Result == CrudResult.Error;
        }
    }

    public string ErrorMessage { get; private set; }

    public T Data { get; private set; }
}
</code>```

And here is the JSON data returned:

```<code>{
    "isError": false,
    "errorMessage": null,
    "data": [{
        "id": 1,
        "enabled": true,
        "name": "apiResource1",
        "displayName": "My API",
        "description": null,
        "secrets": null,
        "scopes": [{
            "id": 1,
            "name": "apiResource1",
            "displayName": "My API",
            "description": null,
            "required": false,
            "emphasize": false,
            "showInDiscoveryDocument": true,
            "userClaims": null
        }],
        "userClaims": [{
            "id": 1,
            "type": "role"
        },
        {
            "id": 2,
            "type": "user"
        }]
    }]
}
</code>```

答: Because of the [...] JsonConvert.DeserializeObject thinks data a List<T> Data { get; private set; }.

Title: JSON Deserialize to generic type

Body:
I am writing tests for my controllers (ASP.NET Core), and am receiving back some JSON.  I would now like to deserialize it into the correct object so that I can do some assertions against the returned data.  There are no exceptions thrown during deserialization, but my Data variable is null.

Here is the code used for the deserialization:

var output = JsonConvert.DeserializeObject(responseString,
                typeof(CrudOperationResult<IEnumerable<ApiResource>>));

This is the CrudOperationResult class:

public class CrudOperationResult<T>
{
    private CrudOperationResult()
    { }

    private CrudOperationResult(CrudResult result, string errorMessage, T data)
    {
        Result = result;
        ErrorMessage = errorMessage;
        Data = data;
    }

    [JsonIgnore]
    public CrudResult Result { get; private set; }

    public bool IsError
    {
        get
        {
            return Result == CrudResult.Error;
        }
    }

    public string ErrorMessage { get; private set; }

    public T Data { get; private set; }
}

And here is the JSON data returned:

{
    "isError": false,
    "errorMessage": null,
    "data": [{
        "id": 1,
        "enabled": true,
        "name": "apiResource1",
        "displayName": "My API",
        "description": null,
        "secrets": null,
        "scopes": [{
            "id": 1,
            "name": "apiResource1",
            "displayName": "My API",
            "description": null,
            "required": false,
            "emphasize": false,
            "showInDiscoveryDocument": true,
            "userClaims": null
        }],
        "userClaims": [{
            "id": 1,
            "type": "role"
        },
        {
            "id": 2,
            "type": "user"
        }]
    }]
}


问:
How to read JSON response produced by PHP using angular 2
I am using angular 2 as front end and PHP, MySQL for my back end.

PHP properly creates json data but angular 2 unable to read the file content. I am getting the below error.

```<code>XMLHttpRequest cannot load http://localhost:81/login.json.
 No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 404.
</code>```

JSON file available at http://localhost:81/login.json location. I am using XAMPP to run my php file.

My angular 2 code is below.

```<code>import { Component, OnInit, Input } from '@angular/core';
import { Http, Response } from '@angular/http';

@Component({
  moduleId: module.id,
  selector: 'app-header-modal',
  templateUrl: './header-modal.component.html',
  styleUrls: ['./header-modal.component.css']
})

    export class HeaderModalComponent implements OnInit {

       private data;

        constructor(private http:Http){
        }

        ngOnInit(){

        }
        ngAfterViewInit() {
           this.getData();
        }
        getData(){
            this.http.get('http://localhost:81/login.json')
                    .subscribe(res => this.data = res.json());

                console.log('User Data: '+this.data);
        }

    }
</code>```

My PHP code is below.

```<code><?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: X-Requested-With");

include 'connect.php';

$username       = str_replace(" ", "", $_POST['username']);
$password       = str_replace(" ", "", $_POST['password']);

    $query      =   mysql_query("select username, password, id from registration where username='".$username."' and password='".$password."'");
    $result     =   mysql_fetch_array($query);
    if($result){
        $data = array(
        array('userId' => $result['id'],'userName' => $result['username'])
    );

    $fp = fopen('login.json', 'w');
    fwrite($fp, json_encode($data));
    fclose($fp);

    ?>
        <script>
            history.go(-1);
        </script>
    <?php

}

?>
</code>```

Can somebody help!

答:
This appears to be a CORS issue with the php server backend you are trying to use. You angular App doesn't have the ability to make a request to the php server because of CORS.

Once you have properly configured the php server the request should start working.

More information on CORS.

Body:
I am using angular 2 as front end and PHP, MySQL for my back end.

PHP properly creates json data but angular 2 unable to read the file content. I am getting the below error.

XMLHttpRequest cannot load http://localhost:81/login.json.
 No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 404.

JSON file available at http://localhost:81/login.json location. I am using XAMPP to run my php file.

My angular 2 code is below.

import { Component, OnInit, Input } from '@angular/core';
import { Http, Response } from '@angular/http';

@Component({
  moduleId: module.id,
  selector: 'app-header-modal',
  templateUrl: './header-modal.component.html',
  styleUrls: ['./header-modal.component.css']
})

    export class HeaderModalComponent implements OnInit {

       private data;

        constructor(private http:Http){
        }

        ngOnInit(){

        }
        ngAfterViewInit() {
           this.getData();
        }
        getData(){
            this.http.get('http://localhost:81/login.json')
                    .subscribe(res => this.data = res.json());

                console.log('User Data: '+this.data);
        }

    }

My PHP code is below.

<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: X-Requested-With");

include 'connect.php';

$username       = str_replace(" ", "", $_POST['username']);
$password       = str_replace(" ", "", $_POST['password']);

    $query      =   mysql_query("select username, password, id from registration where username='".$username."' and password='".$password."'");
    $result     =   mysql_fetch_array($query);
    if($result){
        $data = array(
        array('userId' => $result['id'],'userName' => $result['username'])
    );

    $fp = fopen('login.json', 'w');
    fwrite($fp, json_encode($data));
    fclose($fp);

    ?>

    <?php

}

?>

Can somebody help!


问:
Is zip() the most efficient way to combine arrays with respect to memory in numpy?
I use numpy and have two arrays, which are read with genfromtxt.

They have the shape <10000,> according to np.shape().

I want these two vectors to be in an array with the shape <10000,2>. For now I use:

```<code>x = zip(x1,x2)
</code>```

but i am not sure if there is numpy function that does this better/more efficient. I dont think concatenate does what I think (or I'm doing it wrong).

答:
A simple test:

```<code>python -m timeit "import numpy as np; x, y = np.array([range(100000), range(100000,200000)]); zip(x,y)"
</code>```

10 loops, best of 3: 32.2 msec per loop

```<code>python -m timeit "import numpy as np; x, y = np.array([range(100000), range(100000,200000)]); np.column_stack((x, y))"
</code>```

10 loops, best of 3: 14.4 msec per loop

Body:
I use numpy and have two arrays, which are read with genfromtxt.

They have the shape <10000,> according to np.shape().

I want these two vectors to be in an array with the shape <10000,2>. For now I use:

x = zip(x1,x2)

but i am not sure if there is numpy function that does this better/more efficient. I dont think concatenate does what I think (or I'm doing it wrong).

Body:
A simple test:

python -m timeit "import numpy as np; x, y = np.array([range(100000), range(100000,200000)]); zip(x,y)"

10 loops, best of 3: 32.2 msec per loop

python -m timeit "import numpy as np; x, y = np.array([range(100000), range(100000,200000)]); np.column_stack((x, y))"

10 loops, best of 3: 14.4 msec per loop


问:
Is there a way to simplify OpenCl kernels usage ?
To use OpenCL kernel the following is needed:

Put the kernel code in a string

call clCreateProgramWithSource

call clBuildProgram

call clCreateKernel

call clSetKernelArg (x number of arguments)

call clEnqueueNDRangeKernel

This need to be done for each kernel. Is there a way to do this repeating less code for each kernel?

答:
There is no way to speed up the process. You need to go step by step as you listed.

But it is important to know why it is needed these steps, to understand how flexible the chain is.

clCreateProgramWithSource: Allows to add different strings from different sources to generate the program. Some string might be static, but some might be downloaded from a server, or loaded from disk. It allows the CL code to be dynamic and updated over time.

clBuildProgram: Builds the program for a given device. Maybe you have 8 devices, so you need to call this multiple times. Each device will produce a different binary code.

clCreateKernel: Creates a kernel. But a kernel is an entry point in a binary. So it is possible you create multiple kernels from a program (for different functions). Also the same kernel might be created multiple times, since it holds the arguments. This is useful for having ready-to-be-launched instances with proper parameters.

clSetKernelArg: Changes the parameters in the instance of the kernel. (it is stored there, so it can used multiple times in the future).

clEnqueueNDRangeKernel: Launches it, configuring the size of the launch and the chain of dependencies with other operations.

So, even if you could have a way to just call "getKernelFromString()", the functionality will be very limited, and not very flexible.


问:
a function produces an inifinite loop
I wrote the following function and when I run it , it produces an infinite loop and I dont understand why.

This function creates a dynamic array of dynamic strings. Every such string starts with  a letter given, or with a capital letter which is compatible to the letter given:

```<code>void wordsStartWithLetter(char letter, char *str,char***newstr,int *numOfWords)
{
    int i=0, count=0;
    char *word;
    char *delimiter = " ";

    while (str[i] != '\0')
    {
        if (str[i]==letter ||str[i]==(letter-32 )) //if it founds the letter at the begining of the word, than run till the space//
        {
            while (str[i] != ' ' && str[i] != '\0' )
              i++;      //counting the number of words beginng with the letter given//
            count++;
        }
        else
        {
            while (str[i] != ' ' && str[i] != '\0' )
                i++;
        }
    }

    *newstr = (char**)malloc (sizeof(char*)*count);
    *numOfWords=count;
    i=0;

    word = strtok(str, delimiter);      //we use strtok to separate each word from the origin string//

    while(word!=NULL)
    {
        if (word[0]==letter ||word[0]==letter-32)
        {
            (*newstr)[i]=word;                 //insert the compatible words into the new 2D-string//
            i++;
        }
        word = strtok(NULL, delimiter);
    }

}
</code>```

I call that  function the by the following way:

```<code>#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>

#define SIZE 50

void Ex();
void wordsStartWithLetter(char letter, char *str,char***newstr,int *numOfWords) ;

void main()
{

    Ex();
}

void Ex()
{
    char ch;
    char str[SIZE];
    char **newstr;
    int numOfWords,i;

    printf("please enter a string: ");
    _flushall();
    gets(str);
    printf("plese enter a letter: " );
    _flushall();
    ch=_getche();
    wordsStartWithLetter(ch, str,&newstr,&numOfWords);

    ("the words of the origin string which start which %c :\n",ch);
    for(i=0;i<numOfWords;i++)
        printf("%s\n",newstr[i]);

    for (i=0;i<numOfWords; i++)
       free(newstr[i]);
    free(newstr);
}
</code>```

答:
Consider this input string "a b" and assume the letter is c.

When i is 0 you enter the code below because str[0]is a which doesn't match the letter:

```<code>    else
    {
        while (str[i] != ' ' && str[i] != '\0' )
            i++;   // Increment i from 0 to 1
    }
</code>```

In the above block, you increment i to 1 and then leave the block because str[1] is ' '

In the next main loop, you will again hit this code block:

```<code>    else
    {
        while (str[i] != ' ' && str[i] != '\0' )
            i++;   // No increment, i.e. i stays at 1
    }
</code>```

but you will not increment i (as str[1] is a space). In other words - i remains at 1 and you have an infinite loop.

Maybe you can fix it by this:

```<code>    else
    {
        while (str[i] != ' ' && str[i] != '\0' )
            i++;   // No increment, i.e. i stays at 1

        // Add this line to remove the spaces
        while (str[i] == ' ') i++;
    }
</code>```

Title: a function produces an inifinite loop

Body:
I wrote the following function and when I run it , it produces an infinite loop and I dont understand why.

This function creates a dynamic array of dynamic strings. Every such string starts with  a letter given, or with a capital letter which is compatible to the letter given:

void wordsStartWithLetter(char letter, char *str,char***newstr,int *numOfWords)
{
    int i=0, count=0;
    char *word;
    char *delimiter = " ";

    while (str[i] != '\0')
    {
        if (str[i]==letter ||str[i]==(letter-32 )) //if it founds the letter at the begining of the word, than run till the space//
        {
            while (str[i] != ' ' && str[i] != '\0' )
              i++;      //counting the number of words beginng with the letter given//
            count++;
        }
        else
        {
            while (str[i] != ' ' && str[i] != '\0' )
                i++;
        }
    }

    *newstr = (char**)malloc (sizeof(char*)*count);
    *numOfWords=count;
    i=0;

    word = strtok(str, delimiter);      //we use strtok to separate each word from the origin string//

    while(word!=NULL)
    {
        if (word[0]==letter ||word[0]==letter-32)
        {
            (*newstr)[i]=word;                 //insert the compatible words into the new 2D-string//
            i++;
        }
        word = strtok(NULL, delimiter);
    }

}

I call that  function the by the following way:

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>

#define SIZE 50

void Ex();
void wordsStartWithLetter(char letter, char *str,char***newstr,int *numOfWords) ;

void main()
{

    Ex();
}

void Ex()
{
    char ch;
    char str[SIZE];
    char **newstr;
    int numOfWords,i;

    printf("please enter a string: ");
    _flushall();
    gets(str);
    printf("plese enter a letter: " );
    _flushall();
    ch=_getche();
    wordsStartWithLetter(ch, str,&newstr,&numOfWords);

    ("the words of the origin string which start which %c :\n",ch);
    for(i=0;i<numOfWords;i++)
        printf("%s\n",newstr[i]);

    for (i=0;i<numOfWords; i++)
       free(newstr[i]);
    free(newstr);
}

Body:
Consider this input string "a b" and assume the letter is c.

When i is 0 you enter the code below because str[0]is a which doesn't match the letter:

    else
    {
        while (str[i] != ' ' && str[i] != '\0' )
            i++;   // Increment i from 0 to 1
    }

In the above block, you increment i to 1 and then leave the block because str[1] is ' '

In the next main loop, you will again hit this code block:

    else
    {
        while (str[i] != ' ' && str[i] != '\0' )
            i++;   // No increment, i.e. i stays at 1
    }

but you will not increment i (as str[1] is a space). In other words - i remains at 1 and you have an infinite loop.

Maybe you can fix it by this:

    else
    {
        while (str[i] != ' ' && str[i] != '\0' )
            i++;   // No increment, i.e. i stays at 1

        // Add this line to remove the spaces
        while (str[i] == ' ') i++;
    }


问:
How can I get Mercurial to list all tracked files that are tracked as symlinks?
I would like to have Mercurial list all tracked files in the repo that are supposed to be symlinks.  I can get a list of tracked symlinks that are symlinks in the working copy with hg files "set:symlink()", but that doesn't capture the tracked symlinks that aren't symlinks in the working copy.

What I want instead is a command that looks at the tracked file's properties in the manifest and tells me if the symlink bit is set.  I've tried to use hg manifest -v, which the documentation says will "print file permissions, symlink and executable bits". I've tried that, but the symlinks are indistinguishable from non-link files whose executable bit is set.  I get lots of:

```<code>755 * path/to/file
</code>```

If I try to use the leading markers (hg manifest -v | grep '755 *'), the files I want are listed, but I also get lots of false positives.

Background: Adding and committing symbolic links seems to work for us, but Mercurial is refusing to create the symlinks when someone else pulls those changesets.  I understand why Mercurial is refusing: we run afoul of an undocumented rule.  So now we end up with files where the symlinks are supposed to be, and the content of the file is the path to which the symlink is supposed to point.  If I can get Mercurial to tell me which files are supposed to be symlinks, I can easily replace the files with the appropriate links.

Thank you!

Edit: In my repository, the symlinks had not been committed properly due to a bug in the client, which is why hg manifest -v wasn't showing the committed files as links.

答:
I've learned a few things, and I wasn't asking the right question, but let's get the close-enough answer out of the way first:

hg manifest -v | grep ' @ '

Caveat: I will guess that it's possible for manifest to put multiple symbols between the permissions number and the path, so ' @ ' as the grep expression may not work perfectly if you have an exotic set of bits on a file.  I needed the spaces around the @ because our repository has many files with @ in their names.

The rest of the story: After some experimentation, I was able to determine that a particular mercurial GUI (SourceTree) wasn't committing new symlinks correctly, which turned out to be a longstanding issue with the Mac version.  I created a new repo (hg init) and added/committed one target file and one symlink (Link\link.txt) with command-line hg.  I then added/committed a second symlink (Link\STlink.txt) with SourceTree.  hg manifest -v shows that the links were not treated the same by the different clients:

```<code>755 * Link/STlink.txt
644 @ Link/link.txt
644   Target/target.txt
</code>```

If I clone that repo, even with SourceTree, the Link/link.txt symlink is reproduced faithfully, but the Link\STlink.txt link is not.  So the real fix for me is to replace all of the files with links and commit again from the command line and to try to remember not to use SourceTree to commit new symlinks again in the future.

Body:
I would like to have Mercurial list all tracked files in the repo that are supposed to be symlinks.  I can get a list of tracked symlinks that are symlinks in the working copy with hg files "set:symlink()", but that doesn't capture the tracked symlinks that aren't symlinks in the working copy.

What I want instead is a command that looks at the tracked file's properties in the manifest and tells me if the symlink bit is set.  I've tried to use hg manifest -v, which the documentation says will "print file permissions, symlink and executable bits". I've tried that, but the symlinks are indistinguishable from non-link files whose executable bit is set.  I get lots of:

755 * path/to/file

If I try to use the leading markers (hg manifest -v | grep '755 *'), the files I want are listed, but I also get lots of false positives.

Background: Adding and committing symbolic links seems to work for us, but Mercurial is refusing to create the symlinks when someone else pulls those changesets.  I understand why Mercurial is refusing: we run afoul of an undocumented rule.  So now we end up with files where the symlinks are supposed to be, and the content of the file is the path to which the symlink is supposed to point.  If I can get Mercurial to tell me which files are supposed to be symlinks, I can easily replace the files with the appropriate links.

Thank you!

Edit: In my repository, the symlinks had not been committed properly due to a bug in the client, which is why hg manifest -v wasn't showing the committed files as links.

Body:
I've learned a few things, and I wasn't asking the right question, but let's get the close-enough answer out of the way first:

hg manifest -v | grep ' @ '

Caveat: I will guess that it's possible for manifest to put multiple symbols between the permissions number and the path, so ' @ ' as the grep expression may not work perfectly if you have an exotic set of bits on a file.  I needed the spaces around the @ because our repository has many files with @ in their names.

The rest of the story: After some experimentation, I was able to determine that a particular mercurial GUI (SourceTree) wasn't committing new symlinks correctly, which turned out to be a longstanding issue with the Mac version.  I created a new repo (hg init) and added/committed one target file and one symlink (Link\link.txt) with command-line hg.  I then added/committed a second symlink (Link\STlink.txt) with SourceTree.  hg manifest -v shows that the links were not treated the same by the different clients:

755 * Link/STlink.txt
644 @ Link/link.txt
644   Target/target.txt

If I clone that repo, even with SourceTree, the Link/link.txt symlink is reproduced faithfully, but the Link\STlink.txt link is not.  So the real fix for me is to replace all of the files with links and commit again from the command line and to try to remember not to use SourceTree to commit new symlinks again in the future.