问:
Unable to show Highcharts graph with in ASP.Net MVC
I was trying to bind data to Highcharts & display a column chart on webpage.
Below given jQuery AJAX method to call controller's action

```<code><script type="text/javascript">
$(document).ready(function () {
    $.ajax({
        url: '@Url.Action("getChartData", "Default")',
        dataType: 'json',
        type: 'GET',
        success: function (resData) {
            let dataArray = new Array();
            for (let i in resData) {
                let series = new Array(resData[i].CategoryName, resData[i].ProductName, resData[i].ProductSales);
                dataArray.push(series);
            }
            alert(dataArray);
            drawChart(dataArray);
        },
        error: function () {
            alert('Server couldnot process request');
        }
    });
});

function drawChart(resData) {
    $('#highchartData').highcharts({
        chart: {
            type: "column"
        },
        title: {
            text: 'Product Sales for year 1997'
        },
        series: {
            data: resData
        },
        plotOptions: {
            column: {
                dataLabels: { enabled: true }
            }
        },
        xAxis: {
            scrollbar: {
                enabled: true
            },
            //categories: ['Beverages', 'Seafood', 'Dairy Products', 'Condiments', 'Meat/Poultry', 'Confections', 'Grains/Cereals', 'Produce']
        },
        credits: {
            enabled: false
        },
        tooltip: {
            pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
        }
    });
}
</code>```

alert(dataArray); shows below data returned from controller's action

Meat/Poultry,Alice Mutton,16580.85,Condiments,Aniseed Syrup,1724,Seafood,Boston Crab Meat,9796.33,Dairy Products,Camembert Pierrot,20652.28,Seafood,Carnarvon Tigers,15950,Beverages,Chai,4887,Beverages,Chang,7038.55,Beverages,Chartreuse verte,4475.7,Condiments,Chef Anton's Cajun Seasoning,5214.88,Condiments,Chef Anton's Gumbo Mix,373.63,Confections,Chocolade,1282.01,Beverages,Côte de Blaye,46563.09,Seafood,Escargots de Bourgogne,2076.28,Grains/Cereals,Filo Mix,2068.15,Dairy Products,Flotemysost,9642.76,Dairy Products,Geitost,786,Condiments,Genen Shouyu,1474.83,Grains/Cereals,Gnocchi di nonna Alice,32604,Dairy Products,Gorgonzola Telino,7620.75,Condiments,Grandma's Boysenberry Spread,2500,Seafood,Gravad lax,629.2,Beverages,Guaraná Fantástica,1553.63,Dairy Products,Gudbrandsdalsost,14041.8,Condiments,Gula Malacca,6543.45,Confections,Gumbär Gummibärchen,11225.66,Grains/Cereals,Gustaf's Knäckebröd,4233.6,Seafood,Ikura,8819.5,Seafood,Inlagd Sill,6894.15,Beverages,Ipoh Coffee,11069.9,Seafood,Jack's New England Clam Chowder,4638.8,Seafood,Konbu,758.94,Beverages,Lakkalikööri,7883.1,Beverages,Laughing Lumberjack Lager,910,Produce,Longlife Tofu,888,Condiments,Louisiana Fiery Hot Pepper Sauce,9331.08,Condiments,Louisiana Hot Spiced Okra,2958,Produce,Manjimup Dried Apples,23550.02,Dairy Products,Mascarpone Fabioli,2668.8,Confections,Maxilaku,3060.6,Meat/Poultry,Mishi Kobe Niku,6935.5,Dairy Products,Mozzarella di Giovanni,11838.6,Seafood,Nord-Ost Matjeshering,5884.29,Condiments,Northwoods Cranberry Sauce,4260,Confections,NuNuCa Nuß-Nougat-Creme,1551.9,Condiments,Original Frankfurter grüne Soße

Here i observed that data returned didn't have column names as

{"CategoryName":"Meat/Poultry","ProductName":"Alice Mutton","ProductSales":16580.8500}

I can see the title given for column chart as 'Product Sales for year 1997' and also the options to print/ download chart. But the chart isn't shown. How to fix this and where did i go wrong?

答:
In this line you define a format for the data:

```<code>let series = new Array(resData[i].CategoryName, resData[i].ProductName, resData[i].ProductSales);
</code>```

In Highcharts data is an array of points. Information about every point is grouped into an object or an array. It seems that you omit grouping and push all the properties from all the points into one array (which is not correct).

Refer to this Docs page: https://www.highcharts.com/docs/chart-concepts/series

It explains how to format your data properly before using it in the chart constructor.

Body:
In this line you define a format for the data:

let series = new Array(resData[i].CategoryName, resData[i].ProductName, resData[i].ProductSales);

In Highcharts data is an array of points. Information about every point is grouped into an object or an array. It seems that you omit grouping and push all the properties from all the points into one array (which is not correct).

Refer to this Docs page: https://www.highcharts.com/docs/chart-concepts/series

It explains how to format your data properly before using it in the chart constructor.


来源: stackexchange

问:
ValuError encounted in SMOTE imblearn.over_sampling
I have been trying to oversample my dataset since it is not balanced. I am doing a binary text classification and would like to keep a ratio of 1 between both my classes. I am trying the SMOTE mechanism to solve the problem.

I followed this tutorial:
https://beckernick.github.io/oversampling-modeling/

However, I encounter an error which says:

ValueError: could not convert string to float

Here is my code:

```<code>import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline
from sklearn.model_selection import KFold
from sklearn.metrics import confusion_matrix, f1_score
from imblearn.over_sampling import SMOTE

data = pd.read_csv("dataset.csv")

nb_pipeline = Pipeline([
    ('vectorizer', CountVectorizer(ngram_range = (1, 10))),
    ('tfidf_transformer', TfidfTransformer()),
    ('classifier', MultinomialNB())
])

k_fold = KFold(n_splits = 10)
nb_f1_scores = []
nb_conf_mat = np.array([[0, 0], [0, 0]])

for train_indices, test_indices in k_fold.split(data):

    train_text = data.iloc[train_indices]['sentence'].values
    train_y = data.iloc[train_indices]['isRelevant'].values

    test_text = data.iloc[test_indices]['sentence'].values
    test_y = data.iloc[test_indices]['isRelevant'].values

    sm = SMOTE(ratio = 1.0)
    train_text_res, train_y_res = sm.fit_sample(train_text, train_y)

    nb_pipeline.fit(train_text, train_y)
    predictions = nb_pipeline.predict(test_text)

    nb_conf_mat += confusion_matrix(test_y, predictions)
    score1 = f1_score(test_y, predictions)
    nb_f1_scores.append(score1)

print("F1 Score: ", sum(nb_f1_scores)/len(nb_f1_scores))
print("Confusion Matrix: ")
print(nb_conf_mat)
</code>```

Can anyone tell me where I am going wrong, without the two lines of SMOTE, my program works fine.

答:
You should oversample after vectorizing the text data but before fitting the classifier. This means splitting up the pipeline in the code. The relevant part of the code should be something like this:</p>

```<code>nb_pipeline = Pipeline([
    ('vectorizer', CountVectorizer(ngram_range = (1, 10))),
    ('tfidf_transformer', TfidfTransformer())
])

k_fold = KFold(n_splits = 10)
nb_f1_scores = []
nb_conf_mat = np.array([[0, 0], [0, 0]])

for train_indices, test_indices in k_fold.split(data):

    train_text = data.iloc[train_indices]['sentence'].values
    train_y = data.iloc[train_indices]['isRelevant'].values

    test_text = data.iloc[test_indices]['sentence'].values
    test_y = data.iloc[test_indices]['isRelevant'].values

    vectorized_text = nb_pipeline.fit_transform(train_text)

    sm = SMOTE(ratio = 1.0)
    train_text_res, train_y_res = sm.fit_sample(vectorized_text, train_y)

    clf = MultinomialNB()
    clf.fit(train_text_res, train_y_res)
    predictions = clf.predict(nb_pipeline.transform(test_text))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have been trying to oversample my dataset since it is not balanced. I am doing a binary text classification and would like to keep a ratio of 1 between both my classes. I am trying the SMOTE mechanism to solve the problem.

I followed this tutorial:
https://beckernick.github.io/oversampling-modeling/

However, I encounter an error which says:

ValueError: could not convert string to float

Here is my code:

import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import Pipeline
from sklearn.model_selection import KFold
from sklearn.metrics import confusion_matrix, f1_score
from imblearn.over_sampling import SMOTE

data = pd.read_csv("dataset.csv")

nb_pipeline = Pipeline([
    ('vectorizer', CountVectorizer(ngram_range = (1, 10))),
    ('tfidf_transformer', TfidfTransformer()),
    ('classifier', MultinomialNB())
])

k_fold = KFold(n_splits = 10)
nb_f1_scores = []
nb_conf_mat = np.array([[0, 0], [0, 0]])

for train_indices, test_indices in k_fold.split(data):

    train_text = data.iloc[train_indices]['sentence'].values
    train_y = data.iloc[train_indices]['isRelevant'].values

    test_text = data.iloc[test_indices]['sentence'].values
    test_y = data.iloc[test_indices]['isRelevant'].values

    sm = SMOTE(ratio = 1.0)
    train_text_res, train_y_res = sm.fit_sample(train_text, train_y)

    nb_pipeline.fit(train_text, train_y)
    predictions = nb_pipeline.predict(test_text)

    nb_conf_mat += confusion_matrix(test_y, predictions)
    score1 = f1_score(test_y, predictions)
    nb_f1_scores.append(score1)

print("F1 Score: ", sum(nb_f1_scores)/len(nb_f1_scores))
print("Confusion Matrix: ")
print(nb_conf_mat)

Can anyone tell me where I am going wrong, without the two lines of SMOTE, my program works fine.

Body:
You should oversample after vectorizing the text data but before fitting the classifier. This means splitting up the pipeline in the code. The relevant part of the code should be something like this:

nb_pipeline = Pipeline([
    ('vectorizer', CountVectorizer(ngram_range = (1, 10))),
    ('tfidf_transformer', TfidfTransformer())
])

k_fold = KFold(n_splits = 10)
nb_f1_scores = []
nb_conf_mat = np.array([[0, 0], [0, 0]])

for train_indices, test_indices in k_fold.split(data):

    train_text = data.iloc[train_indices]['sentence'].values
    train_y = data.iloc[train_indices]['isRelevant'].values

    test_text = data.iloc[test_indices]['sentence'].values
    test_y = data.iloc[test_indices]['isRelevant'].values

    vectorized_text = nb_pipeline.fit_transform(train_text)

    sm = SMOTE(ratio = 1.0)
    train_text_res, train_y_res = sm.fit_sample(vectorized_text, train_y)

    clf = MultinomialNB()
    clf.fit(train_text_res, train_y_res)
    predictions = clf.predict(nb_pipeline.transform(test_text))


问:
Tornado: get request arguments
I have following code:

```<code>application = tornado.web.Application([
    (r"/get(.*)", GetHandler),
])

class GetHandler(tornado.web.RequestHandler):
    def get(self, key):
        response = {'key': key}
        self.write(response)
