答:
Try enchant from http://pythonhosted.org/pyenchant/tutorial.html

```<code>>>> from nltk import everygrams
>>> import enchant
>>> word = 'godaddy'
>>> [''.join(_ngram) for _ngram in everygrams(word) if d.check(''.join(_ngram))]
['g', 'o', 'd', 'a', 'd', 'd', 'y', 'go', 'ad', 'god', 'dad', 'add', 'daddy']
>>> d = enchant.Dict("en_US")
# Exclude single char words.
>>> [''.join(_ngram) for _ngram in everygrams(word) if d.check(''.join(_ngram)) and len(_ngram) > 1]
['go', 'ad', 'god', 'dad', 'add', 'daddy']
</code>```

But if it's all combinations of strings, regardless of whether it's a valid English word:

```<code>>>> list(everygrams(word))
</code>```

See also:

n-grams in python, four, five, six grams?

Generating Ngrams (Unigrams,Bigrams etc) from a large corpus of .txt files and their Frequency

extracting n grams from huge text

Fast/Optimize N-gram implementations in python

How to compute skipgrams in python?

Note

Any dictionary checking method would have its limitation:

```<code>>>> from nltk.corpus import words as english
>>> vocab = set(w.lower() for w in english.words())
>>> "google" in vocab
False
>>> "stackoverflow" in vocab
False

>>> import enchant
>>> d = enchant.Dict("en_US")
>>> d.check('StackOverflow')
False
>>> d.check('Stackoverflow')
False
>>> d.check('Google')
True
</code>```

The "principled" way to do this task is to do language modeling at character level and have some probabilistic way to check whether the sequence of characters is more/less probable as English words.

Also, there are many Englishes in the world. A "valid" word in British English could be an unknown word in American English. See http://www.ucl.ac.uk/english-usage/projects/ice.htm and https://en.wikipedia.org/wiki/World_Englishes#Classification_of_Englishes

Title: Get all possible english words from a string

Body:
Generate all possible combination of english words from a given string in python.

Input: godaddy
Output: go, god, dad, add, daddy

Any good libraries?

Body:
Try enchant from http://pythonhosted.org/pyenchant/tutorial.html

>>> from nltk import everygrams
>>> import enchant
>>> word = 'godaddy'
>>> [''.join(_ngram) for _ngram in everygrams(word) if d.check(''.join(_ngram))]
['g', 'o', 'd', 'a', 'd', 'd', 'y', 'go', 'ad', 'god', 'dad', 'add', 'daddy']
>>> d = enchant.Dict("en_US")
# Exclude single char words.
>>> [''.join(_ngram) for _ngram in everygrams(word) if d.check(''.join(_ngram)) and len(_ngram) > 1]
['go', 'ad', 'god', 'dad', 'add', 'daddy']

But if it's all combinations of strings, regardless of whether it's a valid English word:

>>> list(everygrams(word))

See also:

n-grams in python, four, five, six grams?

Generating Ngrams (Unigrams,Bigrams etc) from a large corpus of .txt files and their Frequency

extracting n grams from huge text

Fast/Optimize N-gram implementations in python

How to compute skipgrams in python?

Note

Any dictionary checking method would have its limitation:

>>> from nltk.corpus import words as english
>>> vocab = set(w.lower() for w in english.words())
>>> "google" in vocab
False
>>> "stackoverflow" in vocab
False

>>> import enchant
>>> d = enchant.Dict("en_US")
>>> d.check('StackOverflow')
False
>>> d.check('Stackoverflow')
False
>>> d.check('Google')
True

The "principled" way to do this task is to do language modeling at character level and have some probabilistic way to check whether the sequence of characters is more/less probable as English words.

Also, there are many Englishes in the world. A "valid" word in British English could be an unknown word in American English. See http://www.ucl.ac.uk/english-usage/projects/ice.htm and https://en.wikipedia.org/wiki/World_Englishes#Classification_of_Englishes


来源: stackexchange