</code>```

when I go to localhost:port/get?key=python I receive empty key value {'key': ''}. What is wrong here?

答:
 I hope that you will figure what you did wrong by yourself - that's a task for you.

Your working code:

```<code>import tornado.ioloop
import tornado.web

class GetHandler(tornado.web.RequestHandler):
    def get(self):
        response = self.get_arguments("key")
        if len(response) == 0:
            # Handle me
            self.set_status(400)
            return self.finish("Invalid key")
        self.write({"key":self.get_argument("key")})

def make_app():
    return tornado.web.Application([
        (r"/", GetHandler),
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()
</code>```

Title: Tornado: get request arguments

Body:
I have following code:

application = tornado.web.Application([
    (r"/get(.*)", GetHandler),
])

class GetHandler(tornado.web.RequestHandler):
    def get(self, key):
        response = {'key': key}
        self.write(response)

when I go to localhost:port/get?key=python I receive empty key value {'key': ''}. What is wrong here?

Body:
 I hope that you will figure what you did wrong by yourself - that's a task for you.

Your working code:

import tornado.ioloop
import tornado.web

class GetHandler(tornado.web.RequestHandler):
    def get(self):
        response = self.get_arguments("key")
        if len(response) == 0:
            # Handle me
            self.set_status(400)
            return self.finish("Invalid key")
        self.write({"key":self.get_argument("key")})

def make_app():
    return tornado.web.Application([
        (r"/", GetHandler),
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

ContentLicense: CC BY-SA 4.0


问:
Wordpress single image lightbox gallery
I am trying to create lightbox gallery in Wordpress. I would like to display gallery as single image. When user clicks on image lightbox opens and you can navigate (left-right) through gallery.

I tried many plugins but none of them gives me an option to display gallery as single image. I can write code but but I would like to know is there a plugin for a kind of gallery I described above (for easier adding of future galleries).

If you know any other solution please let me know. I would appreciate it very much.

答:
I did something like this recently with the native WordPress galleries, a little CSS, and the lightbox plugin I was already using on a site: dFactory's Responsive Lightbox.

The plugin will show your entire gallery in a lightbox even if you hide all but the first slide. If you don't want this to effect all your galleries either create a alternate page template with a different ID, or enclose the gallery/galleries in a div in the text editor. Here's the CSS:

```<code>#your-content .gallery .gallery-item {display:none;}
#your-content .gallery .gallery-item:first-child {display:block;}
</code>```

I used it to create a set of albums where the first image served as the album cover. This little bit below gave me six images across with captions, where you click on the single image and get a full gallery for each.

```<code>#your-content .gallery {
  width:14.6%;
  float:left;
  clear:none;
  position:relative;
  margin:1%;
  padding:0;
  }
</code>```

Title: Wordpress single image lightbox gallery

Body:
I did something like this recently with the native WordPress galleries, a little CSS, and the lightbox plugin I was already using on a site: dFactory's Responsive Lightbox.

The plugin will show your entire gallery in a lightbox even if you hide all but the first slide. If you don't want this to effect all your galleries either create a alternate page template with a different ID, or enclose the gallery/galleries in a div in the text editor. Here's the CSS:

#your-content .gallery .gallery-item {display:none;}
#your-content .gallery .gallery-item:first-child {display:block;}

I used it to create a set of albums where the first image served as the album cover. This little bit below gave me six images across with captions, where you click on the single image and get a full gallery for each.

#your-content .gallery {
  width:14.6%;
  float:left;
  clear:none;
  position:relative;
  margin:1%;
  padding:0;
  }


问:
How well does NHibernate handle large models (about 1000 tables)?
I have seen a few discussions about how well Entity Framework works with large models - most prominently that question.

But I haven't been able to find any substantial information about how well NHibernate handles large models - what are the difficulties, and are they not too hard to work around?

答:
There shouldn't be any issues with large models.

Of course, for ease of maintenance, you should use a conventions-based data mapping approach, like ConfORM or Fluent NHibernate.

ContentLicense: CC BY-SA 2.5


问:
In Robot framework how to log to console during execution
i'm actually trying to run a keyword from imported test library written in java (RF 3.0.2 , Jython 2.7.1rc3 )

```<code>import org.apache.log4j.Logger;

public class Sample
{
private static final Logger logger = Utils.getLogger(Sample.class);

@RobotKeyword("Print Message")
@ArgumentNames({"message"})
public void printMessage(String message)
   {
    logger.info("I'm inside");
   }
}
</code>```

```<code>import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class Utils
{
    public static final Logger logger = getLogger(Utils.class);

    public static Logger getLogger(Class<?> clazz)
    Logger logger = Logger.getLogger(className.getClass());
    PropertyConfigurator.configure("/src/main/resources/log4j.properties");
    return logger;
}
</code>```

log4j.properties :

```<code>log4j.rootLogger=DEBUG, Stdout, file
log4j.appender.Stdout=org.apache.log4j.ConsoleAppender
log4j.appender.Stdout.Target=System.out
log4j.appender.Stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.Stdout.layout.conversionPattern=%d %-5p [%t] %F:%L %m%n
log4j.appender.Stdout.ImmediateFlush=true
log4j.appender.Stdout.follow=true
</code>```

With this setup i'm able to see log after test execution in robot framework test report but it would be very helpful if i can see logs during test execution as if i was calling log to console keyword.

is There a way to do this ?

答:
You can use listener interface http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#listener-interface to get real time execution information. In docs there is a sample script.

This is used in RED Robot Editor to get execution status,debug information etc. - source can be found:
TestRunnerAgent.py

Body:
i'm actually trying to run a keyword from imported test library written in java (RF 3.0.2 , Jython 2.7.1rc3 )

import org.apache.log4j.Logger;

public class Sample
{
private static final Logger logger = Utils.getLogger(Sample.class);

@RobotKeyword("Print Message")
@ArgumentNames({"message"})
public void printMessage(String message)
   {
    logger.info("I'm inside");
   }
}

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class Utils
{
    public static final Logger logger = getLogger(Utils.class);

    public static Logger getLogger(Class<?> clazz)
    Logger logger = Logger.getLogger(className.getClass());
    PropertyConfigurator.configure("/src/main/resources/log4j.properties");
    return logger;
}

log4j.properties :

log4j.rootLogger=DEBUG, Stdout, file
log4j.appender.Stdout=org.apache.log4j.ConsoleAppender
log4j.appender.Stdout.Target=System.out
log4j.appender.Stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.Stdout.layout.conversionPattern=%d %-5p [%t] %F:%L %m%n
log4j.appender.Stdout.ImmediateFlush=true
log4j.appender.Stdout.follow=true

With this setup i'm able to see log after test execution in robot framework test report but it would be very helpful if i can see logs during test execution as if i was calling log to console keyword.

is There a way to do this ?


问:
Bulk updating normalized Redux state
Let's say I have normalized state like this (using normalizr)

```<code>entities: {
  todos: {
    'aaa': {
      id: 'aaa',
      text: 'Todo A',
      completed: false
    },
    'bbb': {
      id: 'bbb',
      text: 'Todo B',
      completed: false
    },
    'ccc': {
      id: 'ccc',
      text: 'Todo C',
      completed: false
    }
  }
}
</code>```

Then I have an action that fetches array of IDs from the server, that are completed. For that action type, I have reducer like this:

```<code>const todos = (state = initialState, action) => {
  switch (action.type) {
    case ActionTypes.FETCH_COMPLETED_SUCCESS:
      return {
        ...state,
        todos: action.payload.completedIds.map((id) => {
          return {
            [id]: {
              ...state.todos[id],
              completed: true
            }
          }
        })
      };
    default:
      return state;
  }
};
</code>```

If I recieved an array with ['aaa', 'ccc'] (could be thousands of items in real world app), I want to set "completed" to TRUE on those respective todos in a single action, is it possible?

My current implementation of reducer doesn't work since it returns an array of objects, while original normalized state is object with IDs as key.

Thanks.

答:
You can try this:</p>

```<code> const todos = (state = initialState, action) => {
  switch (action.type) {
    case ActionTypes.FETCH_COMPLETED_SUCCESS:
      const newState = {};//New Object
      const filterKeys = Object.keys(state).filter( key=>{
        newState[key]=state[key]; //copy
        return completedIds.indexOf(key)!=-1;
      });
      filterKeys.forEach(key=> newState[key].completed = true);
       return newState;
    default:
      return state;
  }
};
</code>```

Title: Bulk updating normalized Redux state

Body:
Let's say I have normalized state like this (using normalizr)

entities: {
  todos: {
    'aaa': {
      id: 'aaa',
      text: 'Todo A',
      completed: false
    },
    'bbb': {
      id: 'bbb',
      text: 'Todo B',
      completed: false
    },
    'ccc': {
      id: 'ccc',
      text: 'Todo C',
      completed: false
    }
  }
}

Then I have an action that fetches array of IDs from the server, that are completed. For that action type, I have reducer like this:

const todos = (state = initialState, action) => {
  switch (action.type) {
    case ActionTypes.FETCH_COMPLETED_SUCCESS:
      return {
        ...state,
        todos: action.payload.completedIds.map((id) => {
          return {
            [id]: {
              ...state.todos[id],
              completed: true
            }
          }
        })
      };
    default:
      return state;
  }
};

If I recieved an array with ['aaa', 'ccc'] (could be thousands of items in real world app), I want to set "completed" to TRUE on those respective todos in a single action, is it possible?

My current implementation of reducer doesn't work since it returns an array of objects, while original normalized state is object with IDs as key.

Thanks.

Body:
You can try this:

 const todos = (state = initialState, action) => {
  switch (action.type) {
    case ActionTypes.FETCH_COMPLETED_SUCCESS:
      const newState = {};//New Object
      const filterKeys = Object.keys(state).filter( key=>{
        newState[key]=state[key]; //copy
        return completedIds.indexOf(key)!=-1;
      });
      filterKeys.forEach(key=> newState[key].completed = true);
       return newState;
    default:
      return state;
  }
};


问:
Get the length of a String
How do you get the length of a String? For example, I have a variable defined like:

```<code>var test1: String = "Scott"
</code>```

However, I can't seem to find a length method on the string.

答:
Swift 4

```<code>let str =  "Your name"

str.count
</code>```

Remember: Space is also counted in the number

Title: Get the length of a String

Body:
How do you get the length of a String? For example, I have a variable defined like:

var test1: String = "Scott"

However, I can't seem to find a length method on the string.

Body:
Swift 4

let str =  "Your name"

str.count

Remember: Space is also counted in the number


问:
printing bold, colored, etc., text in ipython qtconsole
I'm trying to get text to display as bold, or in colors, or possibly in italics, in ipython's qtconsole.

I found this link: How do I print bold text in Python?, and used the first and second answers, but in qtconsole, only the underlining option works.

I try:

print '\033[1m' + 'Hello World!' + '\033[0m'

And get:

Hello World!

(No boldface). The colors don't work either. But:

print '\033[4m' + 'Hello World!' + '\033[0m'

And get:

Hello World!

With underlining.

This is only in the qtconsole. Running ipython just in the terminal, it works to do boldface and color in this way.

There were other options suggested in that link and another, Print in terminal with colors using Python?, linked from it, but they all seem more complex, and to use more elaborate packages, than seems necessary for what I want to do, which is simply to get qtconsole to display like the ordinary terminal does.

Does anyone know what's going on? Is this simply a limitation of the qtconsole?

答:
I would like to complete the previous incomplete answer.
Way more complex and fun things can be done without importing additional packages. e.g.

```<code>print('\x1b[1;03;31;46m'+'Hello'+ '\x1b[0;4;30;42m' + ' world' '\x1b[0m')
</code>```

i.e.:

Open with:

```<code>'\x1b[XX;YY;ZZm'
</code>```

Close with:

```<code>'\x1b[0m'
</code>```

Where XX, YY and ZZ are numbers from:
https://en.wikipedia.org/wiki/ANSI_escape_code

It should be noted that it is very much dependant on what you use as a console to see what works.

Working for me are combinations of the following:

Text styling

1 Increased intensity (it operates on highlight and text simultaneously in my case)

3 Itallic

4 Underline

Text colors

30 Black text

31 Dark Red text

32 Dark Green text

33 Red text

34 Dark blue text

35 Purple text

36 Blue text

37 Gray text

Bright text colors

1;30 Gray text (Bright black)

1;31 Orange text (Bright red)

1;32 Bright Green text

1;33 Bright Yellow text

1;34 Bright Blue text

1;35 Bright Purple text

1;36 Bright Cyan text

1;37 White text (Bright
gray)

Background colors (i.e. highlights)

40 Black highlight

41 Dark Red highlight

42 Dark Green highlight

43 Red highlight

44 Dark blue highlight

45 Purple highlight

46 Blue highlight

47 Gray highlight

Note that 1;42 etc. also works similarly

Tested on windows 7, python 3.6, IPython console, in spyder 3.2.3 this works for me

Body:
I would like to complete the previous incomplete answer.
Way more complex and fun things can be done without importing additional packages. e.g.

print('\x1b[1;03;31;46m'+'Hello'+ '\x1b[0;4;30;42m' + ' world' '\x1b[0m')

i.e.:

Open with:

'\x1b[XX;YY;ZZm'

Close with:

'\x1b[0m'

Where XX, YY and ZZ are numbers from:
https://en.wikipedia.org/wiki/ANSI_escape_code

It should be noted that it is very much dependant on what you use as a console to see what works.

Working for me are combinations of the following:

Text styling

1 Increased intensity (it operates on highlight and text simultaneously in my case)

3 Itallic

4 Underline

Text colors

30 Black text

31 Dark Red text

32 Dark Green text

33 Red text

34 Dark blue text

35 Purple text

36 Blue text

37 Gray text

Bright text colors

1;30 Gray text (Bright black)

1;31 Orange text (Bright red)

1;32 Bright Green text

1;33 Bright Yellow text

1;34 Bright Blue text

1;35 Bright Purple text

1;36 Bright Cyan text

1;37 White text (Bright
gray)

Background colors (i.e. highlights)

40 Black highlight

41 Dark Red highlight

42 Dark Green highlight

43 Red highlight

44 Dark blue highlight

45 Purple highlight

46 Blue highlight

47 Gray highlight

Note that 1;42 etc. also works similarly

Tested on windows 7, python 3.6, IPython console, in spyder 3.2.3 this works for me


问:
How do I show and hide loader to show more posts?
How do I show the loader when a user clicks on load more posts button and more posts are loading and hide it after the posts have been loaded successfully. Then I want to again show the loader when user clicks on load more posts button

$("#lmb").click(function(e) {
  $('#lmi').show();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="lmb" type="button" style="background-color: #f44336;width:98%;border-radius:6px;border:2px solid #4a235a;">Load More Posts <img src="http://www.nvidia.com/docs/IO/151309/loader.gif" width="2%" height="2%" id="lmi" style="display:none;"></button></code>```

答:
I don't know how are the posts loaded but I suppose that when you click the button, you launch an AJAX request to the server and the server returns the posts... So you just need to hide the loader in the callback function.

JQuery:

```<code>$.ajax("where/I/get/posts.php", {
    method: get,
    //more options
    success: function(response) {
        //add posts
        $('#lmi').hide();
    }
}
</code>```

Body:
How do I show the loader when a user clicks on load more posts button and more posts are loading and hide it after the posts have been loaded successfully. Then I want to again show the loader when user clicks on load more posts button

$("#lmb").click(function(e) {
  $('#lmi').show();
});

<button id="lmb" type="button" style="background-color: #f44336;width:98%;border-radius:6px;border:2px solid #4a235a;">Load More Posts </button>

Body:
I don't know how are the posts loaded but I suppose that when you click the button, you launch an AJAX request to the server and the server returns the posts... So you just need to hide the loader in the callback function.

JQuery:

$.ajax("where/I/get/posts.php", {
    method: get,
    //more options
    success: function(response) {
        //add posts
        $('#lmi').hide();
    }
}


问:
Comprobating function not working as it should
I need to create a lottery game. I have an idea of how the whole code should be and it's mostly done, but I have a problem:

I have a button with an onclick called generar(), and this function, needs to draw 3 numbers from 1 to 999 and create along with the three numbers, another button which after pressing it, draws another number and then (the new button) checks the new number number with the ones who are already created to see if I won, or not.

Okay, I've managed to do the whole code, but the comparison of the three first numbers with the fourth number, doesn't work correctly. Always, the comprobation which says if I won or not, writes "¡Perdedor!" (looser!).

This is my code:

```<code><html>
    <head>
        <title>Práctica 3</title>
        <style>
            #contenedor { border: 1px black solid;
                    width: 250px;
                    height: 250px;
                    float: left;
                    margin-right: 5px;
                    text-align: center;
                    margin-bottom: 5px; }
        </style>
    </head>

    <body>
        <div id="contenedor"> <p id="primerNumero"/> </div>
        <div id="contenedor"> <p id="segundoNumero"/> </div>
        <div id="contenedor"> <p id="tercerNumero"/> </div>
        <button id="generar" onclick="generar()">Genera dècims</button>
        <div id="contenedor"> <p id="resultado"/> </div>
        <p id="t"/>

    <script>
        function generar() {
            var primerNumero = Math.floor(Math.random() * 10);
            var segundoNumero = Math.floor(Math.random() * 10);
            var tercerNumero = Math.floor(Math.random() * 10);
            var botones = document.getElementsByTagName("BUTTON").length;

            if (botones < 2) {
                generarBotones();
            }

            document.getElementById("primerNumero").innerHTML = primerNumero;
            document.getElementById("primerNumero").style.fontSize = "72px";
            document.getElementById("segundoNumero").innerHTML = segundoNumero;
            document.getElementById("segundoNumero").style.fontSize = "72px";
            document.getElementById("tercerNumero").innerHTML = tercerNumero;
            document.getElementById("tercerNumero").style.fontSize = "72px";
        }

        function generarBotones() {
                var boton = document.createElement("BUTTON");
                var t = document.createTextNode("Realizar sorteig");
                boton.onclick = function(){
                    var numeroGanador = Math.floor(Math.random() * 10);
                    document.getElementById("resultado").innerHTML = numeroGanador;
                    document.getElementById("resultado").style.fontSize = "72px";
                    if(primerNumero == numeroGanador || segundoNumero == numeroGanador || tercerNumero == numeroGanador) {
                        document.getElementById("t").innerHTML = "¡Ganador!";
                    } else {
                        document.getElementById("t").innerHTML = "¡Perdedor!";
                    }
                };
                boton.appendChild(t);
                document.body.appendChild(boton);
        }
    </script>

    </body>
</html>
</code>```

If somebody can tell me why and where I fail and a possible solution, it will be great. I will very grateful if an explanation is given too

答:
```<code>primerNumero
segundoNumero
tercerNumero
</code>```

Are html elements, not value, to get the value is necessary to use innerText OR innerHTML.

```<code>if(primerNumero.innerText == numeroGanador || segundoNumero.innerText == numeroGanador || tercerNumero.innerText == numeroGanador) {
    document.getElementById("t").innerHTML = "¡Ganador!";
} else {
    document.getElementById("t").innerHTML = "¡Perdedor!";
}
</code>```

Or you can rename the variables to a different name of the element, because your problem is that the variables that contain the generated numbers are the same name as the id of the html element. If rename will work according to your first code.

Body:
I need to create a lottery game. I have an idea of how the whole code should be and it's mostly done, but I have a problem:

I have a button with an onclick called generar(), and this function, needs to draw 3 numbers from 1 to 999 and create along with the three numbers, another button which after pressing it, draws another number and then (the new button) checks the new number number with the ones who are already created to see if I won, or not.

Okay, I've managed to do the whole code, but the comparison of the three first numbers with the fourth number, doesn't work correctly. Always, the comprobation which says if I won or not, writes "¡Perdedor!" (looser!).

This is my code:

        <title>Práctica 3</title>

        <button id="generar" onclick="generar()">Genera dècims</button>

If somebody can tell me why and where I fail and a possible solution, it will be great. I will very grateful if an explanation is given too

Body:
primerNumero
segundoNumero
tercerNumero

Are html elements, not value, to get the value is necessary to use innerText OR innerHTML.

if(primerNumero.innerText == numeroGanador || segundoNumero.innerText == numeroGanador || tercerNumero.innerText == numeroGanador) {
    document.getElementById("t").innerHTML = "¡Ganador!";
} else {
    document.getElementById("t").innerHTML = "¡Perdedor!";
}

Or you can rename the variables to a different name of the element, because your problem is that the variables that contain the generated numbers are the same name as the id of the html element. If rename will work according to your first code.


问:
Using map() on an iterator
Say we have a Map: let m = new Map();, using m.values() returns a map iterator.

But I can't use forEach() or map() on that iterator and implementing a while loop on that iterator seems like an anti-pattern since ES6 offer functions like map().

So is there a way to use map() on an iterator?

答:
You could define another iterator function to loop over this:

function* generator() {
    for (let i = 0; i < 10; i++) {
        console.log(i);
        yield i;
    }
}

function* mapIterator(iterator, mapping) {
    for (let i of iterator) {
        yield mapping(i);
    }
}

let values = generator();
let mapped = mapIterator(values, (i) => {
    let result = i*2;
    console.log(`x2 = ${result}`);
    return result;
});

console.log('The values will be generated right now.');
console.log(Array.from(mapped).join(','));```

Now you might ask: why not just use Array.from instead? Because this will run through the entire iterator, save it to a (temporary) array, iterate it again and then do the mapping. If the list is huge (or even potentially infinite) this will lead to unnecessary memory usage.

Of course, if the list of items is fairly small, using Array.from should be more than sufficient.

Title: Using map() on an iterator

Body:
You could define another iterator function to loop over this:

function* generator() {
    for (let i = 0; i < 10; i++) {
        console.log(i);
        yield i;
    }
}

function* mapIterator(iterator, mapping) {
    for (let i of iterator) {
        yield mapping(i);
    }
}

let values = generator();
let mapped = mapIterator(values, (i) => {
    let result = i*2;
    console.log(`x2 = ${result}`);
    return result;
});

console.log('The values will be generated right now.');
console.log(Array.from(mapped).join(','));

Now you might ask: why not just use Array.from instead? Because this will run through the entire iterator, save it to a (temporary) array, iterate it again and then do the mapping. If the list is huge (or even potentially infinite) this will lead to unnecessary memory usage.

Of course, if the list of items is fairly small, using Array.from should be more than sufficient.


问:
TfsTeamProjectCollection get service returns null for WorkItemStore
I am experiencing a problem with getting work items from TFS server.
I have installed Microsoft.TeamFoundation.Client, Microsoft.TeamFoundation.WorkItemTracking.Client and Microsoft.TeamFoundationServer.ExtendedClient

I have Windows form application with following method:

```<code>TfsConfigurationServer configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(tfsUri);
CatalogNode collectionNode = configurationServer.CatalogNode.QueryChildren(new[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None).FirstOrDefault();
Guid collectionId = new Guid(collectionNode.Resource.Properties["InstanceId"]);
TfsTeamProjectCollection teamProjectCollection = configurationServer.GetTeamProjectCollection(collectionId);
var workItemStore = (WorkItemStore)teamProjectCollection.GetService(typeof(WorkItemStore));
</code>```

All results before teamProjectCollection.GetService looks ok, however workItemStore is always null. Any ideas why i'm not getting service back?

I'm running Visual Studio 2015 on Win 10 x64.. Maybe it is to do with that?

UPDATED:
I found out this error

Reference to type 'Team Foundation Server' claims it is defined in 'Microsoft.TeamFoundation.Client', but it could not be found

答:
Did you add references to individual libraries? Add the nuget package

Microsoft.TeamFoundationServer.ExtendedClient

It would add all dependent packages you need. I tried your code with the following package and it worked fine

```<code><package id="Microsoft.TeamFoundationServer.ExtendedClient" version="15.112.1" targetFramework="net452" />
</code>```

Body:
I am experiencing a problem with getting work items from TFS server.
I have installed Microsoft.TeamFoundation.Client, Microsoft.TeamFoundation.WorkItemTracking.Client and Microsoft.TeamFoundationServer.ExtendedClient

I have Windows form application with following method:

TfsConfigurationServer configurationServer = TfsConfigurationServerFactory.GetConfigurationServer(tfsUri);
CatalogNode collectionNode = configurationServer.CatalogNode.QueryChildren(new[] { CatalogResourceTypes.ProjectCollection }, false, CatalogQueryOptions.None).FirstOrDefault();
Guid collectionId = new Guid(collectionNode.Resource.Properties["InstanceId"]);
TfsTeamProjectCollection teamProjectCollection = configurationServer.GetTeamProjectCollection(collectionId);
var workItemStore = (WorkItemStore)teamProjectCollection.GetService(typeof(WorkItemStore));

All results before teamProjectCollection.GetService looks ok, however workItemStore is always null. Any ideas why i'm not getting service back?

I'm running Visual Studio 2015 on Win 10 x64.. Maybe it is to do with that?

UPDATED:
I found out this error

Reference to type 'Team Foundation Server' claims it is defined in 'Microsoft.TeamFoundation.Client', but it could not be found

Body:
Did you add references to individual libraries? Add the nuget package

Microsoft.TeamFoundationServer.ExtendedClient

It would add all dependent packages you need. I tried your code with the following package and it worked fine

<package id="Microsoft.TeamFoundationServer.ExtendedClient" version="15.112.1" targetFramework="net452" />


问:
Keyword matching involving integers without leading zeros using sed and awk
Assume a multi-line textfile (file1) that contains one keyword per line, where each keyword has the format StringInteger. The order of the lines is fixed.

```<code>$cat file1
foo1
foo2
foo4
foo10
</code>```

Assume further a multi-line textfile (file2) whose lines contain several whitespace-delimited words, one of which may be one of the above-mentioned keywords. Every line can only contain one keyword, and the keyword may be located anywhere within the line, except as the last word. If a keyword exists in the line, then the term baz=() also exists in the line. The order of the lines is not fixed.

```<code>$cat file2
foo1 bar baz=()
bar foo4 baz=()
foo10 qux baz=()
foo2 baz=()
</code>```

If a line in file2 contains keyword n, I want to add the line number that keyword n has in file1 in the term baz=().

```<code>$sought_commands file1 file2
foo1 bar baz=(1)
bar foo4 baz=(3)
foo10 qux baz=(4)
foo2 baz=(2)
</code>```

I came up with the following code, which has the flaw that keyword foo1 masks the term baz=() for keyword foo10:

```<code>for kw in $(cat file1); do
    lineNumbr=$(cat file1 | awk '/'$kw'/{print NR; exit}')
    sed -i "/$kw/ s/baz\=()/baz\=($lineNumbr)/" file2
done
</code>```

.

```<code>$cat file2
foo1 bar baz=(1)
bar foo4 baz=(3)
foo10 qux baz=(1) # ERROR!
foo2 baz=(2)
</code>```

Edit 1: I considered using the circumstance that the keywords are always followed by a whitespace in file2 as a delimiter, but then the awk-command fails:

```<code>for kw in $(cat file1); do
    kw_adj="$kw "
    lineNumbr=$(cat file1 | awk '/'$kw_adj'/{print NR; exit}')
    sed -i "/$kw_adj/ s/baz\=()/baz\=($lineNumbr)/" file2
done

awk: cmd. line:1: /foo1
awk: cmd. line:1:  ^ unterminated regexp
awk: cmd. line:1: /foo2
awk: cmd. line:1:  ^ unterminated regexp
awk: cmd. line:1: /foo4
awk: cmd. line:1:  ^ unterminated regexp
awk: cmd. line:1: /foo10
awk: cmd. line:1:  ^ unterminated regexp
</code>```

答:
The problem is here:

```<code>sed -i "/$kw/ s/baz\=()/baz\=($lineNumbr)/" file2
</code>```

When the value of kw is "foo1", the pattern /$kw/ matches "foo10" as well, replacing foo10 qux baz=() with foo10 qux baz=(). Once this is written to the file, baz=() will no longer exist, so when the "foo10" pattern is applied from the input, it will have nothing to replace.

Change that line like this:

```<code>sed -i "/\<$kw\>/ s/baz\=()/baz\=($lineNumbr)/" file2
</code>```

The \<...\> makes a pattern match word boundaries.
This way "foo10" will not be matched by /\<foo1\>/, only the complete word "foo1".

Also, the lineNumbr=$(...) inside the loop is silly,
when you can already know the line number using simple counting:

```<code>lineNumbr=1
for kw in $(cat file1); do
    sed -i "/\<$kw\>/ s/baz\=()/baz\=($lineNumbr)/" file2
    ((lineNumbr++))
done
</code>```

Body:
Assume a multi-line textfile (file1) that contains one keyword per line, where each keyword has the format StringInteger. The order of the lines is fixed.

$cat file1
foo1
foo2
foo4
foo10

Assume further a multi-line textfile (file2) whose lines contain several whitespace-delimited words, one of which may be one of the above-mentioned keywords. Every line can only contain one keyword, and the keyword may be located anywhere within the line, except as the last word. If a keyword exists in the line, then the term baz=() also exists in the line. The order of the lines is not fixed.

$cat file2
foo1 bar baz=()
bar foo4 baz=()
foo10 qux baz=()
foo2 baz=()

If a line in file2 contains keyword n, I want to add the line number that keyword n has in file1 in the term baz=().

$sought_commands file1 file2
foo1 bar baz=(1)
bar foo4 baz=(3)
foo10 qux baz=(4)
foo2 baz=(2)

I came up with the following code, which has the flaw that keyword foo1 masks the term baz=() for keyword foo10:

for kw in $(cat file1); do
    lineNumbr=$(cat file1 | awk '/'$kw'/{print NR; exit}')
    sed -i "/$kw/ s/baz\=()/baz\=($lineNumbr)/" file2
done

.

$cat file2
foo1 bar baz=(1)
bar foo4 baz=(3)
foo10 qux baz=(1) # ERROR!
foo2 baz=(2)

Edit 1: I considered using the circumstance that the keywords are always followed by a whitespace in file2 as a delimiter, but then the awk-command fails:

for kw in $(cat file1); do
    kw_adj="$kw "
    lineNumbr=$(cat file1 | awk '/'$kw_adj'/{print NR; exit}')
    sed -i "/$kw_adj/ s/baz\=()/baz\=($lineNumbr)/" file2
done

awk: cmd. line:1: /foo1
awk: cmd. line:1:  ^ unterminated regexp
awk: cmd. line:1: /foo2
awk: cmd. line:1:  ^ unterminated regexp
awk: cmd. line:1: /foo4
awk: cmd. line:1:  ^ unterminated regexp
awk: cmd. line:1: /foo10
awk: cmd. line:1:  ^ unterminated regexp

Body:
The problem is here:

sed -i "/$kw/ s/baz\=()/baz\=($lineNumbr)/" file2

When the value of kw is "foo1", the pattern /$kw/ matches "foo10" as well, replacing foo10 qux baz=() with foo10 qux baz=(). Once this is written to the file, baz=() will no longer exist, so when the "foo10" pattern is applied from the input, it will have nothing to replace.

Change that line like this:

sed -i "/\<$kw\>/ s/baz\=()/baz\=($lineNumbr)/" file2

The \<...\> makes a pattern match word boundaries.
This way "foo10" will not be matched by /\<foo1\>/, only the complete word "foo1".

Also, the lineNumbr=$(...) inside the loop is silly,
when you can already know the line number using simple counting:

lineNumbr=1
for kw in $(cat file1); do
    sed -i "/\<$kw\>/ s/baz\=()/baz\=($lineNumbr)/" file2
    ((lineNumbr++))
done


问:
PyModbus.server port 502 not open StartTcpServer
I am setting up a Modbus TCP server on my Linux PC.
When i run the code below the port 502 is not open on my computer, when i check with nmap.

Anyone have experience with this?

https://pymodbus.readthedocs.io/en/latest/examples/synchronous-server.html

```<code>from pymodbus.server.async import StartTcpServer

from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore import ModbusSequentialDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext

store = ModbusSlaveContext(
    di = ModbusSequentialDataBlock(0, [17]*100),
    co = ModbusSequentialDataBlock(0, [17]*100),
    hr = ModbusSequentialDataBlock(0, [17]*100),
    ir = ModbusSequentialDataBlock(0, [17]*100))
context = ModbusServerContext(slaves=store, single=True)

    #---------------------------------------------------------------------------#
# initialize the server information
#---------------------------------------------------------------------------#
# If you don't set this or any fields, they are defaulted to empty strings.
    #---------------------------------------------------------------------------#
identity = ModbusDeviceIdentification()
identity.VendorName  = 'Pymodbus'
identity.ProductCode = 'PM'
identity.VendorUrl   = 'http://github.com/riptideio/pymodbus/'
identity.ProductName = 'Pymodbus Server'
identity.ModelName   = 'Pymodbus Server'
identity.MajorMinorRevision = '1.0'

    #---------------------------------------------------------------------------#
# run the server you want
    #---------------------------------------------------------------------------#
# Tcp:
StartTcpServer(context, identity=identity, address=('localhost', 502))
</code>```

Edit:
If i connect to the server with a client on the same computer, the server is working. If i close the server the client responds with port 502 closed.

答:
The 'localhost' string you give as the server's listening address in this call:

```<code>StartTcpServer(context, identity=identity, address=('localhost', 502))
</code>```

tells your server to listen for connections only from clients running on the same system as the server.  If you want your server to accept connections from other systems then pass an empty string '' as the address instead of 'localhost'.  The empty string tells the server to listen on all of this system's interfaces.

Body:
I am setting up a Modbus TCP server on my Linux PC.
When i run the code below the port 502 is not open on my computer, when i check with nmap.

Anyone have experience with this?

https://pymodbus.readthedocs.io/en/latest/examples/synchronous-server.html

from pymodbus.server.async import StartTcpServer

from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore import ModbusSequentialDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext

store = ModbusSlaveContext(
    di = ModbusSequentialDataBlock(0, [17]*100),
    co = ModbusSequentialDataBlock(0, [17]*100),
    hr = ModbusSequentialDataBlock(0, [17]*100),
    ir = ModbusSequentialDataBlock(0, [17]*100))
context = ModbusServerContext(slaves=store, single=True)

    #---------------------------------------------------------------------------#
# initialize the server information
#---------------------------------------------------------------------------#
# If you don't set this or any fields, they are defaulted to empty strings.
    #---------------------------------------------------------------------------#
identity = ModbusDeviceIdentification()
identity.VendorName  = 'Pymodbus'
identity.ProductCode = 'PM'
identity.VendorUrl   = 'http://github.com/riptideio/pymodbus/'
identity.ProductName = 'Pymodbus Server'
identity.ModelName   = 'Pymodbus Server'
identity.MajorMinorRevision = '1.0'

    #---------------------------------------------------------------------------#
# run the server you want
    #---------------------------------------------------------------------------#
# Tcp:
StartTcpServer(context, identity=identity, address=('localhost', 502))

Edit:
If i connect to the server with a client on the same computer, the server is working. If i close the server the client responds with port 502 closed.

Body:
The 'localhost' string you give as the server's listening address in this call:

StartTcpServer(context, identity=identity, address=('localhost', 502))

tells your server to listen for connections only from clients running on the same system as the server.  If you want your server to accept connections from other systems then pass an empty string '' as the address instead of 'localhost'.  The empty string tells the server to listen on all of this system's interfaces.


问:
Uncaught ReferenceError: Popper is not defined - with Bootstrap 4 and Webpack 3.8.1
I am using the Visual Studio 2017 Angular template with .NET Core 2.0. The template has numerous older dependencies which I have updated, including to Angular 5.0.0. Running the vanilla template with Bootstrap 3.x.x works. However, using Bootstrap 4.0.0-beta.2 results in the following error:

Uncaught ReferenceError: Popper is not defined

I have followed the instructions here to the best of my ability:

http://getbootstrap.com/docs/4.0/getting-started/webpack/

I have looked at this issue:

Bootstrap 4: Uncaught ReferenceError: Popper is not defined

Per the solutions listed there, I have to to either register popper before bootstrap or to use the min version of boostrap since it comes with popper already. However, I am using webpack 2.5.1 (which I am just now learning) and I don't know how to implement either of those solutions in the webpack.config.js file which was provided as part of the template and includes the modification called out by the boostrap-webpack docs.

webpack.config.js

```<code>const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AotPlugin = require('@ngtools/webpack').AotPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;

module.exports = (env) => {
    // Configuration in common to both client-side and server-side bundles
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        stats: { modules: false },
        context: __dirname,
        resolve: { extensions: ['.js', '.ts'] },
        output: {
            filename: '[name].js',
            publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
        },
        module: {
            rules: [
                { test: /\.ts$/, include: /ClientApp/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader'] : '@ngtools/webpack' },
                { test: /\.html$/, use: 'html-loader?minimize=false' },
                { test: /\.css$/, use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize'] },
                { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
            ]
        },
        plugins: [new CheckerPlugin()]
    };

    // Configuration for client-side bundle suitable for running in browsers
    const clientBundleOutputDir = './wwwroot/dist';
    const clientBundleConfig = merge(sharedConfig, {
        entry: { 'main-client': './ClientApp/boot.browser.ts' },
        output: { path: path.join(__dirname, clientBundleOutputDir) },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./wwwroot/dist/vendor-manifest.json')
            }),
            new webpack.ProvidePlugin({
                $: 'jquery',
                jQuery: 'jquery',
                'window.jQuery': 'jquery',
                Popper: ['popper.js', 'default'],
                // In case you imported plugins individually, you must also require them here:
                //Util: "exports-loader?Util!bootstrap/js/dist/util",
                //Dropdown: "exports-loader?Dropdown!bootstrap/js/dist/dropdown"
            })
        ].concat(isDevBuild ? [
            // Plugins that apply in development builds only
            new webpack.SourceMapDevToolPlugin({
                filename: '[file].map', // Remove this line if you prefer inline source maps
                moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
            })
        ] : [
                // Plugins that apply in production builds only
                new webpack.optimize.UglifyJsPlugin(),
                new AotPlugin({
                    tsConfigPath: './tsconfig.json',
                    entryModule: path.join(__dirname, 'ClientApp/app/app.module.browser#AppModule'),
                    exclude: ['./**/*.server.ts']
                })
            ])
    });

    // Configuration for server-side (prerendering) bundle suitable for running in Node
    const serverBundleConfig = merge(sharedConfig, {
        resolve: { mainFields: ['main'] },
        entry: { 'main-server': './ClientApp/boot.server.ts' },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./ClientApp/dist/vendor-manifest.json'),
                sourceType: 'commonjs2',
                name: './vendor'
            })
        ].concat(isDevBuild ? [] : [
            // Plugins that apply in production builds only
            new AotPlugin({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.module.server#AppModule'),
                exclude: ['./**/*.browser.ts']
            })
        ]),
        output: {
            libraryTarget: 'commonjs',
            path: path.join(__dirname, './ClientApp/dist')
        },
        target: 'node',
        devtool: 'inline-source-map'
    });

    return [clientBundleConfig, serverBundleConfig];
};
</code>```

Also, here is the main entry point file boot.browser.ts provided as part of the template:

```<code>import 'reflect-metadata';
import 'zone.js';
import 'bootstrap';
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module.browser';

if (module.hot) {
    module.hot.accept();
    module.hot.dispose(() => {
        // Before restarting the app, we create a new root element and dispose the old one
        const oldRootElem = document.querySelector('app');
        const newRootElem = document.createElement('app');
        oldRootElem!.parentNode!.insertBefore(newRootElem, oldRootElem);
        modulePromise.then(appModule => appModule.destroy());
    });
} else {
    enableProdMode();
}

// Note: @ng-tools/webpack looks for the following expression when performing production
// builds. Don't change how this line looks, otherwise you may break tree-shaking.
const modulePromise = platformBrowserDynamic().bootstrapModule(AppModule);
</code>```

答:
I finally found out how to get past the error. I used the following lines in the main entry point boot.browser.ts file:

```<code>import * as $ from 'jquery';

//These two lines didn't remove the error
//import Popper from 'popper.js';
//import 'bootstrap';

//This one did remove the error. The bundle version of bootstrap includes popper in the correct order (according to the docs)
import 'bootstrap/dist/js/bootstrap.bundle.js';
</code>```

Interestingly, the suggested code at the bootstrap github (https://github.com/twbs/bootstrap/issues/24648) was to use this line for the jquery import:

```<code>import $ from 'jquery'
</code>```

instead of

```<code>import * as $ from 'jquery'
</code>```

but the former caused this error:

Could not find a declaration file for module 'jquery'

However, I have no idea what the difference is between the two lines

Body:
I am using the Visual Studio 2017 Angular template with .NET Core 2.0. The template has numerous older dependencies which I have updated, including to Angular 5.0.0. Running the vanilla template with Bootstrap 3.x.x works. However, using Bootstrap 4.0.0-beta.2 results in the following error:

Uncaught ReferenceError: Popper is not defined

I have followed the instructions here to the best of my ability:

http://getbootstrap.com/docs/4.0/getting-started/webpack/

I have looked at this issue:

Bootstrap 4: Uncaught ReferenceError: Popper is not defined

Per the solutions listed there, I have to to either register popper before bootstrap or to use the min version of boostrap since it comes with popper already. However, I am using webpack 2.5.1 (which I am just now learning) and I don't know how to implement either of those solutions in the webpack.config.js file which was provided as part of the template and includes the modification called out by the boostrap-webpack docs.

webpack.config.js

const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const AotPlugin = require('@ngtools/webpack').AotPlugin;
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;

module.exports = (env) => {
    // Configuration in common to both client-side and server-side bundles
    const isDevBuild = !(env && env.prod);
    const sharedConfig = {
        stats: { modules: false },
        context: __dirname,
        resolve: { extensions: ['.js', '.ts'] },
        output: {
            filename: '[name].js',
            publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
        },
        module: {
            rules: [
                { test: /\.ts$/, include: /ClientApp/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader'] : '@ngtools/webpack' },
                { test: /\.html$/, use: 'html-loader?minimize=false' },
                { test: /\.css$/, use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize'] },
                { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
            ]
        },
        plugins: [new CheckerPlugin()]
    };

    // Configuration for client-side bundle suitable for running in browsers
    const clientBundleOutputDir = './wwwroot/dist';
    const clientBundleConfig = merge(sharedConfig, {
        entry: { 'main-client': './ClientApp/boot.browser.ts' },
        output: { path: path.join(__dirname, clientBundleOutputDir) },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./wwwroot/dist/vendor-manifest.json')
            }),
            new webpack.ProvidePlugin({
                $: 'jquery',
                jQuery: 'jquery',
                'window.jQuery': 'jquery',
                Popper: ['popper.js', 'default'],
                // In case you imported plugins individually, you must also require them here:
                //Util: "exports-loader?Util!bootstrap/js/dist/util",
                //Dropdown: "exports-loader?Dropdown!bootstrap/js/dist/dropdown"
            })
        ].concat(isDevBuild ? [
            // Plugins that apply in development builds only
            new webpack.SourceMapDevToolPlugin({
                filename: '[file].map', // Remove this line if you prefer inline source maps
                moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
            })
        ] : [
                // Plugins that apply in production builds only
                new webpack.optimize.UglifyJsPlugin(),
                new AotPlugin({
                    tsConfigPath: './tsconfig.json',
                    entryModule: path.join(__dirname, 'ClientApp/app/app.module.browser#AppModule'),
                    exclude: ['./**/*.server.ts']
                })
            ])
    });

    // Configuration for server-side (prerendering) bundle suitable for running in Node
    const serverBundleConfig = merge(sharedConfig, {
        resolve: { mainFields: ['main'] },
        entry: { 'main-server': './ClientApp/boot.server.ts' },
        plugins: [
            new webpack.DllReferencePlugin({
                context: __dirname,
                manifest: require('./ClientApp/dist/vendor-manifest.json'),
                sourceType: 'commonjs2',
                name: './vendor'
            })
        ].concat(isDevBuild ? [] : [
            // Plugins that apply in production builds only
            new AotPlugin({
                tsConfigPath: './tsconfig.json',
                entryModule: path.join(__dirname, 'ClientApp/app/app.module.server#AppModule'),
                exclude: ['./**/*.browser.ts']
            })
        ]),
        output: {
            libraryTarget: 'commonjs',
            path: path.join(__dirname, './ClientApp/dist')
        },
        target: 'node',
        devtool: 'inline-source-map'
    });

    return [clientBundleConfig, serverBundleConfig];
};

Also, here is the main entry point file boot.browser.ts provided as part of the template:

import 'reflect-metadata';
import 'zone.js';
import 'bootstrap';
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module.browser';

if (module.hot) {
    module.hot.accept();
    module.hot.dispose(() => {
        // Before restarting the app, we create a new root element and dispose the old one
        const oldRootElem = document.querySelector('app');
        const newRootElem = document.createElement('app');
        oldRootElem!.parentNode!.insertBefore(newRootElem, oldRootElem);
        modulePromise.then(appModule => appModule.destroy());
    });
} else {
    enableProdMode();
}

// Note: @ng-tools/webpack looks for the following expression when performing production
// builds. Don't change how this line looks, otherwise you may break tree-shaking.
const modulePromise = platformBrowserDynamic().bootstrapModule(AppModule);

Body:
I finally found out how to get past the error. I used the following lines in the main entry point boot.browser.ts file:

import * as $ from 'jquery';

//These two lines didn't remove the error
//import Popper from 'popper.js';
//import 'bootstrap';

//This one did remove the error. The bundle version of bootstrap includes popper in the correct order (according to the docs)
import 'bootstrap/dist/js/bootstrap.bundle.js';

Interestingly, the suggested code at the bootstrap github (https://github.com/twbs/bootstrap/issues/24648) was to use this line for the jquery import:

import $ from 'jquery'

instead of

import * as $ from 'jquery'

but the former caused this error:

Could not find a declaration file for module 'jquery'

However, I have no idea what the difference is between the two lines


问:
Django model DateField: How to ensure a two-digit year is saved as "19xx"?
I have a form that takes a user's birthdate. By default, Django accepts three input formats for dates, including MM/DD/YY. However if I enter something like 02/13/45, it saves as 02/13/2045. I've looked through the places I expected to find some threads in the docs but still nothing. Can someone push me in the right direction?</p>

答:
DateField just uses the datetime.strptime method, which in turn uses the underlying C strftime implementation; there's no way to change the way it parses a two-digit year. As mentioned in the comment, probably the best way to do this is to check if it's in the future, then subtract 100.

```<code>def clean_birthdate(self):
    birthdate = self.cleaned_data('birthdate')
    if birthdate > datetime.datetime.today():
        birthdate = birthdate.replace(year=(birthdate.year-100))
    return birthdate