问:
Delegates in C#
I`m having some trouble in understanding how delegates in C# work. I have many code examples, but i still could not grasp it properly.

Can someone explain it to me in "plain english"? Of course! examples of code will help, but i think i need more of a description of how/why it works.

EDIT:

Well, the question is: why does delegates work? What is a "flow chart" of the entire process?

What are the pre-requisites of using delegates?

I hope this makes the question clearer.

答:
Delagates in  c# :  it defines the signature of the method which it can invoke.In other words we can say that it wraps the reference of the method which it can call. Below are the uses of delegates :

It provides the mechanism to implement the call back functionality in .NET framework.

It provides the ability to call multiple methods sequentially.

It has the ability to implement asynchronous method calling.

It supports both static and instance methods.

Below is the explanation how it works internally.

//Here is the declaration of the delegates.

```<code>public delegate void DisplayNamme(string name);
</code>```

at run time CLR creates a class for the delegates as shown below.

```<code>public class DisplayNamme : System.MulticastDelegate{

   // It is a contructor
   public DisplayNamme(Object @object, IntPtr method);

   // It is the method with the same prototype as defined in the source code.
   public void Invoke(String name);

// This method allowing the callback to be asynchronouslly.

 public virtual IAsyncResult BeginInvoke(String name,
 AsyncCallback callback, Object @object);

 public virtual void EndInvoke(IAsyncResult result);

}
</code>```

We can see it through ILDasm.exe tool. Use this tool to break the DLL.

Constructor have two parameters: IntPrt refers the name of the method that is passed to the function, and @object refers the reference of the object that is passed to the constructor implicitly.

CLR uses Invoke method of delegates to call the callback method.

Below is the implementation of callback method using delegates.

```<code>// Declare Delegates
    public delegate void DisplayNamme(string name);
    class Program
    {
       public static void getName(string name)
        {
            Console.WriteLine(name);
        }
       public static void ShowName(DisplayNamme dn, string name)
        {
        // callback method calling. We can call it in two ways.
           dn(name);
          // or explicitly
            dn.Invoke(name);
    }
      static void Main(string[] args)
        {
            DisplayNamme delDN = getName;
            Program.ShowName(delDN, "CallBack");
            Console.ReadLine();
        }
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Delegates in C#

Body:
Delagates in  c# :  it defines the signature of the method which it can invoke.In other words we can say that it wraps the reference of the method which it can call. Below are the uses of delegates :

It provides the mechanism to implement the call back functionality in .NET framework.

It provides the ability to call multiple methods sequentially.

It has the ability to implement asynchronous method calling.

It supports both static and instance methods.

Below is the explanation how it works internally.

//Here is the declaration of the delegates.

public delegate void DisplayNamme(string name);

at run time CLR creates a class for the delegates as shown below.

public class DisplayNamme : System.MulticastDelegate{

   // It is a contructor
   public DisplayNamme(Object @object, IntPtr method);

   // It is the method with the same prototype as defined in the source code.
   public void Invoke(String name);

// This method allowing the callback to be asynchronouslly.

 public virtual IAsyncResult BeginInvoke(String name,
 AsyncCallback callback, Object @object);

 public virtual void EndInvoke(IAsyncResult result);

}

We can see it through ILDasm.exe tool. Use this tool to break the DLL.

Constructor have two parameters: IntPrt refers the name of the method that is passed to the function, and @object refers the reference of the object that is passed to the constructor implicitly.

CLR uses Invoke method of delegates to call the callback method.

Below is the implementation of callback method using delegates.

// Declare Delegates
    public delegate void DisplayNamme(string name);
    class Program
    {
       public static void getName(string name)
        {
            Console.WriteLine(name);
        }
       public static void ShowName(DisplayNamme dn, string name)
        {
        // callback method calling. We can call it in two ways.
           dn(name);
          // or explicitly
            dn.Invoke(name);
    }
      static void Main(string[] args)
        {
            DisplayNamme delDN = getName;
            Program.ShowName(delDN, "CallBack");
            Console.ReadLine();
        }
    }


问:
Read a file after write and closing it in C
My code does the following

do 100 times of

open a new file; write 10M data; close it

open the 100 files together, read and merge their data into a larger file

do steps 1 and 2 many times in a loop

I was wondering if I can keep the 100 open w/o opening and closing them too many times. What I can do is fopen them with w+. After writing I set position the beginning to read, after read I set position to the beginning to write, and so on.

The questions are:

if I read after write w/o closing, do we always read all the written data

would this save some overhead? File open and close must have some overhead, but is this overhead large enough to save?

Bases on the comments and discussion I will talk about why I need to do this in my work. It is also related to my other post

how to convert large row-based tables into column-based tables efficently

I have a calculation that generates a stream of results. So far the results are saved in a row-storage table. This table has 1M columns, each column could be 10M long. Actually each column is one attribute the calculation produces. At the calculation runs, I dump and append the intermediate results the table. The intermediate results could be 2 or 3 double values at each column. I wanted to dump it soon because it already consumes >16M memory. And the calculate needs more memoy. This ends up a table like the following

```<code> aabbcc...zzaabbcc..zz.........aabb...zz
</code>```

A row of data are stored together. The problem happens when I want to analyze the data column by column. So I have to read 16 bytes then seek to the next row for reading 16 bytes then keep on going. There are too many seeks, it is much slower than if all columns are stored together so I can read them sequentially.

I can make the calculation dump less frequent. But to make the late read more efficent. I may want to have 4K data stored together since I assume each fread gets 4K by default even if I read only 16bytes. But this means I need to buffer 1M*4k = 4G in memory...

So I was thinking if I can merge fragment datas into larger chunks like that the post says

how to convert large row-based tables into column-based tables efficently

So I wanted to use files as offline buffers. I may need 256 files to get a 4K contiguous data after merge if each file contains 1M of 2 doubles. This work can be done as an asynchronous way in terms of the main calculation. But I wanted to ensure the merge overhead is small so when it runs in parallel it can finish before  the main calculation is done. So I came up with this question.

I guess this is very related to how column based  data base is constructed. When people create them, do they have the similar issues? Is there any description of how it works on creation?

答:
Yes. You can keep the 100 files open without doing the opening-closing-opening cycle. Most systems do have a limit on the number of open files though.

if I read after write w/o closing, do we always read all the written data

It depends on you. You can do an fseek goto wherever you want in the file and read data from there. It's all the way you and your logic.

would this save some overhead? File open and close must have some overhead, but is this overhead large enough to save?

This would definitely save some overhead, like additional unnecessary I/O operations and also in some systems, the content which you write to file is not immediately flushed to physical file, it may be buffered and flushed periodically and or done at the time of fclose.

So, such overheads are saved, but, the real question is what do you achieve by saving such overheads? How does it suit you in the overall picture of your application? This is the call which you must take before deciding on the logic.

Body:
My code does the following

do 100 times of

open a new file; write 10M data; close it

open the 100 files together, read and merge their data into a larger file

do steps 1 and 2 many times in a loop

I was wondering if I can keep the 100 open w/o opening and closing them too many times. What I can do is fopen them with w+. After writing I set position the beginning to read, after read I set position to the beginning to write, and so on.

The questions are:

if I read after write w/o closing, do we always read all the written data

would this save some overhead? File open and close must have some overhead, but is this overhead large enough to save?

Bases on the comments and discussion I will talk about why I need to do this in my work. It is also related to my other post

how to convert large row-based tables into column-based tables efficently

I have a calculation that generates a stream of results. So far the results are saved in a row-storage table. This table has 1M columns, each column could be 10M long. Actually each column is one attribute the calculation produces. At the calculation runs, I dump and append the intermediate results the table. The intermediate results could be 2 or 3 double values at each column. I wanted to dump it soon because it already consumes >16M memory. And the calculate needs more memoy. This ends up a table like the following

 aabbcc...zzaabbcc..zz.........aabb...zz

A row of data are stored together. The problem happens when I want to analyze the data column by column. So I have to read 16 bytes then seek to the next row for reading 16 bytes then keep on going. There are too many seeks, it is much slower than if all columns are stored together so I can read them sequentially.

I can make the calculation dump less frequent. But to make the late read more efficent. I may want to have 4K data stored together since I assume each fread gets 4K by default even if I read only 16bytes. But this means I need to buffer 1M*4k = 4G in memory...

So I was thinking if I can merge fragment datas into larger chunks like that the post says

how to convert large row-based tables into column-based tables efficently

So I wanted to use files as offline buffers. I may need 256 files to get a 4K contiguous data after merge if each file contains 1M of 2 doubles. This work can be done as an asynchronous way in terms of the main calculation. But I wanted to ensure the merge overhead is small so when it runs in parallel it can finish before  the main calculation is done. So I came up with this question.

I guess this is very related to how column based  data base is constructed. When people create them, do they have the similar issues? Is there any description of how it works on creation?


答:
You can use w+ as long as the maximum number of open files on your system allows it; this is usually 255 or 1024, and can be set (e.g. on Unix by ulimit).

But I'm not too sure this will be worth the effort.

On the other hand, 100 files of 10M each is one gigabyte; you might want to experiment with a RAM disk. Or with a large file system cache.

I suspect that huger savings might be reaped by analyzing your specific problem structure. Why is it 100 files? Why 10 M? What kind of "merge" are you doing? Are those 100 files always accessed in the same order and with the same frequency? Could some data be kept in RAM and never be written at all?

Update

So, you have several large buffers like,

```<code>ABCDEFG...
ABCDEFG...
ABCDEFG...
</code>```

and you want to pivot them so they read

```<code>AAA...
BBB...
CCC...
</code>```

If you already have the total size (i.e., you know that you are going to write 10 GB of data), you can do this with two files, pre-allocating the file and using fseek() to write to the output file. With memory-mapped files, this should be quite efficient. In practice, row Y, column X of 1,000,000 , has been dumped at address 16*X in file Y.dat; you need to write it to address 16*(Y*1,000,000 + X) into largeoutput.dat.

Actually, you could write the data even during the first calculation. Or you could have two processes communicating via a pipe, one calculating, one writing to both row-column and column-row files, so that you can monitor the performances of each.

Frankly, I think that adding more RAM and/or a fast I/O layer (SSD maybe?) could get you more bang for the same buck. Your time costs too, and the memory will remain available after this one work has been completed.

Title: Read a file after write and closing it in C

Body:
You can use w+ as long as the maximum number of open files on your system allows it; this is usually 255 or 1024, and can be set (e.g. on Unix by ulimit).

But I'm not too sure this will be worth the effort.

On the other hand, 100 files of 10M each is one gigabyte; you might want to experiment with a RAM disk. Or with a large file system cache.

I suspect that huger savings might be reaped by analyzing your specific problem structure. Why is it 100 files? Why 10 M? What kind of "merge" are you doing? Are those 100 files always accessed in the same order and with the same frequency? Could some data be kept in RAM and never be written at all?

Update

So, you have several large buffers like,

ABCDEFG...
ABCDEFG...
ABCDEFG...

and you want to pivot them so they read

AAA...
BBB...
CCC...

If you already have the total size (i.e., you know that you are going to write 10 GB of data), you can do this with two files, pre-allocating the file and using fseek() to write to the output file. With memory-mapped files, this should be quite efficient. In practice, row Y, column X of 1,000,000 , has been dumped at address 16*X in file Y.dat; you need to write it to address 16*(Y*1,000,000 + X) into largeoutput.dat.

Actually, you could write the data even during the first calculation. Or you could have two processes communicating via a pipe, one calculating, one writing to both row-column and column-row files, so that you can monitor the performances of each.

Frankly, I think that adding more RAM and/or a fast I/O layer (SSD maybe?) could get you more bang for the same buck. Your time costs too, and the memory will remain available after this one work has been completed.


问:
Cannot read property 'location' of undefined
I try to use react-router-dom 4.0.0 library. But it send me this error

Uncaught TypeError: Cannot read property 'location' of undefined

It seems that problem in browserHistore. Before I used react-router 2.x.x and everything was alright.
This is my index.js

```<code>import 'babel-polyfill'
import React from 'react'
import { Router, hashHistory } from 'react-router-dom'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { configureStore } from './store'
import { routes } from './routes'

const store = configureStore()

render(
  <Provider store={store}>
    <Router history={hashHistory} routes={routes} />
  </Provider>,
  document.getElementById('root')
)
</code>```

This is my routes

```<code>import React from 'react'
import { IndexRoute, Route } from 'react-router-dom'
import App from './containers/App'
import Main from './containers/Main'
import First from './containers/First'

export const routes = (
  <Route path='/' component={Main}>
    <Route path='/path' component={First} />
    <IndexRoute component={App} />
  </Route>
  )
</code>```

And also for server side express I set this get configuration

```<code>app.get('*', function root(req, res) {
  res.sendFile(__dirname + '/index.html');
});
</code>```

答:
React Router v4 is a complete re-write and isn't compatible with previous versions as you're assuming in your code. With that said, you shouldn't expect to be able to just upgrade to a new major version (V4) and have your app work as normal. You should check out the documentation or downgrade back to V2/3. Here's some code that should get you started in the right direction</p>

```<code>import 'babel-polyfill'
import React from 'react'
import { BrowserRouter as Router, Route } from 'react-router-dom'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { configureStore } from './store'
import App from './containers/App'
import Main from './containers/Main'
import First from './containers/First'

const store = configureStore()

render(
  <Provider store={store}>
    <Router>
      <Route path='/' component={Main} />
      <Route path='/path' component={First} />
    </Router>
  </Provider>,
  document.getElementById('root')
)
</code>```

Body:
I try to use react-router-dom 4.0.0 library. But it send me this error

Uncaught TypeError: Cannot read property 'location' of undefined

It seems that problem in browserHistore. Before I used react-router 2.x.x and everything was alright.
This is my index.js

import 'babel-polyfill'
import React from 'react'
import { Router, hashHistory } from 'react-router-dom'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { configureStore } from './store'
import { routes } from './routes'

const store = configureStore()

render(
  <Provider store={store}>
    <Router history={hashHistory} routes={routes} />
  </Provider>,
  document.getElementById('root')
)

This is my routes

import React from 'react'
import { IndexRoute, Route } from 'react-router-dom'
import App from './containers/App'
import Main from './containers/Main'
import First from './containers/First'

export const routes = (
  <Route path='/' component={Main}>
    <Route path='/path' component={First} />
    <IndexRoute component={App} />
  </Route>
  )

And also for server side express I set this get configuration

app.get('*', function root(req, res) {
  res.sendFile(__dirname + '/index.html');
});

Body:
React Router v4 is a complete re-write and isn't compatible with previous versions as you're assuming in your code. With that said, you shouldn't expect to be able to just upgrade to a new major version (V4) and have your app work as normal. You should check out the documentation or downgrade back to V2/3. Here's some code that should get you started in the right direction

import 'babel-polyfill'
import React from 'react'
import { BrowserRouter as Router, Route } from 'react-router-dom'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { configureStore } from './store'
import App from './containers/App'
import Main from './containers/Main'
import First from './containers/First'

const store = configureStore()

render(
  <Provider store={store}>
    <Router>
      <Route path='/' component={Main} />
      <Route path='/path' component={First} />
    </Router>
  </Provider>,
  document.getElementById('root')
)


问:
Error I got while trying to make json work in a jsp page . How to debug this?
```<code><%@ page language="java" import="net.sf.json.JSONArray" %>

 <%
  JSONArray arrayObj=new JSONArray();
   arrayObj.add("MCA");
   arrayObj.add("Amit Kumar");
   arrayObj.add("19-12-1986");
   arrayObj.add(24);
   arrayObj.add("Scored");
   arrayObj.add(new Double(66.67));
%>
<h2>Array Object is =></h2> <%=arrayObj%>
<br><hr>
<%  for(int i=0;i<arrayObj.size();i++){  %>
          <%=arrayObj.getString(i)%>
<%
  }
%>
</code>```

the error I am getting is this

```<code>org.apache.jasper.JasperException: Unable to compile class for JSP:

An error occurred at line: 6 in the generated java file
Only a type can be imported. net.sf.json.JSONArray resolves to a package

An error occurred at line: 19 in the jsp file: /index.jsp
JSONArray cannot be resolved to a type
16:         <%@ page language="java" import="net.sf.json.JSONArray" %>
17:
18:         <%
19:         JSONArray arrayObj=new JSONArray();
20:         arrayObj.add("MCA");
21:          arrayObj.add("Amit Kumar");
22:          arrayObj.add("19-12-1986");

An error occurred at line: 19 in the jsp file: /index.jsp
JSONArray cannot be resolved to a type
16:         <%@ page language="java" import="net.sf.json.JSONArray" %>
17:
18:         <%
19:         JSONArray arrayObj=new JSONArray();
20:         arrayObj.add("MCA");
21:          arrayObj.add("Amit Kumar");
22:          arrayObj.add("19-12-1986");
</code>```

How to debug this error ? I have downloaded the Json library and have put it in Tomcat/webapps/star/WEB-INF/lib.

Where star is the folder that contains the jsp page.

答: Either the JSON library is not there where you think it is, or the JAR file of the JSON library which you've downloaded simply doesn't contain that class. Investigate the JAR file using a ZIP or RAR tool. There should be a net/sf/json/JSONArray.class file inside the JAR. If it is missing, then you probably downloaded the wrong library.

ContentLicense: CC BY-SA 2.5

Body:
<%@ page language="java" import="net.sf.json.JSONArray" %>

 <%
  JSONArray arrayObj=new JSONArray();
   arrayObj.add("MCA");
   arrayObj.add("Amit Kumar");
   arrayObj.add("19-12-1986");
   arrayObj.add(24);
   arrayObj.add("Scored");
   arrayObj.add(new Double(66.67));
%>

Array Object is =>
 <%=arrayObj%>

<%  for(int i=0;i<arrayObj.size();i++){  %>
          <%=arrayObj.getString(i)%>
<%
  }
%>

the error I am getting is this

org.apache.jasper.JasperException: Unable to compile class for JSP:

An error occurred at line: 6 in the generated java file
Only a type can be imported. net.sf.json.JSONArray resolves to a package

An error occurred at line: 19 in the jsp file: /index.jsp
JSONArray cannot be resolved to a type
16:         <%@ page language="java" import="net.sf.json.JSONArray" %>
17:
18:         <%
19:         JSONArray arrayObj=new JSONArray();
20:         arrayObj.add("MCA");
21:          arrayObj.add("Amit Kumar");
22:          arrayObj.add("19-12-1986");

An error occurred at line: 19 in the jsp file: /index.jsp
JSONArray cannot be resolved to a type
16:         <%@ page language="java" import="net.sf.json.JSONArray" %>
17:
18:         <%
19:         JSONArray arrayObj=new JSONArray();
20:         arrayObj.add("MCA");
21:          arrayObj.add("Amit Kumar");
22:          arrayObj.add("19-12-1986");

How to debug this error ? I have downloaded the Json library and have put it in Tomcat/webapps/star/WEB-INF/lib.

Where star is the folder that contains the jsp page.


问:
Visual Studio for mac iOS storyboard not working
I'm using Visual Studio for mac for my Xamarin project. and also I'm using Xamarin Studio, because of few bugs.

I tried to edit iOS Package's Launchscreen.storyboard file, but it didn't work. It says "The designer could not be initialized.". and Error messages are too long... ;-;

So I edited it on Xcode. I added Background Color and app's logo but after I built it, but the logo didn't came out.

答:
Editing storyboards in Visual Studio for Mac is not the only way to do it. VS for Mac is still in preview.

You can use Xamarin Studio side by side with VS for Mac. So you can edit storyboards in XS instead of VS for Mac.

Alternatively (and this is my personal preference) you can edit storyboards in XCode by using context menu on the storyboard file in Solution Explorer and choosing Open with -> XCode.

Here is a plugin for Xamarin Studio to open storyboards by default in XCode: https://github.com/colbylwilliams/DefaultDesigner

There is a video showing how to use XCode with Xamarin (start from 14:34)


问:
Reverse word of full sentence
I want to print string in reverse format:

Input:  My name is Archit Patel

Output: Patel Archit is name My.

I've tied the following but it displays as letaP tihcrA si eman ym.

```<code>public static string ReverseString(string s)
{
    char[] arr = s.ToCharArray();
    Array.Reverse(arr);
    return new string(arr);
}
</code>```

答:
I appreciate Rob Anderson answer, but it will reverse complete sentence,
Just editing that

```<code>string s = "My name is Archit Patel";

        string[] words = s.Split(' ');
        StringBuilder sb = new StringBuilder();

        for (int i = words.Length - 1; i >= 0; i--)
        {
            sb.Append(words[i]);
            sb.Append(" ");
        }

        Console.WriteLine(sb);
</code>```

O/P will be "Patel Archit is name My"

Title: Reverse word of full sentence

Body:
I want to print string in reverse format:

Input:  My name is Archit Patel

Output: Patel Archit is name My.

I've tied the following but it displays as letaP tihcrA si eman ym.

public static string ReverseString(string s)
{
    char[] arr = s.ToCharArray();
    Array.Reverse(arr);
    return new string(arr);
}

Body:
I appreciate Rob Anderson answer, but it will reverse complete sentence,
Just editing that

string s = "My name is Archit Patel";

        string[] words = s.Split(' ');
        StringBuilder sb = new StringBuilder();

        for (int i = words.Length - 1; i >= 0; i--)
        {
            sb.Append(words[i]);
            sb.Append(" ");
        }

        Console.WriteLine(sb);

O/P will be "Patel Archit is name My"


问:
F# Performance Impact of Checked Calcs?
Is there a performance impact from using the Checked module?  I've tested it out with sequences of type int and see no noticeable difference.  Sometimes the checked version is faster and sometimes unchecked is faster, but generally not by much.

```<code>Seq.initInfinite (fun x-> x) |> Seq.item 1000000000;;
</code>```

```<code>Real: 00:00:05.272, CPU: 00:00:05.272, GC gen0: 0, gen1: 0, gen2: 0
val it : int = 1000000000
</code>```

```<code>open Checked

Seq.initInfinite (fun x-> x) |> Seq.item 1000000000;;
</code>```

```<code>Real: 00:00:04.785, CPU: 00:00:04.773, GC gen0: 0, gen1: 0, gen2: 0
val it : int = 1000000000
</code>```

Basically I'm trying to figure out if there would be any downside to always opening Checked.  (I encountered an overflow that wasn't immediately obvious, so I'm now playing the role of the jilted lover who doesn't want another broken heart.)  The only non-contrived reason I can come up with for not always using Checked is if there were some performance hit, but I haven't seen one yet.

答:
When you measure performance it's usually not a good idea to include Seq as Seq adds lots of overhead (at least compared to int operations) so you risk that most of the time is spent in Seq, not in the code you like to test.

I wrote a small test program for (+):

```<code>let clock =
  let sw = System.Diagnostics.Stopwatch ()
  sw.Start ()
  fun () ->
    sw.ElapsedMilliseconds

let dbreak () = System.Diagnostics.Debugger.Break ()

let time a =
  let b = clock ()
  let r = a ()
  let n = clock ()
  let d = n - b
  d, r

module Unchecked =
  let run c () =
    let rec loop a i =
      if i < c then
        loop (a + 1) (i + 1)
      else
        a
    loop 0 0

module Checked =
  open Checked

  let run c () =
    let rec loop a i =
      if i < c then
        loop (a + 1) (i + 1)
      else
        a
    loop 0 0

[<EntryPoint>]
let main argv =
  let count     = 1000000000
  let testCases =
    [|
      "Unchecked" , Unchecked.run
      "Checked"   , Checked.run
    |]

  for nm, a in testCases do
    printfn "Running %s ..." nm
    let ms, r = time (a count)
    printfn "... it took %d ms, result is %A" ms r

  0
</code>```

The performance results are this:

```<code>Running Unchecked ...
... it took 561 ms, result is 1000000000
Running Checked ...
... it took 1103 ms, result is 1000000000
</code>```

So it seems some overhead is added by using Checked. The cost of int add should be less than the loop overhead so the overhead of Checked is higher than 2x maybe closer to 4x.

Out of curiousity we can check the IL Code using tools like ILSpy:

Unchecked:

```<code>    IL_0000: nop
    IL_0001: ldarg.2
    IL_0002: ldarg.0
    IL_0003: bge.s IL_0014

    IL_0005: ldarg.0
    IL_0006: ldarg.1
    IL_0007: ldc.i4.1
    IL_0008: add
    IL_0009: ldarg.2
    IL_000a: ldc.i4.1
    IL_000b: add
    IL_000c: starg.s i
    IL_000e: starg.s a
    IL_0010: starg.s c
    IL_0012: br.s IL_0000
</code>```

Checked:

```<code>    IL_0000: nop
    IL_0001: ldarg.2
    IL_0002: ldarg.0
    IL_0003: bge.s IL_0014

    IL_0005: ldarg.0
    IL_0006: ldarg.1
    IL_0007: ldc.i4.1
    IL_0008: add.ovf
    IL_0009: ldarg.2
    IL_000a: ldc.i4.1
    IL_000b: add.ovf
    IL_000c: starg.s i
    IL_000e: starg.s a
    IL_0010: starg.s c
    IL_0012: br.s IL_0000
</code>```

The only difference is that Unchecked uses add and Checked uses add.ovf. add.ovf is add with overflow check.

We can dig even deeper by looking at the jitted x86_64 code.

Unchecked:

```<code>; if i < c then
00007FF926A611B3  cmp         esi,ebx
00007FF926A611B5  jge         00007FF926A611BD
; i + 1
00007FF926A611B7  inc         esi
; a + 1
00007FF926A611B9  inc         edi
; loop (a + 1) (i + 1)
00007FF926A611BB  jmp         00007FF926A611B3
</code>```

Checked:

```<code>; if i < c then
00007FF926A62613  cmp         esi,ebx
00007FF926A62615  jge         00007FF926A62623
; a + 1
00007FF926A62617  add         edi,1
; Overflow?
00007FF926A6261A  jo          00007FF926A6262D
; i + 1
00007FF926A6261C  add         esi,1
; Overflow?
00007FF926A6261F  jo          00007FF926A6262D
; loop (a + 1) (i + 1)
00007FF926A62621  jmp         00007FF926A62613
</code>```

Now the reason for the Checked overhead is visible. After each operation the jitter inserts the conditional instruction jo which jumps to code that raises OverflowException if the overflow flag is set.

This chart shows us that the cost of an integer add is less than 1 clock cycle. The reason it's less than 1 clock cycle is that modern CPU can execute certain instructions in parallel.

The chart also shows us that branch that was correctly predicted by the CPU takes around 1-2 clock cycles.

So assuming a throughtput of at least 2 the cost of two integer additions in the Unchecked example should be 1 clock cycle.

In the Checked example we do add, jo, add, jo. Most likely CPU can't parallelize in this case and the cost of this should be around 4-6 clock cycles.

Another interesting difference is that the order of additions changed. With checked additions the order of the operations matter but with unchecked the jitter (and the CPU) has a greater flexibility moving the operations possibly improving performance.

So long story short; for cheap operations like (+) the overhead of Checked should be around 4x-6x compared to Unchecked.

This assumes no overflow exception. The cost of a .NET exception is probably around 100,000x times more expensive than an integer addition.

Title: F# Performance Impact of Checked Calcs?

Body:
Is there a performance impact from using the Checked module?  I've tested it out with sequences of type int and see no noticeable difference.  Sometimes the checked version is faster and sometimes unchecked is faster, but generally not by much.

Seq.initInfinite (fun x-> x) |> Seq.item 1000000000;;

Real: 00:00:05.272, CPU: 00:00:05.272, GC gen0: 0, gen1: 0, gen2: 0
val it : int = 1000000000

open Checked

Seq.initInfinite (fun x-> x) |> Seq.item 1000000000;;

Real: 00:00:04.785, CPU: 00:00:04.773, GC gen0: 0, gen1: 0, gen2: 0
val it : int = 1000000000

Basically I'm trying to figure out if there would be any downside to always opening Checked.  (I encountered an overflow that wasn't immediately obvious, so I'm now playing the role of the jilted lover who doesn't want another broken heart.)  The only non-contrived reason I can come up with for not always using Checked is if there were some performance hit, but I haven't seen one yet.