</code>```

Body:
DateField just uses the datetime.strptime method, which in turn uses the underlying C strftime implementation; there's no way to change the way it parses a two-digit year. As mentioned in the comment, probably the best way to do this is to check if it's in the future, then subtract 100.

def clean_birthdate(self):
    birthdate = self.cleaned_data('birthdate')
    if birthdate > datetime.datetime.today():
        birthdate = birthdate.replace(year=(birthdate.year-100))
    return birthdate


问:
Is there a way to have two values from one variable/constant in Swift?
I currently have to make a school project where I have to write into a textfield a food and the values of the price and calories must appear to the user. Is there a way to have a variable or better yet, a constant have more than one value? Thanks</p>

答:
You can use Tuples to save several values for one variable. A tuple can hold values with different types.

Here an example:

```<code>let lasagne = (1200, 5.50)
print("The lasagne has \(lasagne.0) kCal and costs \(lasagne.1)$")
</code>```

you can also name the inner elements and then access them by their name:

```<code>let pizza = (calories: 900, price: 4)
print("The pizza has \(pizza.calories) kCal and costs \(pizza.price)$")
</code>```

Body:
You can use Tuples to save several values for one variable. A tuple can hold values with different types.

Here an example:

let lasagne = (1200, 5.50)
print("The lasagne has \(lasagne.0) kCal and costs \(lasagne.1)$")

you can also name the inner elements and then access them by their name:

let pizza = (calories: 900, price: 4)
print("The pizza has \(pizza.calories) kCal and costs \(pizza.price)$")


问:
How to parse JSON string to struct
I have struct of Request, value is optional:

```<code>type Request struct {
    Operation string      `json:"operation"`
    Key string            `json:"key"`
    Value string          `json:"value"`
}
</code>```

And function that should parse json string to struct^

```<code>go func() {
    s := string("{'operation': 'get', 'key': 'example'}")
    data := Request{}
    json.Unmarshal([]byte(s), data)
    log.Printf("Operation: %s", data.Operation)
}
</code>```

For some reason data.Operation is empty. What is wrong here?

答:
Two problems, first, your json is invalid, it needs to use " instead of '

Second, you have to unmarshal into &data and not to data

https://play.golang.org/p/zdMq5_ex8G

```<code>package main