Body:
When you measure performance it's usually not a good idea to include Seq as Seq adds lots of overhead (at least compared to int operations) so you risk that most of the time is spent in Seq, not in the code you like to test.

I wrote a small test program for (+):

let clock =
  let sw = System.Diagnostics.Stopwatch ()
  sw.Start ()
  fun () ->
    sw.ElapsedMilliseconds

let dbreak () = System.Diagnostics.Debugger.Break ()

let time a =
  let b = clock ()
  let r = a ()
  let n = clock ()
  let d = n - b
  d, r

module Unchecked =
  let run c () =
    let rec loop a i =
      if i < c then
        loop (a + 1) (i + 1)
      else
        a
    loop 0 0

module Checked =
  open Checked

  let run c () =
    let rec loop a i =
      if i < c then
        loop (a + 1) (i + 1)
      else
        a
    loop 0 0

[<EntryPoint>]
let main argv =
  let count     = 1000000000
  let testCases =
    [|
      "Unchecked" , Unchecked.run
      "Checked"   , Checked.run
    |]

  for nm, a in testCases do
    printfn "Running %s ..." nm
    let ms, r = time (a count)
    printfn "... it took %d ms, result is %A" ms r

  0

The performance results are this:

Running Unchecked ...
... it took 561 ms, result is 1000000000
Running Checked ...
... it took 1103 ms, result is 1000000000

So it seems some overhead is added by using Checked. The cost of int add should be less than the loop overhead so the overhead of Checked is higher than 2x maybe closer to 4x.

Out of curiousity we can check the IL Code using tools like ILSpy:

Unchecked:

    IL_0000: nop
    IL_0001: ldarg.2
    IL_0002: ldarg.0
    IL_0003: bge.s IL_0014

    IL_0005: ldarg.0
    IL_0006: ldarg.1
    IL_0007: ldc.i4.1
    IL_0008: add
    IL_0009: ldarg.2
    IL_000a: ldc.i4.1
    IL_000b: add
    IL_000c: starg.s i
    IL_000e: starg.s a
    IL_0010: starg.s c
    IL_0012: br.s IL_0000

Checked:

    IL_0000: nop
    IL_0001: ldarg.2
    IL_0002: ldarg.0
    IL_0003: bge.s IL_0014

    IL_0005: ldarg.0
    IL_0006: ldarg.1
    IL_0007: ldc.i4.1
    IL_0008: add.ovf
    IL_0009: ldarg.2
    IL_000a: ldc.i4.1
    IL_000b: add.ovf
    IL_000c: starg.s i
    IL_000e: starg.s a
    IL_0010: starg.s c
    IL_0012: br.s IL_0000

The only difference is that Unchecked uses add and Checked uses add.ovf. add.ovf is add with overflow check.

We can dig even deeper by looking at the jitted x86_64 code.

Unchecked:

; if i < c then
00007FF926A611B3  cmp         esi,ebx
00007FF926A611B5  jge         00007FF926A611BD
; i + 1
00007FF926A611B7  inc         esi
; a + 1
00007FF926A611B9  inc         edi
; loop (a + 1) (i + 1)
00007FF926A611BB  jmp         00007FF926A611B3

Checked:

; if i < c then
00007FF926A62613  cmp         esi,ebx
00007FF926A62615  jge         00007FF926A62623
; a + 1
00007FF926A62617  add         edi,1
; Overflow?
00007FF926A6261A  jo          00007FF926A6262D
; i + 1
00007FF926A6261C  add         esi,1
; Overflow?
00007FF926A6261F  jo          00007FF926A6262D
; loop (a + 1) (i + 1)
00007FF926A62621  jmp         00007FF926A62613

Now the reason for the Checked overhead is visible. After each operation the jitter inserts the conditional instruction jo which jumps to code that raises OverflowException if the overflow flag is set.

This chart shows us that the cost of an integer add is less than 1 clock cycle. The reason it's less than 1 clock cycle is that modern CPU can execute certain instructions in parallel.

The chart also shows us that branch that was correctly predicted by the CPU takes around 1-2 clock cycles.

So assuming a throughtput of at least 2 the cost of two integer additions in the Unchecked example should be 1 clock cycle.

In the Checked example we do add, jo, add, jo. Most likely CPU can't parallelize in this case and the cost of this should be around 4-6 clock cycles.

Another interesting difference is that the order of additions changed. With checked additions the order of the operations matter but with unchecked the jitter (and the CPU) has a greater flexibility moving the operations possibly improving performance.

So long story short; for cheap operations like (+) the overhead of Checked should be around 4x-6x compared to Unchecked.

This assumes no overflow exception. The cost of a .NET exception is probably around 100,000x times more expensive than an integer addition.


问:
How to install both Python 2.x and Python 3.x in Windows
I do most of my programming in Python 3.x on Windows 7, but now I need to use the Python Imaging Library (PIL), ImageMagick, and wxPython, all of which require Python 2.x.

Can I have both Python 2.x and Python 3.x installed in Windows 7? When I run a script, how would I "choose" which version of Python should run it? Will the aforementioned programs be able to handle multiple versions of Python installed at once? I have searched for hours and hours for how to do this to no avail.

Thanks.

答:
I have installed both python 2.7.13 and python 3.6.1 on windows 10pro and I was getting the same "Fatal error" when I tried pip2 or pip3.

What I did to correct this was to go to the location of python.exe for python 2 and python 3 files and create a copy of each, I then renamed each copy to python2.exe and python3.exe depending on the python version in the installation folder. I therefore had in each python installation folder both a python.exe file and a python2.exe or python3.exe depending on the python version.

This resolved my problem when I typed either pip2 or pip3.

ContentLicense: CC BY-SA 4.0


问: Are

答: Yes,

Title: Are <script>'s not in <head> ok?

Body:
I have had this question niggling at the curious bit of my mind for a while now and I thought I'd ask your collective expertise for an answer to this question.

To elaborate on the title, say I have this:

alert("Some JS outside ");

Outside the  tags of my HTML file. My question is whether it's ok to do this or not, and how much it is used like this.

My instincts tell me it's ok - I reckon browsers look through all HTML for

Body:
Yes, <script> blocks outside the <head> are fine.

In fact many encourage placing them at the end of the <body>.  Placing them just before </body>, defers fetching/loading until after the page content...to speed up the render.

From the W3C HTML4 spec:

The SCRIPT element places a script within a document. This element may appear any number of times in the HEAD or BODY of an HTML document.


问:
python script to download youtube video
On giving youtube video url, I first download video page and extract javascript object between

```<code><script>var ytplayer = ytplayer .....  </script>
</code>```

I got

```<code>{

    "args": {
        "is_listed": "1",
        "account_playback_token": "QUFFLUhqbWdXR1NfQjRiRmNzWVhRVTM0ajlNcnM1alVUd3xBQ3Jtc0tsVi01WFp5VmV2MTU3RnpkYUVkRzVqR1ZTNUI4T2JaQzk1ckxPejdVNkYzUk5zOTdjZnNmb1BYZHNLQ05nblZZbFk2ZWJXNHRPNVFoNVVNc2RjTE1YekdKSGY4dlVhSnlCU1ctNFZJdXBKbWhIRG1TZw==",
        "ptk": "RajshriEntertainment",
        "focEnabled": "1",
        "tag_for_child_directed": false,
        "adaptive_fmts": ......,
        "probe_url": .....,
        "rmktEnabled": "1",
        "allow_ratings": "1",
        "dbp": "ChoKFk5RNTV5UGs5bDZmSk5wSjQ4a3RiSHcQARABGAI",
        "cc3_module": "1",
        "no_get_video_log": "1",
        "fmt_list": ......,
        "title":..........,
        "invideo": true,
        "sffb": true,
        "iurlmq_webp": ,
        "cosver": "10_8_4",
        "url_encoded_fmt_stream_map": .................,
        "max_dynamic_allocation_ad_tag_length": "2040",
        "innertube_api_key": "AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8",
        "timestamp": "1446586407",
        "cc_asr": "1",
        "apiary_host_firstparty": "",
        "adsense_video_doc_id": "yt_Vd4iNPuRlx4",
        "innertube_context_client_version": "1.20151102",
        "mpu": true,
        "tmi": "1",
        "ldpj": "-19",
        "fade_out_duration_milliseconds": "1000",
        .........
 }
}
</code>```

i found key adaptive_fmts and url_encoded_fmt_stream_map contain multiple url in percent-encoded form.
i take one url from url_encoded_fmt_stream_map it look like this

```<code>https://r1---sn-o3o-qxal.googlevideo.com/videoplayback?
ratebypass=yes&
signature=982E413BBE08CA5801420F9696E0F2ED691B99FA.D666D39D1A0AF066F76F12632A10D3B8076076CE&
lmt=1443906393476832&
expire=1446604919&
fexp=9406983%2C9408710%2C9414764%2C9416126%2C9417707%2C9421410%2C9422596%2C9423663&
itag=22&
dur=128.801&
source=youtube&
upn=pk2CEhVBeFM&
sver=3&
key=yt6&
id=o-AK-OlE5NUsbkp51EZY2yKuz5vsSGofgUvrvTtOrhC72e&
sparams=dur%2Cid%2Cinitcwndbps%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpl%2Cratebypass%2Crequiressl%2Csource%2Cupn%2Cexpire&
mime=video%2Fmp4&
ipbits=0&
pl=21&
ip=x.y.z.a&
initcwndbps=5405000&
requiressl=yes&
mn=sn-o3o-qxal&
mm=31&
ms=au&
mv=m&
mt=1446583222&
itag=22&
type=video/mp4
</code>```

but when I paste this(above) url in browser nothing happen, I mean not work.
Please help me.

Also

What is difference between adaptive_fmts and url_encoded_fmt_stream_map containing urls?

答:
In python2.7, this works:</p>

```<code>import urlparse, urllib2

vid        = "vzS1Vkpsi5k"
save_title = "YouTube SpaceX - Booster Number 4 - Thaicom 8 06-06-2016"
url_init   = "https://www.youtube.com/get_video_info?video_id=" + vid

resp = urllib2.urlopen(url_init, timeout=10)
data = resp.read()
info =  urlparse.parse_qs(data)
title = info['title']

print "length:  ", info['length_seconds'][0] + " seconds"

stream_map   = info['adaptive_fmts'][0]
vid_info     = stream_map.split(",")

mp4_filename = save_title + ".mp4"

for video in vid_info:
    item = urlparse.parse_qs(video)

    #print 'quality: ', item['quality'][0]
    #print 'type:    ', item['type'][0]

    url_download  = item['url'][0]
    resp          = urllib2.urlopen(url_download)

    print resp.headers

    length  = int(resp.headers['Content-Length'])
    my_file = open(mp4_filename, "w+")

    done, i = 0, 0
    buff    = resp.read(1024)
    while buff:

        my_file.write(buff)
        done += 1024
        percent = done * 100.0 / length
        buff = resp.read(1024)

        if not i%1000:
            percent = done * 100.0 / length
            print str(percent) + "%"

        i += 1
    break
</code>```

Title: python script to download youtube video

Body:
On giving youtube video url, I first download video page and extract javascript object between

I got

{

    "args": {
        "is_listed": "1",
        "account_playback_token": "QUFFLUhqbWdXR1NfQjRiRmNzWVhRVTM0ajlNcnM1alVUd3xBQ3Jtc0tsVi01WFp5VmV2MTU3RnpkYUVkRzVqR1ZTNUI4T2JaQzk1ckxPejdVNkYzUk5zOTdjZnNmb1BYZHNLQ05nblZZbFk2ZWJXNHRPNVFoNVVNc2RjTE1YekdKSGY4dlVhSnlCU1ctNFZJdXBKbWhIRG1TZw==",
        "ptk": "RajshriEntertainment",
        "focEnabled": "1",
        "tag_for_child_directed": false,
        "adaptive_fmts": ......,
        "probe_url": .....,
        "rmktEnabled": "1",
        "allow_ratings": "1",
        "dbp": "ChoKFk5RNTV5UGs5bDZmSk5wSjQ4a3RiSHcQARABGAI",
        "cc3_module": "1",
        "no_get_video_log": "1",
        "fmt_list": ......,
        "title":..........,
        "invideo": true,
        "sffb": true,
        "iurlmq_webp": ,
        "cosver": "10_8_4",
        "url_encoded_fmt_stream_map": .................,
        "max_dynamic_allocation_ad_tag_length": "2040",
        "innertube_api_key": "AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8",
        "timestamp": "1446586407",
        "cc_asr": "1",
        "apiary_host_firstparty": "",
        "adsense_video_doc_id": "yt_Vd4iNPuRlx4",
        "innertube_context_client_version": "1.20151102",
        "mpu": true,
        "tmi": "1",
        "ldpj": "-19",
        "fade_out_duration_milliseconds": "1000",
        .........
 }
}

i found key adaptive_fmts and url_encoded_fmt_stream_map contain multiple url in percent-encoded form.
i take one url from url_encoded_fmt_stream_map it look like this

https://r1---sn-o3o-qxal.googlevideo.com/videoplayback?
ratebypass=yes&
signature=982E413BBE08CA5801420F9696E0F2ED691B99FA.D666D39D1A0AF066F76F12632A10D3B8076076CE&
lmt=1443906393476832&
expire=1446604919&
fexp=9406983%2C9408710%2C9414764%2C9416126%2C9417707%2C9421410%2C9422596%2C9423663&
itag=22&
dur=128.801&
source=youtube&
upn=pk2CEhVBeFM&
sver=3&
key=yt6&
id=o-AK-OlE5NUsbkp51EZY2yKuz5vsSGofgUvrvTtOrhC72e&
sparams=dur%2Cid%2Cinitcwndbps%2Cip%2Cipbits%2Citag%2Clmt%2Cmime%2Cmm%2Cmn%2Cms%2Cmv%2Cpl%2Cratebypass%2Crequiressl%2Csource%2Cupn%2Cexpire&
mime=video%2Fmp4&
ipbits=0&
pl=21&
ip=x.y.z.a&
initcwndbps=5405000&
requiressl=yes&
mn=sn-o3o-qxal&
mm=31&
ms=au&
mv=m&
mt=1446583222&
itag=22&
type=video/mp4

but when I paste this(above) url in browser nothing happen, I mean not work.
Please help me.

Also

What is difference between adaptive_fmts and url_encoded_fmt_stream_map containing urls?

Body:
In python2.7, this works:

import urlparse, urllib2

vid        = "vzS1Vkpsi5k"
save_title = "YouTube SpaceX - Booster Number 4 - Thaicom 8 06-06-2016"
url_init   = "https://www.youtube.com/get_video_info?video_id=" + vid

resp = urllib2.urlopen(url_init, timeout=10)
data = resp.read()
info =  urlparse.parse_qs(data)
title = info['title']

print "length:  ", info['length_seconds'][0] + " seconds"

stream_map   = info['adaptive_fmts'][0]
vid_info     = stream_map.split(",")

mp4_filename = save_title + ".mp4"

for video in vid_info:
    item = urlparse.parse_qs(video)

    #print 'quality: ', item['quality'][0]
    #print 'type:    ', item['type'][0]

    url_download  = item['url'][0]
    resp          = urllib2.urlopen(url_download)

    print resp.headers

    length  = int(resp.headers['Content-Length'])
    my_file = open(mp4_filename, "w+")

    done, i = 0, 0
    buff    = resp.read(1024)
    while buff:

        my_file.write(buff)
        done += 1024
        percent = done * 100.0 / length
        buff = resp.read(1024)

        if not i%1000:
            percent = done * 100.0 / length
            print str(percent) + "%"

        i += 1
    break


问:
grep for a variable excluding the dot sign
I want to grep a variable excluding those that start with a dot sign. However choosing the -w option for entire word doesn't include a dot sign so instead of only selecting 4 55 48 it also selects 0.4 0.55 5.48.

e.g. $var=1565

input

```<code>A 3.00027 1565
B 3.00026 1565
C -1.1565 5000
</code>```

desired output

```<code>A 3.00027 1565
B 3.00026 1565
</code>```

I have seen solutions to grep for an exact pattern starting with grep, but that doesn't work with a variable.

I have tried adding a space sign before the variable as in lines below but it doesn't give desired output either.

```<code>grep -E -w " $var" input.txt > output.txt #results in empty output
grep -E -w "[:space:]|$var" input.txt > output.txt # gives solutions that include the dot sign
</code>```

答:
Because me like perl-regexes, i would to use overcomplicated regex:

```<code>grep -P "((?<=^)|(?<=\s))$var(?=(\s|$))"
</code>```

the regex will work even with -o and returns just the number without any spaces or like around. (uses non-caturing groups)

Body:
I want to grep a variable excluding those that start with a dot sign. However choosing the -w option for entire word doesn't include a dot sign so instead of only selecting 4 55 48 it also selects 0.4 0.55 5.48.

e.g. $var=1565

input

A 3.00027 1565
B 3.00026 1565
C -1.1565 5000

desired output

A 3.00027 1565
B 3.00026 1565

I have seen solutions to grep for an exact pattern starting with grep, but that doesn't work with a variable.

I have tried adding a space sign before the variable as in lines below but it doesn't give desired output either.

grep -E -w " $var" input.txt > output.txt #results in empty output
grep -E -w "[:space:]|$var" input.txt > output.txt # gives solutions that include the dot sign

Body:
Because me like perl-regexes, i would to use overcomplicated regex:

grep -P "((?<=^)|(?<=\s))$var(?=(\s|$))"

the regex will work even with -o and returns just the number without any spaces or like around. (uses non-caturing groups)


问:
redis zrank : Floating-Point Numbers May Lose Precision
When I push score value length longer than 16 .

like 10000000000000000..

Then rank of sortedset get wrong .

How make it support 48 ?
or make it support string rank somehow ?

答: Scores are floating point values. These use the IEEE 754 standard and have finite precision. There is no way to increase the score's precision.</p>


问:
pdfkit generates small scaled pdfs
I am using pdfkit in order to generate pdfs from html strings, rendered by my Django's views.

For some reason, the output pdf is small.
My pdfkit option dictionary is -

```<code>options = {
            'quiet': '',
            'page-size': 'A4',
            'margin-top': '0.75in',
            'margin-right': '0.75in',
            'margin-bottom': '0.75in',
            'margin-left': '0.75in',
            'disable-smart-shrinking': ''
        }
</code>```

and the output file is here

Html code is -

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="pdfkit-orientation" content="Portrait"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Dribble</title>

    <!-- Bootstrap -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
    <!-- Google Font -->
    <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,700,800" rel="stylesheet">
    <!-- Custom Font -->
    <style>
        body {
            font-family: 'Open Sans', sans-serif;

        }

        p, a {
            color: #002f54;
        }

        .nav {
            background: #002f54;
            color: #FFFFFF;
            border-radius: 5px;
        }

        .ico {
            padding-right: 5px;
            top: 3px;
        }

        .nav > li p {
            text-align: center;
            font-size: 36px;
            font-weight: 800;
        }

        .right-align {
            float: right;
        }

        .pad-mar {
            font-size: 18px;
            padding-top: 10px;
            padding-bottom: 10px;
            margin-left: 30px !important;
            margin-right: 30px;
        }

        .pad-mar-middle {
            font-size: 18px;
            padding-top: 78px;
            padding-bottom: 25px;
            margin-left: 30px !important;
            margin-right: 30px;
        }

        .pad-mar-bottom {
            font-size: 18px;
            padding-top: 10px;
            padding-bottom: 90px;
            margin-left: 30px !important;
            margin-right: 30px;
        }

        .pad-mar-footer {
            padding-top: 20px;
            margin-left: 30px !important;
            margin-right: 30px;
        }

        .bor-bottom {
            border-bottom: 2px solid #ccc;
        }

        .no-pad {
            padding-left: 0;
        }

        .section {
            margin-top: 20px;
            margin-bottom: 20px;
        }

        .bold {
            font-weight: 700;
            color: #002f54;
        }

        .small {
            font-size: 14px;
        }

        .bolder {
            color: #002f54;
            font-weight: 800;
            font-size: 22px;
        }

        .normal {
            color: #002f54;
            font-weight: 700;
        }

        .smaller {
            font-size: 14px;
            font-weight: 700;
        }

        h3 .bold {
            margin-top: 0;
        }

        .neg-mar {
            margin-top: -25px;
        }

        .cus-img {
            max-width: 85px;
            margin-bottom: 10px;
        }

        .nav-stacked.mob > li {
            font-size: 16px;
            margin-left: 0px !important;
            margin-right: 0px;
            margin-bottom: 10px;
            padding-top: 5px;
            border: 1px solid #EB6C6D;
            border-radius: 5px;
            font-weight: 300;
            text-align: center;
            color: #EB6C6D;
        }

        .nav-stacked.mob > li p {
            color: #002f54;
        }

        .nav.mob {
            background: #FFFFFF;
        }

        .pad-mar-bottom.mob {
            margin-left: 0px !important;
            padding-bottom: 10px;
        }

        .pad-mar-footer.mob {
            margin-left: 0px !important;
            text-align: center;
            padding-top: 10px;
        }

        .l-mar {
            margin-left: 40px;
        }

        .titl {
            color: #EB6C6D;
            font-size: 16px;
        }

        .bot-mar {
            margin-bottom: 20px;
        }

        .container {
            max-width: 575px;
        }
    </style>

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<body>
<section class="section">
    <div class="container">

        <div class="row bor-bottom bot-mar">
            <div class="col-xs-6 ">
                <img src="https://api.figo.me/assets/images/accounts/north_channel_bank_144.png"
                     class="img-responsive cus-img"/>
                <p> Commerzbank Service-BZ</p>
                <p>First line</p>
            </div>
            <div class="col-xs-6">
                <div class="right-align neg-mar">
                    <h3 class="bold">First line</h3>
                    <p class="bold">First line</p>
                    <p class="bold">First line</p>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="">
                <ul class="nav nav-stacked mob">
                    <li><span class="glyphicon glyphicon glyphicon-user ico"></span>From<p>Rewe GmbH</p></li>
                    <li><span class="glyphicon glyphicon glyphicon-credit-card ico"></span>Amount<p>$ 32,10 USD</p></li>
                    <li><span class="glyphicon glyphicon glyphicon-calendar ico"></span>Payment Date<p>Nov 5, 2017</p>
                    </li>
                </ul>
            </div>
        </div>

        <div class="row pad-mar-bottom mob bor-bottom">
            <p class="titl"><span class="glyphicon glyphicon-tag ico"></span>Payment Reference</p>
            <div class="l-mar">
                <p class="normal">Hello Ennio,</p>
                <p class="normal">You sent a payment of <span class="bolder">$20.00 USD</span> to Dribble. (<a
                        href="mailto:paypal@dribble.com">paypal@dribble.com</a>)</p>
                <div class="no-pad">
                    <p class="smaller">It may take a few moments for this transaction to appear in your account.</p>
                </div>
            </div>
        </div>
        <footer>
            <div class="row pad-mar-footer mob">
                <a class="smaller" href="#">This document was automatically generated by Koryo</a>
            </div>
        </footer>
    </div><!-- Container -->