import (
    "fmt"
    "encoding/json"
)

type Request struct {
    Operation string      `json:"operation"`
    Key string            `json:"key"`
    Value string          `json:"value"`
}

func main() {
    s := string(`{"operation": "get", "key": "example"}`)
    data := Request{}
    json.Unmarshal([]byte(s), &data)
    fmt.Printf("Operation: %s", data.Operation)
}
</code>```

Side note, you would have seen this, if you would have been checking your errors:

```<code>s := string("{'operation': 'get', 'key': 'example'}")

err := json.Unmarshal([]byte(s), data)
if err != nil {
    fmt.Println(err.Error())
    //json: Unmarshal(non-pointer main.Request)
}

err := json.Unmarshal([]byte(s), &data)
if err != nil {
    fmt.Println(err.Error())
    //invalid character '\'' looking for beginning of object key string
}
</code>```

Title: How to parse JSON string to struct

Body:
I have struct of Request, value is optional:

type Request struct {
    Operation string      `json:"operation"`
    Key string            `json:"key"`
    Value string          `json:"value"`
}

And function that should parse json string to struct^

go func() {
    s := string("{'operation': 'get', 'key': 'example'}")
    data := Request{}
    json.Unmarshal([]byte(s), data)
    log.Printf("Operation: %s", data.Operation)
}

For some reason data.Operation is empty. What is wrong here?

Body:
Two problems, first, your json is invalid, it needs to use " instead of '

Second, you have to unmarshal into &data and not to data

https://play.golang.org/p/zdMq5_ex8G

package main

import (
    "fmt"
    "encoding/json"
)

type Request struct {
    Operation string      `json:"operation"`
    Key string            `json:"key"`
    Value string          `json:"value"`
}

func main() {
    s := string(`{"operation": "get", "key": "example"}`)
    data := Request{}
    json.Unmarshal([]byte(s), &data)
    fmt.Printf("Operation: %s", data.Operation)
}

Side note, you would have seen this, if you would have been checking your errors:

s := string("{'operation': 'get', 'key': 'example'}")

err := json.Unmarshal([]byte(s), data)
if err != nil {
    fmt.Println(err.Error())
    //json: Unmarshal(non-pointer main.Request)
}

err := json.Unmarshal([]byte(s), &data)
if err != nil {
    fmt.Println(err.Error())
    //invalid character '\'' looking for beginning of object key string
}


问:
Backslash in URL causes 404 error
I have a search form on the page and I use GET method to send data to the server, but when I type backslash and click search, I see a 404 error. It is for "\" in URL. How can I prevent it?

```<code>http://127.0.0.1:8080/SelfArea/wpzf/public/\
</code>```

Apache server configuration htaccess file:

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
</code>```

Windows 7, WAMP Server.

答:
There are 2 step to load the page when routing error occurred in laravel :-

Add index.php in url the localhost/project_name/index.php/page_name

Edit apache2.conf  from etc/apache2 Do following :-

<Directory /usr/share>

```<code>`AllowOverride All`

`Require all granted`
</code>```

</Directory>

```<code> <Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>`
</code>```

It will work fine handle all routing error.

Title: Backslash in URL causes 404 error

Body:
I have a search form on the page and I use GET method to send data to the server, but when I type backslash and click search, I see a 404 error. It is for "\" in URL. How can I prevent it?

http://127.0.0.1:8080/SelfArea/wpzf/public/\

Apache server configuration htaccess file:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

Windows 7, WAMP Server.

Body:
There are 2 step to load the page when routing error occurred in laravel :-

Add index.php in url the localhost/project_name/index.php/page_name

Edit apache2.conf  from etc/apache2 Do following :-

<Directory /usr/share>

`AllowOverride All`

`Require all granted`

</Directory>

 <Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>`

It will work fine handle all routing error.


答:
With that many models, the session factory gets really expensive to build. The common workaround is to cache the configuration to a file.

IIRC ConfORM doesn't use XML/HBM config so it might be faster than NHibernate/XML or Fluent NHibernate in these scenarios.

Title: How well does NHibernate handle large models (about 1000 tables)?

Body:
I have seen a few discussions about how well Entity Framework works with large models - most prominently that question.

But I haven't been able to find any substantial information about how well NHibernate handles large models - what are the difficulties, and are they not too hard to work around?


问:
Python kmeans clustering for large datasets
I need to use bag of words (in this case bag of features) to generate descriptor vectors to classify the KTH video dataset. In order to do this, I need to use kmeans clustering algorithm to cluster the extracted features and find the codebook. The extracted features from dataset form approximately 75000 vectors of 100 elements each. So I'm facing memory issues using the scipy.cluster.kmeans2 implementation in Ubuntu. I runed some tests and discovered that with 32000 vector with 100 elements each, the amount of memory used is around 20GB (my total memory is 32GB).

Is there any other Python kmeans implementation more memory effcient?
I already read about Mahout for clustering big data, but I still not understand what is his advantages, is it more memory-efficient with that mentioned amount of data?

答:
When having many samples, consider using sklearn's MiniBatchKMeans, which is a SGD-like method build for this case! (A more tutorial-like intro which does not address memory-usage, but i expect it to be better there for large n_samples. Of course memory also depends on many other parameters like k ... In the case of huge n_features it won't help in regards to memory; but that's not your problem here)

In this case you should carefully tune your mini-batch sizes then.

You can try the classic kmeans implementation there too as you seem to be just quite off the memory-requirements and maybe this implementation is more efficient (more tunable for sure).

In the latter case, init, n_init, precompute_distances, algorithm and maybe copy_x are all parameters having effect on memory-consumption.

And furthermore: if(!) your data is sparse; try calling it with sparse-matrices. (from reading kmeans2-docs it seems it's not supported, but sklearn's kmeans does!)


问:
How to reboot not jailbroken iOS device programmatically?
I need to reboot iOS device for automation.
Is there a way to do that automatically using terminal or may be to write simple iOS app which would reboot device on launch?</p>

答: Actually, if you're interested you could reboot via the killswitch in springboard app switcher</p>


问:
Binding variables in dynamic PL/SQL
I have a dynamic PL/SQL that will construct the SELECT statement based on what the searching criteria input from the users,likes:

```<code>     l_sql := 'SELECT *  INTO  FROM TABLEA WHERE 1=1 ';

      IF in_param1 IS NOT NULL THEN
        l_sql := l_sql || 'AND column1 = in_param1 ';
      END IF;

      IF in_param2 IS NOT NULL THEN
        l_sql := l_sql || 'AND column2 = in_param2 ';
      END IF;
      ...................................

     IF in_paramXX IS NOT NULL THEN
        l_sql := l_sql || 'AND columnXX = in_paramXX ';
      END IF;
</code>```