</section>

<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

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

答:
I had this same issue. I just changed the default configuration:</p>

```<code>PDFKit.configure do |config|
    config.default_options = {
        page_size: 'A4',
        print_media_type: true,
        dpi: 400
    }
end
</code>```

Title: pdfkit generates small scaled pdfs

Body:
I am using pdfkit in order to generate pdfs from html strings, rendered by my Django's views.

For some reason, the output pdf is small.
My pdfkit option dictionary is -

options = {
            'quiet': '',
            'page-size': 'A4',
            'margin-top': '0.75in',
            'margin-right': '0.75in',
            'margin-bottom': '0.75in',
            'margin-left': '0.75in',
            'disable-smart-shrinking': ''
        }

and the output file is here

Html code is -

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="pdfkit-orientation" content="Portrait"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Dribble</title>

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

    <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,700,800" rel="stylesheet">

 Commerzbank Service-BZ

First line

First line

First line

First line

From
Rewe GmbH

Amount
$ 32,10 USD

Payment Date
Nov 5, 2017

Payment Reference

Hello Ennio,

You sent a payment of $20.00 USD to Dribble. (paypal@dribble.com)

It may take a few moments for this transaction to appear in your account.

                This document was automatically generated by Koryo

Body:
I had this same issue. I just changed the default configuration:

PDFKit.configure do |config|
    config.default_options = {
        page_size: 'A4',
        print_media_type: true,
        dpi: 400
    }
end


问:
Why am I getting so many br tags
I started writing html code and when I view it on chrome, the table is displayed after a long white space. When I inspect the element, on chrome, I get a lot of br tags but I have not given any br tags in the code

How come?

<!DOCTYPE html>

  <title> Practice </title>

 <big><big> Registration Form <big><big>

<form name="My Form" action="" method="">

 Username
 <input type="text" name="t1" size="6"/>

 Password
 <input type="password" name="t2" size="6"/>

 Name
 <input type="text" name="t3" size="30"/>

 Address
 <input type="text" name="t4" size="30"/>

 Country
<select name="s1">
<option> Select Your Country </option>
<option> Afghanistan </option>
<option> Bangladesh </option>
<option> China </option>
<option> India </option>
<option> Russia </option>
</select>

 Zip Code
 <input type="text" name="t5" size="6"/>

 Email
 <input type="text" name="t6" size="30"/>

Sex
<input type="radio" name="r1" value="100" checked/>Male
<input type="radio" name="r1" value="102"/>Female

Language
<input type="checkbox" name="r1" value="100" checked/>English
<input type="checkbox" name="r2" value="102"/>Non English

 About
<textarea name="a1" rows="5" cols="32"> </textarea>

<input type="submit" name="b2" value="submit here"/>

</form>

```

答:
You had a lot of LF in your page. You need to check your editor

Also you had invalid tags and missed CSS

Here is a fixed version that validates

<!DOCTYPE html>

  <title> Practice </title>

  <form name="MyForm">

Registration Form

        Username

          <input type="text" name="t1" size="6" />

        Password

          <input type="password" name="t2" size="6" />

        Name

          <input type="text" name="t3" size="30" />

        Address

          <input type="text" name="t4" size="30" />

        Country

          <select name="s1">
            <option> Select Your Country </option>
            <option> Afghanistan </option>
            <option> Bangladesh </option>
            <option> China </option>
            <option> India </option>
            <option> Russia </option>
          </select>

        Zip Code

          <input type="text" name="t5" size="6" />

        Email

          <input type="text" name="t6" size="30" />

        Gender

          <input type="radio" name="r1" value="100" checked/>Male
          <input type="radio" name="r1" value="102" />Female
          <input type="radio" name="r1" value="103" />Irrelevant

        Language

          <input type="checkbox" name="r1" value="100" checked/>English
          <input type="checkbox" name="r2" value="102" />Non English

        About

          <textarea name="a1" rows="5" cols="32"> </textarea>

          <input type="submit" name="b2" value="submit here" />

  </form>

```

Title: Why am I getting so many br tags

Body:
You had a lot of LF in your page. You need to check your editor

Also you had invalid tags and missed CSS

Here is a fixed version that validates

<!DOCTYPE html>
<html>

<head>
  <title> Practice </title>
  <style>
    table {
      border: 0.00001px;
      background-color: silver;
      margin: 0px auto;
    }

    caption {
      text-align: center;
      font-size: x-large;
    }

    .center {
      text-align: center;
    }
  </style>
</head>

<body>
  <form name="MyForm">
    <table>
      <caption>Registration Form</caption>
      <tr>
        <td>Username</td>
        <td>
          <input type="text" name="t1" size="6" /> </td>
      </tr>
      <tr>
        <td>Password</td>
        <td>
          <input type="password" name="t2" size="6" /> </td>
      </tr>
      <tr>
        <td>Name</td>
        <td>
          <input type="text" name="t3" size="30" /> </td>
      </tr>
      <tr>
        <td>Address</td>
        <td>
          <input type="text" name="t4" size="30" /> </td>
      </tr>
      <tr>
        <td>Country</td>
        <td>
          <select name="s1">
            <option> Select Your Country </option>
            <option> Afghanistan </option>
            <option> Bangladesh </option>
            <option> China </option>
            <option> India </option>
            <option> Russia </option>
          </select>
        </td>
      </tr>
      <tr>
        <td>Zip Code</td>
        <td>
          <input type="text" name="t5" size="6" /> </td>
      </tr>
      <tr>
        <td>Email</td>
        <td>
          <input type="text" name="t6" size="30" /> </td>
      </tr>
      <tr>
        <td>Gender</td>
        <td>
          <input type="radio" name="r1" value="100" checked/>Male
          <input type="radio" name="r1" value="102" />Female</td>
          <input type="radio" name="r1" value="103" />Irrelevant</td>
      </tr>
      <tr>
        <td>Language</td>
        <td>
          <input type="checkbox" name="r1" value="100" checked/>English
          <input type="checkbox" name="r2" value="102" />Non English</td>
      </tr>
      <tr>
        <td>About</td>
        <td>
          <textarea name="a1" rows="5" cols="32"> </textarea>
        </td>
      </tr>
      <tr>
        <td class="center" colspan="2">
          <input type="submit" name="b2" value="submit here" />
        </td>
      </tr>
    </table>
  </form>
</body>

</html>


问:
Disconnecting iTunes COM
I'm currently working with the iTunes COM with .NET, and something I came across previously, which stopped me using it, has happened again and I can't for the life of me figure it out.

When I go to close iTunes during or after my program has closed, it tells me something is still using the "Application Scripting Interface", COM is still connected.

This is what I have (removed what is not required)

```<code>    Private Sub frmMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
         AddHandler itunes.OnAboutToPromptUserToQuitEvent, AddressOf itunes_OnAboutToPromptUserToQuitEvent
    End Sub

    Private Sub itunes_OnAboutToPromptUserToQuitEvent()
        System.Runtime.InteropServices.Marshal.ReleaseComObject(itunes)
    End Sub
</code>```

So, the above code does disconnect the COM to the extent that I need to restart iTunes to use it again, but, it doesn't get rid of the Application Scripting error. Meaning, I still need to click quit after the error dialog comes up.  Everything else works fine, apart from this.

Any idea?

-- I've had a look at other questions that had this issue, but none of them resolved it for me. I'm not sure if the event doesn't work anymore with this current version of iTunes, but, it doesn't seem to work currently either way.

答:
Had same issue with COM and Office, this solved it;</p>

```<code>  While System.Runtime.InteropServices.Marshal.ReleaseComObject(itunes) <> 0
            Application.DoEvents()
        End While
</code>```

Title: Disconnecting iTunes COM

Body:
I'm currently working with the iTunes COM with .NET, and something I came across previously, which stopped me using it, has happened again and I can't for the life of me figure it out.

When I go to close iTunes during or after my program has closed, it tells me something is still using the "Application Scripting Interface", COM is still connected.

This is what I have (removed what is not required)

    Private Sub frmMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
         AddHandler itunes.OnAboutToPromptUserToQuitEvent, AddressOf itunes_OnAboutToPromptUserToQuitEvent
    End Sub

    Private Sub itunes_OnAboutToPromptUserToQuitEvent()
        System.Runtime.InteropServices.Marshal.ReleaseComObject(itunes)
    End Sub

So, the above code does disconnect the COM to the extent that I need to restart iTunes to use it again, but, it doesn't get rid of the Application Scripting error. Meaning, I still need to click quit after the error dialog comes up.  Everything else works fine, apart from this.

Any idea?

-- I've had a look at other questions that had this issue, but none of them resolved it for me. I'm not sure if the event doesn't work anymore with this current version of iTunes, but, it doesn't seem to work currently either way.

Body:
Had same issue with COM and Office, this solved it;

  While System.Runtime.InteropServices.Marshal.ReleaseComObject(itunes) <> 0
            Application.DoEvents()
        End While


问:
React can't be found
index.js:

```<code>import react from 'react';
import {render} from 'react-dom';

render(
    <h1>Hello World!</h1>,
    document.getElementById('root')
);
</code>```

package.json:

```<code>{
  "name": "",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server --progress --watch",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Callum Linington",
  "license": "ISC",
  "dependencies": {
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "whatwg-fetch": "^2.0.3"
  },
  "devDependencies": {
    "babel-cli": "^6.24.0",
    "babel-preset-es2015": "^6.24.0",
    "babel-preset-react": "^6.23.0",
    "babel-core": "^6.24.0",
    "babel-loader": "^6.4.1",
    "babel-preset-env": "^1.3.2",
    "bluebird": "^3.5.0",
    "eslint": "^3.19.0",
    "webpack": "^2.3.2",
    "webpack-dev-server": "^2.4.2"
  }
}
</code>```

Webpack config:

```<code>var webpack = require('webpack');
var packages = require('./package.json');
var path = require('path');

module.exports = {
    entry: {
        main: './src/index.js',
        vendor: Object.keys(packages.dependencies)
    },
    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'dist')
    },

    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor' // Specify the common bundle's name.
        })
    ],

    devtool: "cheap-eval-source-map",

    devServer: {
        contentBase: path.join(__dirname, "dist"),
        publicPath: '/',
        port: 9000
    },

    module: {
        rules: [
            {
                test: /\.js?$/,
                use: [ 'babel-loader', ],
                exclude: /node_modules/
            }
        ]
    }
};
</code>```

Webpack output:

Chrome Dev Output:

答: It is crutial to name imported React class starting with capital letter. You first line should be: import React from 'react';. That is because all JSX tags will be converted by Babel to something like React.createElement(....) and React is not there. Exactly what console output tells you.

Title: React can't be found

Body:
index.js:

import react from 'react';
import {render} from 'react-dom';

render(

Hello World!
,
    document.getElementById('root')
);

package.json:

{
  "name": "",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server --progress --watch",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Callum Linington",
  "license": "ISC",
  "dependencies": {
    "react": "^15.4.2",
    "react-dom": "^15.4.2",
    "whatwg-fetch": "^2.0.3"
  },
  "devDependencies": {
    "babel-cli": "^6.24.0",
    "babel-preset-es2015": "^6.24.0",
    "babel-preset-react": "^6.23.0",
    "babel-core": "^6.24.0",
    "babel-loader": "^6.4.1",
    "babel-preset-env": "^1.3.2",
    "bluebird": "^3.5.0",
    "eslint": "^3.19.0",
    "webpack": "^2.3.2",
    "webpack-dev-server": "^2.4.2"
  }
}

Webpack config:

var webpack = require('webpack');
var packages = require('./package.json');
var path = require('path');

module.exports = {
    entry: {
        main: './src/index.js',
        vendor: Object.keys(packages.dependencies)
    },
    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'dist')
    },

    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor' // Specify the common bundle's name.
        })
    ],

    devtool: "cheap-eval-source-map",

    devServer: {
        contentBase: path.join(__dirname, "dist"),
        publicPath: '/',
        port: 9000
    },

    module: {
        rules: [
            {
                test: /\.js?$/,
                use: [ 'babel-loader', ],
                exclude: /node_modules/
            }
        ]
    }
};

Webpack output:

Chrome Dev Output:


问:
Is there a maximum size to char[]?
IN JAVA

Is there a maximum size of char[]? Can I have a char[5,000,000]?

Is array in java composed of contiguous memory blocks?

答:
heap size of JVM is the limit.

as @wildcodeforjava mentioned int is the paremeter while initilizing array

so which ever is less.

Title: Is there a maximum size to char[]?


答:
Try this using correlated subquery with limit to find out the id of the first conversation between the given two people.

```<code>select *
from your_table t
where id = (
        select id
        from your_table t2
        where least(t.sender_id, t.recipient_id) = least(t2.sender_id, t2.recipient_id)
            and greatest(t.sender_id, t.recipient_id) = greatest(t2.sender_id, t2.recipient_id)
        order by id limit 1
        );
</code>```

Demo

Title: Get the first message of the conversations

Body:
Please help me to retrieve the first message of the each conversation.

Table: messages

id | sender_id | recipient_id | content      | Created_at
1  | 100       | 101          | AB           | 2017-03-20 22:37:30
2  | 101       | 100          | Hello        | 2017-03-21 20:29:10
3  | 101       | 100          | XYZ          | 2017-03-21 22:02:00
4  | 200       | 100          | xxt          | 2017-03-21 23:01:01
5  | 200       | 100          | Hi there     | 2017-03-22 10:10:10
6  | 102       | 500          | Can you meet?| 2017-03-22 10:15:32
7  | 600       | 700          | Yes          | 2017-03-22 10:20:30
8  | 600       | 700          | Hello world  | 2017-03-23 01:00:00
9  | 700       | 600          | Hi           | 2017-03-23 08:10:10
10 | 800       | 900          | hello        | 2017-03-26 22:00:00

Expected result:

id | sender_id | recipient_id | content      | Created_at
1  | 100       | 101          | AB           | 2017-03-20 22:37:30
4  | 200       | 100          | xxt          | 2017-03-21 23:01:01
6  | 102       | 500          | Can you meet?| 2017-03-22 10:15:32
7  | 600       | 700          | Yes          | 2017-03-22 10:20:30
10 | 800       | 900          | hello        | 2017-03-26 22:00:00

Thank you in advance.

Body:
Try this using correlated subquery with limit to find out the id of the first conversation between the given two people.

select *
from your_table t
where id = (
        select id
        from your_table t2
        where least(t.sender_id, t.recipient_id) = least(t2.sender_id, t2.recipient_id)
            and greatest(t.sender_id, t.recipient_id) = greatest(t2.sender_id, t2.recipient_id)
        order by id limit 1
        );

Demo


问:
@Transactional annotation not working
I am trying to save a TestEntity object in the database. The code is being executed and the Id for the entity is created, but the entity is not persisted to the database (no row inserted):

```<code>@Repository
public class DBConnectionConfig {
    @Autowired
    SessionFactory sessionFactory;
    DBConnectionConfig(){
        //this.sessionFactory=getSessionFactory();
    }
    /*private SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    private void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }*/
    public Session getSession(){
        return sessionFactory.openSession();
    }
}

package com.homecare.persistance.repository;
@Repository
@Transactional
public class HomeCareDaoImp extends DBConnectionConfig  implements HomeCareDao{
    Logger LOGGER=Logger.getLogger("Connection.class");
    Session session=null;
    Transaction trnx=null;
    @Autowired
    ApplicationContext ctx;
    @Autowired
    DBConnectionConfig dBConnectionConfig;
    public void doaProcess(TestEntity testEntity){
        LOGGER.info(dBConnectionConfig.toString());
        session=getSession();
        // trnx=session.beginTransaction();
        session.save(testEntity);
        // session.flush();
        // trnx.commit();
        LOGGER.info("connection established");
    }
}
</code>```

Removing the comments from the 3 lines (beginTransation, flush, commit) solves the problem, but why does the @Transactional annotation not work here?

Spring XML:

```<code><!-- Our service layer components -->
<context:component-scan base-package="com.homecare" />
<!-- <context:component-scan base-package="com.homecare.persistance.repository" /> -->

 <!-- enable @Transactional Annotation -->

<!-- data source with c3p0 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="org.postgresql.Driver" />
      <property name="url" value="jdbc:postgresql://localhost:5433/My_DB" />
      <property name="username" value="postgres" />
      <property name="password" value="password" />
   </bean>

   <bean id="SessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <property name="packagesToScan" value="com.homecare.persistance.resource"></property>   <!-- yet to defined place where to scan> -->
      <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
      <property name="sessionFactory" ref="SessionFactory" />
   </bean>
</beans>
</code>```

POM xml file:

```<code><dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>

<!-- spring framwork -->
<!-- Hibernate -->
       <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.11.Final</version>
       </dependency>
        <dependency>
           <groupId>net.sf.ehcache</groupId>
           <artifactId>ehcache-core</artifactId>
           <version>2.2.0</version>
       </dependency>
</code>```

答:
Hibernate session object used for save is not tied to transaction manager defined in spring config xml.

Define the sessionfactory object using autowired as

```<code>@Autowired
Private SessionFactory sessionFactory;
</code>```

And fetch session object as

```<code>Session session = sessionFactory.getCurrentSession();
</code>```

And now perform the session.save(object);

As per spring config in your code, sessionFactory is associated with transactionManager. So all the changes performed session (associated with transaction manager) will get committed in db when transaction completes successfully.

Title: @Transactional annotation not working

Body:
I am trying to save a TestEntity object in the database. The code is being executed and the Id for the entity is created, but the entity is not persisted to the database (no row inserted):

@Repository
public class DBConnectionConfig {
    @Autowired
    SessionFactory sessionFactory;
    DBConnectionConfig(){
        //this.sessionFactory=getSessionFactory();
    }
    /*private SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    private void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }*/
    public Session getSession(){
        return sessionFactory.openSession();
    }
}

package com.homecare.persistance.repository;
@Repository
@Transactional
public class HomeCareDaoImp extends DBConnectionConfig  implements HomeCareDao{
    Logger LOGGER=Logger.getLogger("Connection.class");
    Session session=null;
    Transaction trnx=null;
    @Autowired
    ApplicationContext ctx;
    @Autowired
    DBConnectionConfig dBConnectionConfig;
    public void doaProcess(TestEntity testEntity){
        LOGGER.info(dBConnectionConfig.toString());
        session=getSession();
        // trnx=session.beginTransaction();
        session.save(testEntity);
        // session.flush();
        // trnx.commit();
        LOGGER.info("connection established");
    }
}

Removing the comments from the 3 lines (beginTransation, flush, commit) solves the problem, but why does the @Transactional annotation not work here?

Spring XML:

<context:component-scan base-package="com.homecare" />

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="org.postgresql.Driver" />
      <property name="url" value="jdbc:postgresql://localhost:5433/My_DB" />
      <property name="username" value="postgres" />
      <property name="password" value="password" />
   </bean>

   <bean id="SessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <property name="packagesToScan" value="com.homecare.persistance.resource"></property>
      <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
      <property name="sessionFactory" ref="SessionFactory" />
   </bean>
</beans>

POM xml file:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>

       <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.11.Final</version>
       </dependency>
        <dependency>
           <groupId>net.sf.ehcache</groupId>
           <artifactId>ehcache-core</artifactId>
           <version>2.2.0</version>
       </dependency>

Body:
Hibernate session object used for save is not tied to transaction manager defined in spring config xml.

Define the sessionfactory object using autowired as

@Autowired
Private SessionFactory sessionFactory;

And fetch session object as

Session session = sessionFactory.getCurrentSession();