To reduce the hard parse overhead , I consider to use the binding variables. However , it is difficult to manage when supplying the actual values to the binding variables as there are so many binding variables and combination of the generated SELECT statement . I cannot use the method of DBMS_SESSION.set_context() introduced at http://www.dba-oracle.com/plsql/t_plsql_dynamic_binds.htm because my account has no right to use this package. Besides , I want the generated SQL only contains the conditions on the fields that the user did not leave empty. So I cannot change the dynamic SQL to something likes

```<code>SELECT *  INTO  FROM TABLEA WHERE 1=1
and ( in_param1 is NULL or  column1 = in_param1)
and ( in_param2 is NULL or  column2 = in_param2)
...............................................
and ( in_paramXX is NULL or  columnXX = in_paramXX)
</code>```

So , I want to try  to use the DBMS_SQL method .Can anyone give an example about how to use DBMS_SQL to call dynamic SQL with binding variables? Especially , how can I get the result executed from DBMS_SQL.execute() to the SYS_REFCURSOR , something like :

```<code>open refcursor for select .... from
</code>```

The oracle version that I use is 10g and it seems that the oracle 10g does not have DBMS_Sql.To_Refcursor()

答:
In your Oracle version you can apply some tricks to your query in order to do this. The idea is to use a query in the following form:

```<code>select *
from
(select
 :possibleParam1 as param1
 -- do the same for every possible param in your query
 :possibleParamN as paramN
 from dual
 where rownum > 0) params
 inner join
-- join your tables here
on
-- concatenate your filters here
where
-- fixed conditions
</code>```

then execute it with:

```<code>open c for query using param1, ..., paramN;
</code>```

It works by using DUAL to generate a fake row with every single param, then inner joining this fake row to your real query (without any filters) using only the filters you want to apply. This way, you have a fixed list of bind variables in the SELECT list of the params subquery, but can control which filters are applied by modifying the join condition between params and your real query.

So, if you have something like, say:

```<code>create table people (
    first_name varchar2(20)
    last_name varchar2(20)
);
</code>```

you can construct the following query if you just want to filter on first name

```<code>select *
from
(select
 :first_name as first_name,
 :last_name as last_name
 from dual
 where rownum > 0) params
 inner join
people
on
people.first_name = params.first_name;
</code>```

and this if you want to filter on both first_name and last_name

```<code>select *
from
(select
 :first_name as first_name,
 :last_name as last_name
 from dual
 where rownum > 0) params
 inner join
people
on
people.first_name = params.first_name and
people.last_name = params.last_name;
</code>```

and in every case you would execute with

```<code>open c for query using filterFirstName, filterLastName;
</code>```

It is important for performance to use the where rownum > 0 with DUAL as it forces Oracle to "materialize" the subquery. This usually makes DUAL stop interfering with the rest of the query. Anyway, you should check the execution plans to be sure Oracle is not doing anything wrong.

Title: Binding variables in dynamic PL/SQL

Body:
I have a dynamic PL/SQL that will construct the SELECT statement based on what the searching criteria input from the users,likes:

     l_sql := 'SELECT *  INTO  FROM TABLEA WHERE 1=1 ';

      IF in_param1 IS NOT NULL THEN
        l_sql := l_sql || 'AND column1 = in_param1 ';
      END IF;

      IF in_param2 IS NOT NULL THEN
        l_sql := l_sql || 'AND column2 = in_param2 ';
      END IF;
      ...................................

     IF in_paramXX IS NOT NULL THEN
        l_sql := l_sql || 'AND columnXX = in_paramXX ';
      END IF;

To reduce the hard parse overhead , I consider to use the binding variables. However , it is difficult to manage when supplying the actual values to the binding variables as there are so many binding variables and combination of the generated SELECT statement . I cannot use the method of DBMS_SESSION.set_context() introduced at http://www.dba-oracle.com/plsql/t_plsql_dynamic_binds.htm because my account has no right to use this package. Besides , I want the generated SQL only contains the conditions on the fields that the user did not leave empty. So I cannot change the dynamic SQL to something likes

SELECT *  INTO  FROM TABLEA WHERE 1=1
and ( in_param1 is NULL or  column1 = in_param1)
and ( in_param2 is NULL or  column2 = in_param2)
...............................................
and ( in_paramXX is NULL or  columnXX = in_paramXX)

So , I want to try  to use the DBMS_SQL method .Can anyone give an example about how to use DBMS_SQL to call dynamic SQL with binding variables? Especially , how can I get the result executed from DBMS_SQL.execute() to the SYS_REFCURSOR , something like :

open refcursor for select .... from

The oracle version that I use is 10g and it seems that the oracle 10g does not have DBMS_Sql.To_Refcursor()

Body:
In your Oracle version you can apply some tricks to your query in order to do this. The idea is to use a query in the following form:

select *
from
(select
 :possibleParam1 as param1
 -- do the same for every possible param in your query
 :possibleParamN as paramN
 from dual
 where rownum > 0) params
 inner join
-- join your tables here
on
-- concatenate your filters here
where
-- fixed conditions

then execute it with:

open c for query using param1, ..., paramN;

It works by using DUAL to generate a fake row with every single param, then inner joining this fake row to your real query (without any filters) using only the filters you want to apply. This way, you have a fixed list of bind variables in the SELECT list of the params subquery, but can control which filters are applied by modifying the join condition between params and your real query.

So, if you have something like, say:

create table people (
    first_name varchar2(20)
    last_name varchar2(20)
);

you can construct the following query if you just want to filter on first name

select *
from
(select
 :first_name as first_name,
 :last_name as last_name
 from dual
 where rownum > 0) params
 inner join
people
on
people.first_name = params.first_name;

and this if you want to filter on both first_name and last_name

select *
from
(select
 :first_name as first_name,
 :last_name as last_name
 from dual
 where rownum > 0) params
 inner join
people
on
people.first_name = params.first_name and
people.last_name = params.last_name;

and in every case you would execute with

open c for query using filterFirstName, filterLastName;

It is important for performance to use the where rownum > 0 with DUAL as it forces Oracle to "materialize" the subquery. This usually makes DUAL stop interfering with the rest of the query. Anyway, you should check the execution plans to be sure Oracle is not doing anything wrong.


问:
HTTPS image not rendering in react native image
I am trying to render an image "https://www.edamam.com/web-img/22c/22c27bdc6b8dc67215c7478cb4e5dc42.jpg" which works fine in a web browser, but in a react-native image the image does not appear.

I am attempting to do :

```<code> <Image
style={{ height: 200, width: 200 }}
source={{
    uri:
        "https://www.edamam.com/web-img/22c/22c27bdc6b8dc67215c7478cb4e5dc42.jpg"
}}
/>;
</code>```

This also does not work:

```<code> <Image
style={{ flex: 1, resizeMode: "cover" }}
source={{
    uri:
        "https://www.edamam.com/web-img/22c/22c27bdc6b8dc67215c7478cb4e5dc42.jpg"
}}
/>;
</code>```

What am I doing incorrectly here?

答:
I tried your code, initially I did not get the image, then I handle the error using onError handler and found the following error

An SSL error has occurred and a secure connection to the server cannot be made

You may look into the stackoverflow answers for this error here

I tried the first solution by changing

info.plist

with following configuration and it worked

```<code><key>NSAppTransportSecurity</key>
<dict>
  <key>NSAllowsArbitraryLoads</key>
  <true/>
</dict>
</code>```

Have a look into this document, above approach is not recommended, instead they have suggested other way (it is also mentioned in the linked stackoverflow answer).

Hope this will help.

Body:
I am trying to render an image "https://www.edamam.com/web-img/22c/22c27bdc6b8dc67215c7478cb4e5dc42.jpg" which works fine in a web browser, but in a react-native image the image does not appear.

I am attempting to do :

 <Image
style={{ height: 200, width: 200 }}
source={{
    uri:
        "https://www.edamam.com/web-img/22c/22c27bdc6b8dc67215c7478cb4e5dc42.jpg"
}}
/>;

This also does not work:

 <Image
style={{ flex: 1, resizeMode: "cover" }}
source={{
    uri:
        "https://www.edamam.com/web-img/22c/22c27bdc6b8dc67215c7478cb4e5dc42.jpg"
}}
/>;

What am I doing incorrectly here?

Body:
I tried your code, initially I did not get the image, then I handle the error using onError handler and found the following error

An SSL error has occurred and a secure connection to the server cannot be made

You may look into the stackoverflow answers for this error here

I tried the first solution by changing

info.plist

with following configuration and it worked

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSAllowsArbitraryLoads</key>
  <true/>
</dict>

Have a look into this document, above approach is not recommended, instead they have suggested other way (it is also mentioned in the linked stackoverflow answer).

Hope this will help.


问:
How to scatterplot between 2 rasters and find correlation?
I have 2 raster images of the same area. One raster represents temperature and the other raster gives NDVI details. I want to correlate between NDVI and Temperature. I tried with ArcGIS using band statistics tool which is giving covariance and correlation coefficient values. Along with the values I want to plot them (Scatter plot i.e., temperature vs NDVI). Can some one please guide me in achieving this. Thankyou.</p>

答:
With R you can do things like this:

```<code>library(raster)
b <- brick(system.file("external/rlogo.grd", package="raster"))

layerStats(b, 'pearson')
#$`pearson correlation coefficient`
#            red     green      blue
#red   1.0000000 0.9980961 0.9501633
#green 0.9980961 1.0000000 0.9658011
#blue  0.9501633 0.9658011 1.0000000

#$mean
#     red    green     blue
#182.2855 185.3509 192.8046

plot(b[[1]], b[[2]])
pairs(b)
</code>```

Body:
With R you can do things like this:

library(raster)
b <- brick(system.file("external/rlogo.grd", package="raster"))

layerStats(b, 'pearson')
#$`pearson correlation coefficient`
#            red     green      blue
#red   1.0000000 0.9980961 0.9501633
#green 0.9980961 1.0000000 0.9658011
#blue  0.9501633 0.9658011 1.0000000

#$mean
#     red    green     blue
#182.2855 185.3509 192.8046

plot(b[[1]], b[[2]])
pairs(b)


问:
Creating polymorphic lens
I am able to create a lens for the last field (c) in my data types by doing the follow:

```<code>{-# LANGUAGE DuplicateRecordFields #-}

data X1 a c = X1 { a' :: a, b' :: Int, c' :: c }

data X2 a b c = X2 { a' :: a, b' :: b, c' :: c }

class HavingFieldC x cs ct where
  c :: Functor f => (cs -> f ct) -> x cs -> f (x ct)

instance HavingFieldC (X1 a) cs ct  where
  c = lens
    (\X1 { c' } -> c')
    (\X1 {..} v -> X1 {c' = v, ..})

instance HavingFieldC (X2 a b) cs ct where
  c = lens
    (\X2 { c' } -> c')
    (\X2 {..} v -> X2 {c' = v, ..})
</code>```

Is there something similar I can do for fields a and b