And now perform the session.save(object);

As per spring config in your code, sessionFactory is associated with transactionManager. So all the changes performed session (associated with transaction manager) will get committed in db when transaction completes successfully.


问:
Google places radar search with a radius greater than 50,000 meters
I'm trying to find all Panera restaurants within a 200 mile radius of a certain point.

Here is the URL I have been using so far :

```<code>https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=39.52963,-119.81380&radius=321869&type=restaurant&name=panera&key=your-key-here
</code>```

However, I have found out that radius has a maximum of 30 miles. Can anyone suggest a quick workaround for me?

Thanks to all in advance.

答:
Open Google Maps and save 8-10 or more points' lat,long value to trigger your request. Then use a loop to find all places within these points. If you want more precise results, increase first trigger points for your requests.

I tried, it works.

Assume we are using php

```<code>$triggerPoints = array("lat1,long1", "lat2,long2", "lat3,long3",....);

foreeach(triggerPoints as $t){
   $requestUrl = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$t&radius=[YOUR_RADIUS_VALUE]&type=restaurant&name=panera&key=your-key-here";
   $results = file_get_contents($requestUrl);
   //Do what you want with response JSON data

}
</code>```

Important: When you choose trigger points, those points should intersect according to your radius value. So you don't miss any restaurants

Body:
I'm trying to find all Panera restaurants within a 200 mile radius of a certain point.

Here is the URL I have been using so far :

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=39.52963,-119.81380&radius=321869&type=restaurant&name=panera&key=your-key-here

However, I have found out that radius has a maximum of 30 miles. Can anyone suggest a quick workaround for me?

Thanks to all in advance.

Body:
Open Google Maps and save 8-10 or more points' lat,long value to trigger your request. Then use a loop to find all places within these points. If you want more precise results, increase first trigger points for your requests.

I tried, it works.

Assume we are using php

$triggerPoints = array("lat1,long1", "lat2,long2", "lat3,long3",....);

foreeach(triggerPoints as $t){
   $requestUrl = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$t&radius=[YOUR_RADIUS_VALUE]&type=restaurant&name=panera&key=your-key-here";
   $results = file_get_contents($requestUrl);
   //Do what you want with response JSON data

}

Important: When you choose trigger points, those points should intersect according to your radius value. So you don't miss any restaurants


答: Yes, and yes as far as I know, I think the max in java is around 2,000,000,000 2*10e9</p>

Title: Is there a maximum size to char[]?

Body:
IN JAVA

Is there a maximum size of char[]? Can I have a char[5,000,000]?

Is array in java composed of contiguous memory blocks?


问:
Rails is not installing any gem
Whenever i try to install any gem and bundle install it it gives me:

following bundle instructions to bundle update rails(which i shouldn't do it suppose) i get:
<img src="https://i.stack.imgur.com/Hlh5K.png" alt="bundle update rails">

答:
STEPS TO RESOLVE THIS :-

Remove the Gemfile.lock

Run the bundle install.

Title: Rails is not installing any gem


问:
Build multiple where clauses with linq
I'm writing a dotnet core MVC web app with EntityFrameWorkCore and Sqlite.

I'm trying to build a dynamic where clause based on data provided by the query string, there could be multiple key value pairs passed in the query string and I want to add them all to the where clause, I thought I could do it like this but it returns me all rows from the initial query.

```<code>public class Application
{
    public Application()
    {
        Data = new List<Data>();
    }
    public int ApplicationId { get; set; }
    [Required][Display(Name = "Application Name")]
    public string Name { get; set; }
    public Guid PublicKey { get; set; }
    public Guid PrivateKey { get; set; }
    public bool HideFromSearch { get; set; }
    public DateTime InsertDate { get; set; }
    public List<Data> Data { get; set; }
}

public class Data
{
    public Data()
    {
        DataItems = new List<DataItem>();
    }
    public int DataId { get; set; }
    public int ApplicationId { get; set; }
    public DateTime InsertDate { get; set; }
    public List<DataItem> DataItems { get; set; }
}

public class DataItem
{
    public int DataItemId { get; set; }
    public int DataId { get; set; }
    public string PropertyName { get; set; }
    public string PropertyValue { get; set; }
}
</code>```

Where code

```<code>var apps = context.Applications.Include(app => app.Data).ThenInclude(data => data.DataItems).Where(app => app.PublicKey == publicKey);

foreach (var item in Request.Query)
{
    apps = apps.Where(q => q.Data.Any(r => r.DataItems.Any(s => s.PropertyName == item.Key && s.PropertyValue == item.Value[0] )));
}
</code>```

答:
I used Dynamic Linq in a project and think it is what you are looking for to solve complex dynamic queries.

Scott Guthrie sample

Nuget package

Title: Build multiple where clauses with linq

Body:
I'm writing a dotnet core MVC web app with EntityFrameWorkCore and Sqlite.

I'm trying to build a dynamic where clause based on data provided by the query string, there could be multiple key value pairs passed in the query string and I want to add them all to the where clause, I thought I could do it like this but it returns me all rows from the initial query.

public class Application
{
    public Application()
    {
        Data = new List<Data>();
    }
    public int ApplicationId { get; set; }
    [Required][Display(Name = "Application Name")]
    public string Name { get; set; }
    public Guid PublicKey { get; set; }
    public Guid PrivateKey { get; set; }
    public bool HideFromSearch { get; set; }
    public DateTime InsertDate { get; set; }
    public List<Data> Data { get; set; }
}

public class Data
{
    public Data()
    {
        DataItems = new List<DataItem>();
    }
    public int DataId { get; set; }
    public int ApplicationId { get; set; }
    public DateTime InsertDate { get; set; }
    public List<DataItem> DataItems { get; set; }
}

public class DataItem
{
    public int DataItemId { get; set; }
    public int DataId { get; set; }
    public string PropertyName { get; set; }
    public string PropertyValue { get; set; }
}

Where code

var apps = context.Applications.Include(app => app.Data).ThenInclude(data => data.DataItems).Where(app => app.PublicKey == publicKey);

foreach (var item in Request.Query)
{
    apps = apps.Where(q => q.Data.Any(r => r.DataItems.Any(s => s.PropertyName == item.Key && s.PropertyValue == item.Value[0] )));
}


问:
android vector background color transparent
My main layout look like this.

```<code><?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent"
    android:orientation="vertical"
    android:padding="0dp"
    tools:context="com.send.apk.bluetoothappsend.MainActivity">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/tool_bar" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="@drawable/background" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/_80sdp"
        android:background="@drawable/ic_footer" />
</LinearLayout>
</code>```

And I use following vector

```<code><vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="1124dp"
        android:height="306dp"
         android:tint="@android:color/transparent"
        android:viewportWidth="11240.0"
        android:viewportHeight="3060.0">
    <path
        android:pathData="M179,3046c-111,-20 -146,-55 -166,-170 -17,-96 -18,-1749 -2,-1861 18,-122 69,-172 194,-194 41,-7 417,-11 1126,-11 585,0 1168,-5 1294,-10 330,-14 760,-47 905,-70 415,-63 789,-207 1132,-437 277,-184 448,-251 718,-278 183,-19 297,-19 480,0 270,27 441,94 718,279 370,247 789,400 1238,451 462,52 862,65 2088,65 713,0 1090,4 1131,11 125,22 176,72 194,194 16,112 15,1765 -2,1861 -21,117 -54,150 -171,171 -100,17 -10778,17 -10877,-1z"
        android:strokeColor="#00000000"
        android:fillColor="#090b17"/>
</vector>
</code>```

But problem that , there exists some black background as picture , I need trasparent background

答:
Try like this </p>

```<code><?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent"
    android:orientation="vertical"
    android:padding="0dp"
    tools:context="com.send.apk.bluetoothappsend.MainActivity">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/tool_bar" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/background"
        android:orientation="vertical">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/rv"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="@dimen/_80sdp"
            android:background="@drawable/ic_footer" />
    </LinearLayout>

</LinearLayout>
</code>```

Body:
My main layout look like this.

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent"
    android:orientation="vertical"
    android:padding="0dp"
    tools:context="com.send.apk.bluetoothappsend.MainActivity">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/tool_bar" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="@drawable/background" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/_80sdp"
        android:background="@drawable/ic_footer" />
</LinearLayout>

And I use following vector

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="1124dp"
        android:height="306dp"
         android:tint="@android:color/transparent"
        android:viewportWidth="11240.0"
        android:viewportHeight="3060.0">
    <path
        android:pathData="M179,3046c-111,-20 -146,-55 -166,-170 -17,-96 -18,-1749 -2,-1861 18,-122 69,-172 194,-194 41,-7 417,-11 1126,-11 585,0 1168,-5 1294,-10 330,-14 760,-47 905,-70 415,-63 789,-207 1132,-437 277,-184 448,-251 718,-278 183,-19 297,-19 480,0 270,27 441,94 718,279 370,247 789,400 1238,451 462,52 862,65 2088,65 713,0 1090,4 1131,11 125,22 176,72 194,194 16,112 15,1765 -2,1861 -21,117 -54,150 -171,171 -100,17 -10778,17 -10877,-1z"
        android:strokeColor="#00000000"
        android:fillColor="#090b17"/>
</vector>

But problem that , there exists some black background as picture , I need trasparent background

Body:
Try like this

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent"
    android:orientation="vertical"
    android:padding="0dp"
    tools:context="com.send.apk.bluetoothappsend.MainActivity">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/tool_bar" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/background"
        android:orientation="vertical">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/rv"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="@dimen/_80sdp"
            android:background="@drawable/ic_footer" />
    </LinearLayout>

</LinearLayout>


问:
A loss of precision
If I have a double string which is equal to "123.546123" and convert it to a double with atof, I get only 123.546. What can I do to fix this?

Here is my code:

```<code>#include <iostream>

int main(){

    std::string a = "123.546123";
    double b = atof(a.c_str());

    std::cout << a << std::endl;
    std::cout << b << std::endl;

    return EXIT_SUCCESS;
}
</code>```

答:
std::cout prints floating-point values with a precision of 6 by default. To increase that precision, use std::setprecision from <iomanip>, e.g.:

```<code>std::cout << std::setprecision(9) << b << std::endl;
</code>```

Title: A loss of precision

Body:
If I have a double string which is equal to "123.546123" and convert it to a double with atof, I get only 123.546. What can I do to fix this?

Here is my code:

#include <iostream>

int main(){

    std::string a = "123.546123";
    double b = atof(a.c_str());

    std::cout << a << std::endl;
    std::cout << b << std::endl;

    return EXIT_SUCCESS;
}

Body:
std::cout prints floating-point values with a precision of 6 by default. To increase that precision, use std::setprecision from <iomanip>, e.g.:

std::cout << std::setprecision(9) << b << std::endl;