答:
You can generalize the definition of the HavingField class; in particular, you can express the relationship between the updated type variable and the record type using functional dependencies. This allows the update type variable to occur in any position; and it allows updates to monomorphic fields.

```<code>class FieldC k k' x x' | k x' -> k', k' x -> k, k -> x, k' -> x' where
  fieldC :: Functor f => (x -> f x') -> k -> f k'

instance (b ~ b0, b' ~ b0') => FieldC (X1 a b) (X1 a b') b0 b0' where ...
instance (b ~ b0, b' ~ b0') => FieldC (X2 c a b) (X2 c a b') b0 b0' where ...
</code>```

You define instances in much the same way; note that some of the equality constraints are placed in the context to improve type inference. You can read the first instance above as instance FieldC (X1 a b) (X1 a b') b b'.

The classes for other fields are defined in exactly the same way; this is essentially the most general way to define a class for lenses (which should be more apparent if one notes that the type of fieldC is actually just Lens k k' x x').

```<code>class FieldA k k' x x' | k x' -> k', k' x -> k, k -> x, k' -> x' where
  fieldA :: Functor f => (x -> f x') -> k -> f k'

class FieldB k k' x x' | k x' -> k', k' x -> k, k -> x, k' -> x' where
  fieldB :: Functor f => (x -> f x') -> k -> f k'
</code>```

(Note: this too can be generalized to a single class with an additional parameter corresponding to the field name; this is probably outside the scope of this question).

Now it should be clearer how to write the instance declarations:

```<code>instance (x0 ~ Int, x1 ~ Int) => FieldB (X1 a c) (X1 a c) x0 x1 where ...
instance (b0 ~ b, b0' ~ b') => FieldB (X2 a b c) (X2 a b' c) b0 b0' where ...

instance (a ~ a0, a' ~ a0') => FieldA (X1 a c) (X1 a' c) a0 a0' where ...
instance (a0 ~ a, a0' ~ a') => FieldA (X2 a b c) (X2 a' b c) a0 a0' where ...
</code>```

The only difference for monomorphic fields being that the field types are monomorphic types.

A simple test will show that the proper polymorphic types are assigned:

```<code>foo x =
  let y = view fieldB x
  in set fieldA (2 * y) $ set fieldC (3 + y) x
</code>```

You can ask GHCi for the inferred types at particular instantiations:

```<code>\x -> foo x `asTypeOf` X1{} :: X1 a b -> X1 Int Int
\x -> foo x `asTypeOf` X2{} :: Num a0' => X2 a a0' b -> X2 a0' a0' a0'
</code>```

This general pattern can be found implemented e.g. here. This implementation is slightly more permissive; the f in Functor f => .. is a typeclass parameter instead of being universally quantified over. Depending on your specific use cases, this may or may not work for you.

Title: Creating polymorphic lens

Body:
I am able to create a lens for the last field (c) in my data types by doing the follow:

{-# LANGUAGE DuplicateRecordFields #-}

data X1 a c = X1 { a' :: a, b' :: Int, c' :: c }

data X2 a b c = X2 { a' :: a, b' :: b, c' :: c }

class HavingFieldC x cs ct where
  c :: Functor f => (cs -> f ct) -> x cs -> f (x ct)

instance HavingFieldC (X1 a) cs ct  where
  c = lens
    (\X1 { c' } -> c')
    (\X1 {..} v -> X1 {c' = v, ..})

instance HavingFieldC (X2 a b) cs ct where
  c = lens
    (\X2 { c' } -> c')
    (\X2 {..} v -> X2 {c' = v, ..})

Is there something similar I can do for fields a and b

Body:
You can generalize the definition of the HavingField class; in particular, you can express the relationship between the updated type variable and the record type using functional dependencies. This allows the update type variable to occur in any position; and it allows updates to monomorphic fields.

class FieldC k k' x x' | k x' -> k', k' x -> k, k -> x, k' -> x' where
  fieldC :: Functor f => (x -> f x') -> k -> f k'

instance (b ~ b0, b' ~ b0') => FieldC (X1 a b) (X1 a b') b0 b0' where ...
instance (b ~ b0, b' ~ b0') => FieldC (X2 c a b) (X2 c a b') b0 b0' where ...

You define instances in much the same way; note that some of the equality constraints are placed in the context to improve type inference. You can read the first instance above as instance FieldC (X1 a b) (X1 a b') b b'.

The classes for other fields are defined in exactly the same way; this is essentially the most general way to define a class for lenses (which should be more apparent if one notes that the type of fieldC is actually just Lens k k' x x').

class FieldA k k' x x' | k x' -> k', k' x -> k, k -> x, k' -> x' where
  fieldA :: Functor f => (x -> f x') -> k -> f k'

class FieldB k k' x x' | k x' -> k', k' x -> k, k -> x, k' -> x' where
  fieldB :: Functor f => (x -> f x') -> k -> f k'

(Note: this too can be generalized to a single class with an additional parameter corresponding to the field name; this is probably outside the scope of this question).

Now it should be clearer how to write the instance declarations:

instance (x0 ~ Int, x1 ~ Int) => FieldB (X1 a c) (X1 a c) x0 x1 where ...
instance (b0 ~ b, b0' ~ b') => FieldB (X2 a b c) (X2 a b' c) b0 b0' where ...

instance (a ~ a0, a' ~ a0') => FieldA (X1 a c) (X1 a' c) a0 a0' where ...
instance (a0 ~ a, a0' ~ a') => FieldA (X2 a b c) (X2 a' b c) a0 a0' where ...

The only difference for monomorphic fields being that the field types are monomorphic types.

A simple test will show that the proper polymorphic types are assigned:

foo x =
  let y = view fieldB x
  in set fieldA (2 * y) $ set fieldC (3 + y) x

You can ask GHCi for the inferred types at particular instantiations:

\x -> foo x `asTypeOf` X1{} :: X1 a b -> X1 Int Int
\x -> foo x `asTypeOf` X2{} :: Num a0' => X2 a a0' b -> X2 a0' a0' a0'

This general pattern can be found implemented e.g. here. This implementation is slightly more permissive; the f in Functor f => .. is a typeclass parameter instead of being universally quantified over. Depending on your specific use cases, this may or may not work for you.


问:
Listen for keyup on all input fields
Im trying to capture the keyup on all input fields on a page.

My current code is:

```<code>var els = document.querySelectorAll('input');
for (var i = 0; i < els.length; i += 1) {
    addEvent('keyup', els[i], makeHandler(els[i]));
}

function makeHandler(field) {
    console.log(field.value);

}

function addEvent(evnt, elem, func) {
    if (elem.addEventListener) {
        elem.addEventListener(evnt,func,false);
    } else if (elem.attachEvent) {
        elem.attachEvent("on"+evnt, function(e) {
            e = e || window.event;
            if (!e.preventDefault) {
                e.preventDefault = preventDefaultOnIE;
            }
            func.call(this, e);
        });
    } else { // No much to do
        elem[evnt] = func;
    }
}
</code>```

But for some reason its only capturing the value on page load, not once i begin to type in any of the fields.

Any ideas what I'm doing wrong?

答:
I like to embed the script in a function so I can minimize it in my IDE and turn it on and off globally. In other words, give it a name.</p>

```<code>attachKeyupListenerToInputElements();
function attachKeyupListenerToInputElements(){
    var inputs = doc.querySelectorAll('input');
    for (var i = 0; i < inputs.length; i += 1) {
        inputs[i].addEventListener("keyup", keyupHandler);
    }

    function keyupHandler() {
        console.log(this.value);
    }
}
</code>```

Title: Listen for keyup on all input fields

Body:
Im trying to capture the keyup on all input fields on a page.

My current code is:

var els = document.querySelectorAll('input');
for (var i = 0; i < els.length; i += 1) {
    addEvent('keyup', els[i], makeHandler(els[i]));
}

function makeHandler(field) {
    console.log(field.value);

}

function addEvent(evnt, elem, func) {
    if (elem.addEventListener) {
        elem.addEventListener(evnt,func,false);
    } else if (elem.attachEvent) {
        elem.attachEvent("on"+evnt, function(e) {
            e = e || window.event;
            if (!e.preventDefault) {
                e.preventDefault = preventDefaultOnIE;
            }
            func.call(this, e);
        });
    } else { // No much to do
        elem[evnt] = func;
    }
}

But for some reason its only capturing the value on page load, not once i begin to type in any of the fields.

Any ideas what I'm doing wrong?

Body:
I like to embed the script in a function so I can minimize it in my IDE and turn it on and off globally. In other words, give it a name.

attachKeyupListenerToInputElements();
function attachKeyupListenerToInputElements(){
    var inputs = doc.querySelectorAll('input');
    for (var i = 0; i < inputs.length; i += 1) {
        inputs[i].addEventListener("keyup", keyupHandler);
    }

    function keyupHandler() {
        console.log(this.value);
    }
}


问:
How do I show and hide loader to show more posts?
How do I show the loader when a user clicks on load more posts button and more posts are loading and hide it after the posts have been loaded successfully. Then I want to again show the loader when user clicks on load more posts button

$("#lmb").click(function(e) {
  $('#lmi').show();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="lmb" type="button" style="background-color: #f44336;width:98%;border-radius:6px;border:2px solid #4a235a;">Load More Posts <img src="http://www.nvidia.com/docs/IO/151309/loader.gif" width="2%" height="2%" id="lmi" style="display:none;"></button></code>```

答:
I hope this will help you.

```<code><button id="lmb" type="button" style="background-color: #f44336;width:98%;border-radius:6px;border:2px solid #4a235a;">Load More Posts
  <img id="loader" src="http://www.nvidia.com/docs/IO/151309/loader.gif" width="2%" height="2%" id="lmi" style="display:none;">
</button>
</code>```

jQuery post method

```<code>$(document).ready(function(){
    $("#lmb").click(function(){
        $('#loader').show();
        $.post( "URL", function( data ) {
         $('#loader').hide();
      });
    });
});
</code>```

There are done, fail & always methods also you can handle it

```<code>var jqxhr = $.post( "example.php", function() {
  alert( "success" );
})
  .done(function() {
    alert( "second success" );
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "finished" );
  });
</code>```

Body:
How do I show the loader when a user clicks on load more posts button and more posts are loading and hide it after the posts have been loaded successfully. Then I want to again show the loader when user clicks on load more posts button

$("#lmb").click(function(e) {
  $('#lmi').show();
});

<button id="lmb" type="button" style="background-color: #f44336;width:98%;border-radius:6px;border:2px solid #4a235a;">Load More Posts </button>

Body:
I hope this will help you.

<button id="lmb" type="button" style="background-color: #f44336;width:98%;border-radius:6px;border:2px solid #4a235a;">Load More Posts
  <img id="loader" src="http://www.nvidia.com/docs/IO/151309/loader.gif" width="2%" height="2%" id="lmi" style="display:none;">
</button>

jQuery post method

$(document).ready(function(){
    $("#lmb").click(function(){
        $('#loader').show();
        $.post( "URL", function( data ) {
         $('#loader').hide();
      });
    });
});

There are done, fail & always methods also you can handle it

var jqxhr = $.post( "example.php", function() {
  alert( "success" );
})
  .done(function() {
    alert( "second success" );
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "finished" );
  });