问:
Is there a way to change column name before fetching data?
Is there a way to change column name before fetching data in all the controllers I call that column from, for example I had 2 columns in my table "Section" : "Title" and "TitleEN"

If the current culture is "en", I want to fetch "TitleEn" data but in my code I'll only use "Title" like this:

```<code>      section.Where(p =>
      p.Title.ToUpper().Contains(searchword.ToUpper()));
</code>```

I was working on a project with only one language and then the client requested adding English. Unfortunately I made the wrong decision by adding language fields for every table having string fields.

Now I want to fix this because the project has a lot of code dealing only with fields without "En".

答:
not the best solution, but you can just use an If currentcul is En, then

```<code> section.Where(p =>
      p.TitleEN.ToUpper().Contains(searchword.ToUpper()));
    Else{
section.Where(p =>
      p.Title.ToUpper().Contains(searchword.ToUpper()));
    }
</code>```

I would recommend using a diffrent solution tho.

Body:
Is there a way to change column name before fetching data in all the controllers I call that column from, for example I had 2 columns in my table "Section" : "Title" and "TitleEN"

If the current culture is "en", I want to fetch "TitleEn" data but in my code I'll only use "Title" like this:

      section.Where(p =>
      p.Title.ToUpper().Contains(searchword.ToUpper()));

I was working on a project with only one language and then the client requested adding English. Unfortunately I made the wrong decision by adding language fields for every table having string fields.

Now I want to fix this because the project has a lot of code dealing only with fields without "En".

Body:
not the best solution, but you can just use an If currentcul is En, then

 section.Where(p =>
      p.TitleEN.ToUpper().Contains(searchword.ToUpper()));
    Else{
section.Where(p =>
      p.Title.ToUpper().Contains(searchword.ToUpper()));
    }

I would recommend using a diffrent solution tho.


来源: stackexchange

问:
Can I install more than one instance of ClickHouse database on a single server using different user
I have ClickHouse already installed on my server(Ubuntu 14.04 LTS) using root, and now can i install it on the same server with another user, and if yes then please provide necessary steps to install it.</p>

答:
I don't think that you can install clickhouse with different user. (because installations will have conflicting ports 9000, 8123, etc.)

I believe the best way to do this is use docker image https://hub.docker.com/r/yandex/clickhouse-server and configure different volume directories and port bindings.

ContentLicense: CC BY-SA 3.0


问:
use RxSwift, driver and bind to
I'm the first time to ask a question，I'm learning RxSwift, how to use bind to and driver, what's the difference between of driver and bind to.Anyone else learning RxSwift now.If you are learning RxSwift or Swift or OC,i hope we can be friends and learn from each other.</p>

答:
@iwillnot response is fine but I will try to improve it with an example:

Imagine you have this code:

```<code>let intObservable = sequenceOf(1, 2, 3, 4, 5, 6)
    .observeOn(MainScheduler.sharedInstance)
    .catchErrorJustReturn(1)
    .map { $0 + 1 }
    .filter { $0 < 5 }
    .shareReplay(1)
</code>```

As @iwillnot wrote:

Driver
  You can read more in detail what the Driver is all about from the documentation. In summary, it simply allows you to rely on these properties:
  - Can't error out
  - Observe on main scheduler
  - Sharing side effects

if you use Driver, you won't have to specify observeOn, shareReplay nor catchErrorJustReturn.

In summary, the code above is similar to this one using Driver:

```<code>let intDriver = sequenceOf(1, 2, 3, 4, 5, 6)
    .asDriver(onErrorJustReturn: 1)
    .map { $0 + 1 }
    .filter { $0 < 5 }
</code>```

More details

Title: use RxSwift, driver and bind to

Body:
@iwillnot response is fine but I will try to improve it with an example:

Imagine you have this code:

let intObservable = sequenceOf(1, 2, 3, 4, 5, 6)
    .observeOn(MainScheduler.sharedInstance)
    .catchErrorJustReturn(1)
    .map { $0 + 1 }
    .filter { $0 < 5 }
    .shareReplay(1)

As @iwillnot wrote:

Driver
  You can read more in detail what the Driver is all about from the documentation. In summary, it simply allows you to rely on these properties:
  - Can't error out
  - Observe on main scheduler
  - Sharing side effects

if you use Driver, you won't have to specify observeOn, shareReplay nor catchErrorJustReturn.

In summary, the code above is similar to this one using Driver:

let intDriver = sequenceOf(1, 2, 3, 4, 5, 6)
    .asDriver(onErrorJustReturn: 1)
    .map { $0 + 1 }
    .filter { $0 < 5 }

More details


问:
How to select irregular shapes in a image
Using python code we are able to create image segments as shown in the screenshot. our requirement is how to select specific segment in the image and apply different color to it ?

The following is our python snippet

```<code>from skimage.segmentation import felzenszwalb, slic,quickshift

from skimage.segmentation import mark_boundaries

from skimage.util import img_as_float

import matplotlib.pyplot as plt

from skimage import measure

from skimage import restoration

from skimage import img_as_float

image = img_as_float(io.imread("leaf.jpg"))
segments = quickshift(image, ratio=1.0, kernel_size=20, max_dist=10,return_tree=False, sigma=0, convert2lab=True, random_seed=42)

fig = plt.figure("Superpixels -- %d segments" % (500))
ax = fig.add_subplot(1, 1, 1)

ax.imshow(mark_boundaries(image, segments))

plt.axis("off")
plt.show()
</code>```

答: You can use OpenCV python module - example: </p>

Body:
Using python code we are able to create image segments as shown in the screenshot. our requirement is how to select specific segment in the image and apply different color to it ?

The following is our python snippet

from skimage.segmentation import felzenszwalb, slic,quickshift

from skimage.segmentation import mark_boundaries

from skimage.util import img_as_float

import matplotlib.pyplot as plt

from skimage import measure

from skimage import restoration

from skimage import img_as_float

image = img_as_float(io.imread("leaf.jpg"))
segments = quickshift(image, ratio=1.0, kernel_size=20, max_dist=10,return_tree=False, sigma=0, convert2lab=True, random_seed=42)

fig = plt.figure("Superpixels -- %d segments" % (500))
ax = fig.add_subplot(1, 1, 1)

ax.imshow(mark_boundaries(image, segments))

plt.axis("off")
plt.show()


问:
Firebase Storage: Fail to download file even with public access
I am trying to test Firebase Storage. I manually uploaded images/egg.jpg.

I built a simple Android app to test the code from Firebase Guide in order to download the image. Just a button that enables the procedure.

The file fails to download and all I am getting is an exception from onFailure() that says "User does not have permission to access this object".

I saw similar questions and the solution was to allow read and write access to anyone through the rules, so I copied them as you can see below.

```<code>service firebase.storage {
  match /b/savephoto-a1cc3.appspot.com/o {
    match /{allPaths=**} {
      // Allow access by all users
      allow read, write;
    }
  }
}
</code>```

and here is the activitys code

```<code>private StorageReference pathRef = FirebaseStorage.getInstance().getReference().child("images/egg.jpg");
private ImageView imageView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    this.imageView = (ImageView) this.findViewById(R.id.imageView);
}

public void getImage(View v){
    File localFile;
    try {
        localFile = File.createTempFile("images","jpg");
        pathRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
                //Local temp file has been created
                Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                //handle error
                Toast.makeText(MainActivity.this, e.getMessage()+"\n"+e.getCause(), Toast.LENGTH_LONG).show();
            }
        });
    }catch (IOException exception){
        Toast.makeText(this, "IOEXCEPTION", Toast.LENGTH_SHORT).show();
    }
}
</code>```

Just to be sure I also added these permissions to the manifest.

```<code><uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
</code>```

Why I cannot download the damn file?

答:
Try change :</p>

```<code>service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write:if true
    }
  }
}
</code>```

Body:
I am trying to test Firebase Storage. I manually uploaded images/egg.jpg.

I built a simple Android app to test the code from Firebase Guide in order to download the image. Just a button that enables the procedure.

The file fails to download and all I am getting is an exception from onFailure() that says "User does not have permission to access this object".

I saw similar questions and the solution was to allow read and write access to anyone through the rules, so I copied them as you can see below.

service firebase.storage {
  match /b/savephoto-a1cc3.appspot.com/o {
    match /{allPaths=**} {
      // Allow access by all users
      allow read, write;
    }
  }
}

and here is the activitys code

private StorageReference pathRef = FirebaseStorage.getInstance().getReference().child("images/egg.jpg");
private ImageView imageView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    this.imageView = (ImageView) this.findViewById(R.id.imageView);
}

public void getImage(View v){
    File localFile;
    try {
        localFile = File.createTempFile("images","jpg");
        pathRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
                //Local temp file has been created
                Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                //handle error
                Toast.makeText(MainActivity.this, e.getMessage()+"\n"+e.getCause(), Toast.LENGTH_LONG).show();
            }
        });
    }catch (IOException exception){
        Toast.makeText(this, "IOEXCEPTION", Toast.LENGTH_SHORT).show();
    }
}

Just to be sure I also added these permissions to the manifest.

<uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Why I cannot download the damn file?

Body:
Try change :

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write:if true
    }
  }
}


问:
Serializiation with Protocol Buffers in a Schemaless Database
We're using MySQL to store schemaless data (see: Using a Relational Database for Schemaless Data for the solution inspired by how FriendFeed uses MySQL to store schemaless data).

One big table holds all entities for our application:

```<code>CREATE TABLE entities (
  added_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY
, id BINARY(16) NOT NULL
, body MEDIUMBLOB
, UNIQUE KEY (id)
) ENGINE=InnoDB ;
</code>```

A few details:

The only required property of stored entities is id, a 16-byte UUID. The rest of the entity is opaque to the database. We can change the "schema" simply by storing new properties in the body.

The added_id column is present because InnoDB stores data rows physically in primary key order. The AUTO_INCREMENT primary key ensures new entities are written sequentially on disk after old entities, which helps for read/write locality (new entities are read more frequently than old entities).

Our database stores our schemaless data in the body. <- This is the topic of this question.

Plenty of other interesting details, like "reaching into" the body data to build asynchronous materialized views (indexes are just tables that are built offline), but they're not relevant to the current discussion...

How should we be serializing the structured data (key-value pairs) in the body?

JSON or BSON would be simple, since the field names are repeated for each row. This gives it an advantage in flexibility but also a big disadvantage in space efficiency (a per-row overhead for field names in the serialized data). We're trying to keep things in memory, and minimizing both memory and network footprint is important here. The more records we can fit in the same space, the faster our queries will be. We prefer relatively long, descriptive field names, and shortening them to make my database faster is wrong!

In the end, JSON/BSON is unworkable for our purposes, unless we get more complex and map small keys to more descriptive keys in the application driver that talks to the database. Which got us thinking...

Although our database is schemaless, in reality: 1) there aren't too many different kinds of entities, 2) versions of the same kind of entity don't change often, and 3) when they do change, it's usually just to add another field. JSON/BSON have no native support for versioning.

Protocol Buffers and Thrift are much more sophisticated when it comes to versioning and data definition changes. Both Thrift and Protocol Buffers are great candidates for serializing data into databases, and Thrift is designed so that the encoding format is extensible.

Protocol Buffers look like a great choice for serializing data in a schemaless database.

CouchDB and MongoDB (the two most popular schemaless databases?) use JSON and BSON respectively, but we can't find anything about using something more advanced, like Protocol Buffers, as a serialization format for storing schemaless data. There are products that store a specific language's version of objects (ie. storing Java's Externalizable objects in a datagrid, or doing NoSQL with MySQL in Ruby), but these are a pain (try accessing them from other platforms, or even from MySQL itself, and forget about versioning).

Is anyone storing the more interoperable Protocol Buffers in their database, or some other advanced serialization format in their schemaless database? This is a question of whether there are other options besides straightforward per-row serialization of JSON/BSON/XML, or serializing a specific language's objects. Is it even feasible? Are we missing something? sorry for the stream of consciousness style narrative!

答:
As you found out, MongoDB and CouchDB have strong opinions about how you store your data. If you're looking for a storage agnostic approach, you'll want to do something like @Joshua suggests and look at Cassandra or HBase. Even these two datastores have opinions about how data should be stored (they're both based on Google's Bigtable) and store data in column families.

Riak uses protocol buffers as one method of serializing data from your application into the datastore. It might be worth checking out to see if it fits your needs. It looks like you're largely planning to do single key lookups, so Riak may be a strong contender for your solution.

ContentLicense: CC BY-SA 2.5

Body:
We're using MySQL to store schemaless data (see: Using a Relational Database for Schemaless Data for the solution inspired by how FriendFeed uses MySQL to store schemaless data).

One big table holds all entities for our application:

CREATE TABLE entities (
  added_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY
, id BINARY(16) NOT NULL
, body MEDIUMBLOB
, UNIQUE KEY (id)
) ENGINE=InnoDB ;

A few details:

The only required property of stored entities is id, a 16-byte UUID. The rest of the entity is opaque to the database. We can change the "schema" simply by storing new properties in the body.

The added_id column is present because InnoDB stores data rows physically in primary key order. The AUTO_INCREMENT primary key ensures new entities are written sequentially on disk after old entities, which helps for read/write locality (new entities are read more frequently than old entities).

Our database stores our schemaless data in the body. <- This is the topic of this question.

Plenty of other interesting details, like "reaching into" the body data to build asynchronous materialized views (indexes are just tables that are built offline), but they're not relevant to the current discussion...

How should we be serializing the structured data (key-value pairs) in the body?

JSON or BSON would be simple, since the field names are repeated for each row. This gives it an advantage in flexibility but also a big disadvantage in space efficiency (a per-row overhead for field names in the serialized data). We're trying to keep things in memory, and minimizing both memory and network footprint is important here. The more records we can fit in the same space, the faster our queries will be. We prefer relatively long, descriptive field names, and shortening them to make my database faster is wrong!

In the end, JSON/BSON is unworkable for our purposes, unless we get more complex and map small keys to more descriptive keys in the application driver that talks to the database. Which got us thinking...

Although our database is schemaless, in reality: 1) there aren't too many different kinds of entities, 2) versions of the same kind of entity don't change often, and 3) when they do change, it's usually just to add another field. JSON/BSON have no native support for versioning.

Protocol Buffers and Thrift are much more sophisticated when it comes to versioning and data definition changes. Both Thrift and Protocol Buffers are great candidates for serializing data into databases, and Thrift is designed so that the encoding format is extensible.

Protocol Buffers look like a great choice for serializing data in a schemaless database.

CouchDB and MongoDB (the two most popular schemaless databases?) use JSON and BSON respectively, but we can't find anything about using something more advanced, like Protocol Buffers, as a serialization format for storing schemaless data. There are products that store a specific language's version of objects (ie. storing Java's Externalizable objects in a datagrid, or doing NoSQL with MySQL in Ruby), but these are a pain (try accessing them from other platforms, or even from MySQL itself, and forget about versioning).

Is anyone storing the more interoperable Protocol Buffers in their database, or some other advanced serialization format in their schemaless database? This is a question of whether there are other options besides straightforward per-row serialization of JSON/BSON/XML, or serializing a specific language's objects. Is it even feasible? Are we missing something? sorry for the stream of consciousness style narrative!


问:
Mutator/Accessor methods for object variable declared in private
I have a couple object variables declared in private of a class:

```<code>private:
a a1;
</code>```

This overloaded operator was originally friends with this class and accessed the objects as shown bellow:

```<code>istream & operator >>( istream & input, class & m )
{
    input >> m.a1;
    return input;
 }
  ostream & operator <<( ostream & os, const class & m )
 {
     os << m.uni;

     return os;
 }
</code>```

When the operator is unfriended it should no longer have access to the private variables.

How would I access the two objects? Would it be the use of accessor/mutator methods that return pointers to the object?

EDIT: changed the code so it explains the question a bit more.

答:
Use whatever ways there is to set the values of a1 and b1.

You don't have to read directly into the private variables, you could also read values into some temporaries and then use those to modify a1 and b1. Or create a brand new Results and assign that to m.

Body:
I have a couple object variables declared in private of a class:

private:
a a1;

This overloaded operator was originally friends with this class and accessed the objects as shown bellow:

istream & operator >>( istream & input, class & m )
{
    input >> m.a1;
    return input;
 }
  ostream & operator <<( ostream & os, const class & m )
 {
     os << m.uni;

     return os;
 }

When the operator is unfriended it should no longer have access to the private variables.

How would I access the two objects? Would it be the use of accessor/mutator methods that return pointers to the object?

EDIT: changed the code so it explains the question a bit more.


问:
write into Hbase table
I have a Hbase table: 'employeedetails' with column families: 'personaldetails','professionaldetails'

When I try to write using put for multiple column families, like below:

```<code>put 'employeedetails','1','personaldetails:firstname','Steven','personaldetails:lastname','Gerrard','professionaldetails:company','ABC','professionaldetails:empid','123abc'
</code>```

I get the error message:

```<code>ERROR: wrong number of arguments (10 for 6)
Here is some help for this command:
Put a cell 'value' at specified table/row/column and optionally
timestamp coordinates.  To put a cell value into table 'ns1:t1' or 't1'
at row 'r1' under column 'c1' marked with the time 'ts1', do:
</code>```

But if I put the data into ColumnFamily's columns one by one, it works.

```<code>hbase(main):040:0> put 'employeedetails','1','personaldetails:firstname','Steven'
0 row(s) in 0.0190 seconds
</code>```

Can anyone tell me if I am doing any mistake while writing for multiple column families or is there any difference in the concept of writing multiple column families in one go.

答:
In Hbase, you cannot write multiple column qualifiers in one go.

Put is meant for writing a single cell value into the Hbase table.

Put a cell ‘value’ at specified table/row/column and optionally
  timestamp coordinates.

Split your put statement into multiple individual put statements.

Title: write into Hbase table

Body:
I have a Hbase table: 'employeedetails' with column families: 'personaldetails','professionaldetails'

When I try to write using put for multiple column families, like below:

put 'employeedetails','1','personaldetails:firstname','Steven','personaldetails:lastname','Gerrard','professionaldetails:company','ABC','professionaldetails:empid','123abc'

I get the error message:

ERROR: wrong number of arguments (10 for 6)
Here is some help for this command:
Put a cell 'value' at specified table/row/column and optionally
timestamp coordinates.  To put a cell value into table 'ns1:t1' or 't1'
at row 'r1' under column 'c1' marked with the time 'ts1', do:

But if I put the data into ColumnFamily's columns one by one, it works.

hbase(main):040:0> put 'employeedetails','1','personaldetails:firstname','Steven'
0 row(s) in 0.0190 seconds

Can anyone tell me if I am doing any mistake while writing for multiple column families or is there any difference in the concept of writing multiple column families in one go.


问:
React JS rendering elements with on click function and passing index to on click function
I am trying to render React components using loop, Basically its link tag having on click function with value.

```<code><p><a href="#" key={i} onClick={() => this.decreaseCount(i)} >delete</a></p>
</code>```

where i is the index of the for loop. The problem is, instead of getting i's value inside this.decreaseCount(i) I am getting length of array. However I am getting correct index with key={i}

Need help!

答:
That should work, try to use this (another way):

```<code><p><a href="#" key={i} onClick={this.decreaseCount.bind(this,i)} >delete</a></p>
</code>```

Check this example, you way will also work:

class App extends React.Component{

   a(i){
     console.log(i);
   }

   render(){
     return (

           {
               [1,2,3].map(i =>
 this.a(i)} > {i}
)
           }

     )
   }
}

ReactDOM.render(<App/>,document.getElementById('app'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/></code>```

Body:
I am trying to render React components using loop, Basically its link tag having on click function with value.

 this.decreaseCount(i)} >delete

where i is the index of the for loop. The problem is, instead of getting i's value inside this.decreaseCount(i) I am getting length of array. However I am getting correct index with key={i}

Need help!

Body:
That should work, try to use this (another way):

<p><a href="#" key={i} onClick={this.decreaseCount.bind(this,i)} >delete</a></p>

Check this example, you way will also work:

class App extends React.Component{

   a(i){
     console.log(i);
   }

   render(){
     return (
        <div>
           {
               [1,2,3].map(i => <p onClick={ () => this.a(i)} > {i} </p>)
           }
        </div>
     )
   }
}

ReactDOM.render(<App/>,document.getElementById('app'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>


问:
Want to pass ArrayList contain class objects in javascript
I have a ArrayList which contain objects of a Java Class.I want to pass that list to javascript and want to populate the data within the object in to jsp.
The ArrayList is present in the jsp.Each class object only contain 2 parameter values.Class name is 'Certificate' and it contain 'certId' and 'certName'

jsp:

```<code><%
 ArrayList getAllCertificateNamewithId=new ArrayList();
 getAllCertificateNamewithId=(ArrayList)mainMap.get("getAllCertificateNamewithIdMap");%>
<input type="button"  width="16" height="16"  onclick="fetchAndShow('<%=getAllCertificateNamewithId %>')" />
</code>```

Javascript

```<code>function fetchAndShow(certObj){
//How to fetch the list's each object  and cast to java class 'Certificate'
}
</code>```

List contain

```<code>[com.dto.Certificate@9b44a1, com.dto.Certificate@1b6b3ac]
</code>```

答:
Think of it this way: you use Java + JSP as a means to write a text file that you then send to the user's browser, with JSP being a simple template mechanism.

You could theory implement your own method to serialize the List with objects to a String, and then implement a mechanism on the client side to deserialize into whatever data structure you want. For instance you could write your List as JSON.

But now I am inclined to ask: do you really, really, Really, REALLY need to do this ? Exposing server certificates of any kind to the client is a big no-no.

Body:
I have a ArrayList which contain objects of a Java Class.I want to pass that list to javascript and want to populate the data within the object in to jsp.
The ArrayList is present in the jsp.Each class object only contain 2 parameter values.Class name is 'Certificate' and it contain 'certId' and 'certName'

jsp:

<%
 ArrayList getAllCertificateNamewithId=new ArrayList();
 getAllCertificateNamewithId=(ArrayList)mainMap.get("getAllCertificateNamewithIdMap");%>
<input type="button"  width="16" height="16"  onclick="fetchAndShow('<%=getAllCertificateNamewithId %>')" />

Javascript

function fetchAndShow(certObj){
//How to fetch the list's each object  and cast to java class 'Certificate'
}

List contain

[com.dto.Certificate@9b44a1, com.dto.Certificate@1b6b3ac]


问:
Strange exception / error in gwt build when I extend ArrayList or other common collections
I am using Eclipse IDE  Version: Luna Service Release 1 (4.4.1).
Using  GWT 2.7 and Java  1.7.

I have implemented some custom collection class using replace with rule provided by GWT.

```<code>public class CustomArrayList<E> extends ArrayList{
 // ...... overridden methods here
}

ArrayList arraList=GWT.create(ArrayList.class);
</code>```

whenever I create instance of arraylist using GWT.create it use my on  CustomArrayList class.

```<code>//gwt.xml file contains this configuration

    <replace-with
        class="xxxxxxxx.yyyyyyy.CustomArrayList">
        <when-type-is class="java.util.ArrayList" />
    </replace-with>
</code>```

In GWT maven project on client side I use array list instantiation as per the mention above but But while project compilation got some stack overflow error with AbstarctTreeLogger related msg printing on console.

```<code>customcollection.CustomArrayList<java.lang.Object>
</code>```

[INFO]                                                                                [WARN] Checking all subtypes of Object which qualify for serialization
[ERROR] Exception in thread "main" java.lang.StackOverflowError
[ERROR]     at com.google.gwt.dev.util.log.AbstractTreeLogger.commitMyBranchEntryInMyParentLogger(AbstractTreeLogger.java:252)
[ERROR]     at com.google.gwt.dev.util.log.AbstractTreeLogger.commitMyBranchEntryInMyParentLogger(AbstractTreeLogger.java:252)
[ERROR]     at

It produces this error repeatedly for at least a few thousand times and then the compiler crashes.

After failure If I try again it works but not every time.

Can any one help me to figure out issue.

答:
Just a guess, but since GWT needs to make sure that every class that could ever be contained in a List is Serializable... By creating a custom List, you just doubled the compiler's work, and now it's hitting a memory limit.

You might be able to solve this by increasing the memory available to the compiler, but your best choice is to be more specific with the types that you use.

See How can I keep GWT from trying to include every serializable class when I use ArrayList and gwt - Using List<Serializable> in a RPC call?

Body:
I am using Eclipse IDE  Version: Luna Service Release 1 (4.4.1).
Using  GWT 2.7 and Java  1.7.

I have implemented some custom collection class using replace with rule provided by GWT.

public class CustomArrayList<E> extends ArrayList{
 // ...... overridden methods here
}

ArrayList arraList=GWT.create(ArrayList.class);

whenever I create instance of arraylist using GWT.create it use my on  CustomArrayList class.

//gwt.xml file contains this configuration

    <replace-with
        class="xxxxxxxx.yyyyyyy.CustomArrayList">
        <when-type-is class="java.util.ArrayList" />
    </replace-with>

In GWT maven project on client side I use array list instantiation as per the mention above but But while project compilation got some stack overflow error with AbstarctTreeLogger related msg printing on console.

customcollection.CustomArrayList<java.lang.Object>

[INFO]                                                                                [WARN] Checking all subtypes of Object which qualify for serialization
[ERROR] Exception in thread "main" java.lang.StackOverflowError
[ERROR]     at com.google.gwt.dev.util.log.AbstractTreeLogger.commitMyBranchEntryInMyParentLogger(AbstractTreeLogger.java:252)
[ERROR]     at com.google.gwt.dev.util.log.AbstractTreeLogger.commitMyBranchEntryInMyParentLogger(AbstractTreeLogger.java:252)
[ERROR]     at

It produces this error repeatedly for at least a few thousand times and then the compiler crashes.

After failure If I try again it works but not every time.

Can any one help me to figure out issue.


问:
How to randomly select letters in Java?
I am learning java, and my assignment now is to simulate a chess notation.

I have done random int codes, but not sure how to make a random letter code, and the thing is I only need to choose random letters from A to H, I have seen random all 26 letter generators but could not work my way to understand how to generate only A to H.

My other concern is will I be able to store char and ints in a matrix [k][8] or do I have to initialise it in a special way?

The idea is to create the class and later try and randomly generate chess notation.  At this stage, the notations do not have to make sense.

Here is what I used for int random

```<code>import java.util.Random;

static Random rnd = new Random();
static int rnd(int A, int B) {
    return A + rnd.nextInt(B - A + 1);
</code>```

Also, how can I make the random selection from specified letters that will represent the chess figures?

I don't need exact codes a push to the right direction will be more than enough.

答:
What about something like this?</p>

```<code>Random rnd = new Random();
String characters = "ABCDEFGH";
char randomChar = characters.charAt(rnd.nextInt(characters.length()));
</code>```

Title: How to randomly select letters in Java?

Body:
I am learning java, and my assignment now is to simulate a chess notation.

I have done random int codes, but not sure how to make a random letter code, and the thing is I only need to choose random letters from A to H, I have seen random all 26 letter generators but could not work my way to understand how to generate only A to H.

My other concern is will I be able to store char and ints in a matrix [k][8] or do I have to initialise it in a special way?

The idea is to create the class and later try and randomly generate chess notation.  At this stage, the notations do not have to make sense.

Here is what I used for int random

import java.util.Random;

static Random rnd = new Random();
static int rnd(int A, int B) {
    return A + rnd.nextInt(B - A + 1);

Also, how can I make the random selection from specified letters that will represent the chess figures?

I don't need exact codes a push to the right direction will be more than enough.

Body:
What about something like this?

Random rnd = new Random();
String characters = "ABCDEFGH";
char randomChar = characters.charAt(rnd.nextInt(characters.length()));


问:
How to distribute a 200MB database to a locally executed HTML5 web page
I am building a search tool that is designed to be run at my organization. My deployment strategy is:

HTML5 web page that's stored on the file server.

200MB JSON or JavaScript file that's in another file.

Right now the 200MB file is a .js file with statements like:

```<code>var data = {....};
</code>```

Where {....} is about 200MB in size. This is working on Apple Safari on a Mac but it causes performance problems on Chrome. Firefox takes several minutes to load, but then it's fine. It seems like a memory problem.

Another option is to store it in a .json file and to load it with JQuery.

Is there a better way to do this?  The 200MB file contains several hundred thousand records.

EDIT YES, the entire database must be local, because I do not have a web server with backend logic.

ALSO, it is unclear to me at the moment if the 200MB object is better distributed as a JSON Object or as an Array.

EDIT I've now determined that I can't store it in a JSON object, because you can't use JQuery to read a file:// URL (even if the HTML comes from a file:// URL). So now my plan is to encode the 200MB file as 200,000 1K statements that insert the values into a {}.

答:
You should read these articles:

https://www.html5rocks.com/en/tutorials/file/dndfiles/

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data

Also there isn't a really good choice of doing that, cause memory leak. I think isn't right choice.

Body:
I am building a search tool that is designed to be run at my organization. My deployment strategy is:

HTML5 web page that's stored on the file server.

200MB JSON or JavaScript file that's in another file.

Right now the 200MB file is a .js file with statements like:

var data = {....};

Where {....} is about 200MB in size. This is working on Apple Safari on a Mac but it causes performance problems on Chrome. Firefox takes several minutes to load, but then it's fine. It seems like a memory problem.

Another option is to store it in a .json file and to load it with JQuery.

Is there a better way to do this?  The 200MB file contains several hundred thousand records.

EDIT YES, the entire database must be local, because I do not have a web server with backend logic.

ALSO, it is unclear to me at the moment if the 200MB object is better distributed as a JSON Object or as an Array.

EDIT I've now determined that I can't store it in a JSON object, because you can't use JQuery to read a file:// URL (even if the HTML comes from a file:// URL). So now my plan is to encode the 200MB file as 200,000 1K statements that insert the values into a {}.


问:
htaccess redirect to no slash with rewrite rule
I have this rewrite rule in my htaccess file

```<code>RewriteRule ^my-old-parent/(.*)$ /$1 [R=301,NC,L]
</code>```

It will redirect:

```<code>example.com/my-old-parent/child/
</code>```

To:

```<code>example.com/child/
</code>```

But I want it to redirect to:

```<code>example.com/child
</code>```

I've seen a few solutions but they are all doing it in two steps which means two redirects. I want just one redirect.

Any ideas? Maybe some search replace / with nothing or some regex solution?

答:
Use below rule,</p>

```<code>RewriteRule ^my-old-parent/(.*)/$ /$1 [R=301,NC,L]
</code>```

Body:
I have this rewrite rule in my htaccess file

RewriteRule ^my-old-parent/(.*)$ /$1 [R=301,NC,L]

It will redirect:

example.com/my-old-parent/child/

To:

example.com/child/

But I want it to redirect to:

example.com/child

I've seen a few solutions but they are all doing it in two steps which means two redirects. I want just one redirect.

Any ideas? Maybe some search replace / with nothing or some regex solution?

Body:
Use below rule,

RewriteRule ^my-old-parent/(.*)/$ /$1 [R=301,NC,L]


问:
Codeigniter and Set Session in Model
I want to unset and set session in model function depend on passed id.

I have language field for every record and should change session considering that.

in sample word i have a link like this : http://www.mysite.com/report/2020

now this article by this id maybe saved by english language but current session is french.so I should change the session.
here is my code but it dos not work.

```<code>  //function for checking language by id
  public function lang($id)
     {
         $data = $this->db
                        ->select('language')
                        ->from('content')
                        ->where('id',$id)
                        ->get();

        if ($data->num_rows > 0) {

            return $data;
  }else{
            return false;
        }
    }
  //function for reading data from db depend on id and language
  public function report($id)
    {

    $cat=2;
    $code=$id;

    $langu= $this->lang($id)->row()->language;
    if($langu==3){
    $this->session->unset_userdata('lang');
    $this->session->set_userdata('lang','dr');
    }
    if($langu==2){
    $this->session->unset_userdata('lang');
    $this->session->set_userdata('lang','pa');
    }
    if($langu==1){
    $this->session->unset_userdata('lang');
    $this->session->set_userdata('lang','en');
    }
    $language= $this->session->userdata('lang');
    $lang=$language;

    $data = $this->db
                        ->select('*')
                        ->from('content')
                        ->where('category',$cat)
                        ->where('language',$lang)
                        ->where('id',$code)
                        ->get();

        if ($data->num_rows > 0) {

            return $data;
        }else{
            return false;
        }

    }
</code>```

答:
Sometimes there is really need to set or get session data in model.
Use then Code Igniter instance like below:

```<code>$codeIgniter =& get_instance();
$codeIgniter->set_userdata('data', $data);
// or to read data:
$data = $codeIgniter->userdata('data');
</code>```

Note that using $this to call set_userdata() or userdata() in model will not work correctly.

Title: Codeigniter and Set Session in Model

Body:
I want to unset and set session in model function depend on passed id.

I have language field for every record and should change session considering that.

in sample word i have a link like this : http://www.mysite.com/report/2020

now this article by this id maybe saved by english language but current session is french.so I should change the session.
here is my code but it dos not work.

  //function for checking language by id
  public function lang($id)
     {
         $data = $this->db
                        ->select('language')
                        ->from('content')
                        ->where('id',$id)
                        ->get();

        if ($data->num_rows > 0) {

            return $data;
  }else{
            return false;
        }
    }
  //function for reading data from db depend on id and language
  public function report($id)
    {

    $cat=2;
    $code=$id;

    $langu= $this->lang($id)->row()->language;
    if($langu==3){
    $this->session->unset_userdata('lang');
    $this->session->set_userdata('lang','dr');
    }
    if($langu==2){
    $this->session->unset_userdata('lang');
    $this->session->set_userdata('lang','pa');
    }
    if($langu==1){
    $this->session->unset_userdata('lang');
    $this->session->set_userdata('lang','en');
    }
    $language= $this->session->userdata('lang');
    $lang=$language;

    $data = $this->db
                        ->select('*')
                        ->from('content')
                        ->where('category',$cat)
                        ->where('language',$lang)
                        ->where('id',$code)
                        ->get();

        if ($data->num_rows > 0) {

            return $data;
        }else{
            return false;
        }

    }

Body:
Sometimes there is really need to set or get session data in model.
Use then Code Igniter instance like below:

$codeIgniter =& get_instance();
$codeIgniter->set_userdata('data', $data);
// or to read data:
$data = $codeIgniter->userdata('data');

Note that using $this to call set_userdata() or userdata() in model will not work correctly.


问:
How to minify JavaScript like Google Analytics?
Most of you are probably familiar with this little tracking code offered by Google Analytics.

```<code><script>
(
    function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    }
)(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-00000000-0', 'auto');
ga('send', 'pageview');
</script>
</code>```

The interesting part is that this little excerpt contains arguments that form the word isogram. This script also uses arguments to declare variables to shave off some bits from the final file size. Arguably, you would not use this pattern when writing the code (?), so my question is, how does Google minify its code and are these techniques available to mere mortals, too?

I found online this example by Stephen Morley that includes a code that looks like something you'd write before minifying it. I took that code and run it through Google's very own Closure Compiler on advanced optimisation. As expected, the resulting code is nothing like the actual script used by Google Analytics.

```<code>(function(){window.b="ga";"ga"in window||(window.a=function(){window.a.q.push(arguments)},window.a.q=[]);window.a.c=(new Date).getTime();var c=document.createElement("script");c.src="//www.google-analytics.com/analytics.js";c.async=!0;var d=document.getElementsByTagName("script")[0];d.parentNode.insertBefore(c,d)})();
</code>```

This time, the code is less DRY and bigger, even without the two extra commands.

So to clarify, I am curious how the Google engineers arrived to the above result (I do not think their code actually looks like the one in Stephen's example), and could this process be replicated even if you are not a part of Google? Thank you in advance!

答:
Google is nice, because they give us a full documentation about many thing on https://developers.google.com

So many of your responses can be found on :

Google analytics file

Closure Compiler documentation

Closure Compiler repository

Here is the unminified Analytics.js

```<code>(function(i, s, o, g, r, a, m){
  i['GoogleAnalyticsObject'] = r; // Acts as a pointer to support renaming.

  // Creates an initial ga() function.
  // The queued commands will be executed once analytics.js loads.
  i[r] = i[r] || function() {
    (i[r].q = i[r].q || []).push(arguments)
  },

  // Sets the time (as an integer) this tag was executed.
  // Used for timing hits.
  i[r].l = 1 * new Date();

  // Insert the script tag asynchronously.
  // Inserts above current tag to prevent blocking in addition to using the
  // async attribute.
  a = s.createElement(o),
  m = s.getElementsByTagName(o)[0];
  a.async = 1;
  a.src = g;
  m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');

// Creates a default tracker with automatic cookie domain configuration.
ga('create', 'UA-XXXXX-Y', 'auto');

// Sends a pageview hit from the tracker just created.
ga('send', 'pageview');
</code>```

And here is the minified version they provide (pretty version):

```<code>(function (i, s, o, g, r, a, m) {
    i['GoogleAnalyticsObject'] = r;
    i[r] = i[r] || function () {
            (i[r].q = i[r].q || []).push(arguments)
        }, i[r].l = 1 * new Date();
    a = s.createElement(o),
        m = s.getElementsByTagName(o)[0];
    a.async = 1;
    a.src = g;
    m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');

ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');
</code>```

And here the minified version with closure compiler tools

```<code>(function (a, e, f, g, b, c, d) {
    a.GoogleAnalyticsObject = b;
    a[b] = a[b] || function () {(a[b].q = a[b].q || []).push(arguments)};
    a[b].l = 1 * new Date;
    c = e.createElement(f);
    d = e.getElementsByTagName(f)[0];
    c.async = 1;
    c.src = g;
    d.parentNode.insertBefore(c, d)
})(window, document, "script", "//www.google-analytics.com/analytics.js", "ga");
ga("create", "UA-XXXXX-Y", "auto");
ga("send", "pageview");
</code>```

It's look like the same.

You can find more details on the project on Github repository.

Body:
Most of you are probably familiar with this little tracking code offered by Google Analytics.

The interesting part is that this little excerpt contains arguments that form the word isogram. This script also uses arguments to declare variables to shave off some bits from the final file size. Arguably, you would not use this pattern when writing the code (?), so my question is, how does Google minify its code and are these techniques available to mere mortals, too?

I found online this example by Stephen Morley that includes a code that looks like something you'd write before minifying it. I took that code and run it through Google's very own Closure Compiler on advanced optimisation. As expected, the resulting code is nothing like the actual script used by Google Analytics.

(function(){window.b="ga";"ga"in window||(window.a=function(){window.a.q.push(arguments)},window.a.q=[]);window.a.c=(new Date).getTime();var c=document.createElement("script");c.src="//www.google-analytics.com/analytics.js";c.async=!0;var d=document.getElementsByTagName("script")[0];d.parentNode.insertBefore(c,d)})();

This time, the code is less DRY and bigger, even without the two extra commands.

So to clarify, I am curious how the Google engineers arrived to the above result (I do not think their code actually looks like the one in Stephen's example), and could this process be replicated even if you are not a part of Google? Thank you in advance!

Body:
Google is nice, because they give us a full documentation about many thing on https://developers.google.com

So many of your responses can be found on :

Google analytics file

Closure Compiler documentation

Closure Compiler repository

Here is the unminified Analytics.js

(function(i, s, o, g, r, a, m){
  i['GoogleAnalyticsObject'] = r; // Acts as a pointer to support renaming.

  // Creates an initial ga() function.
  // The queued commands will be executed once analytics.js loads.
  i[r] = i[r] || function() {
    (i[r].q = i[r].q || []).push(arguments)
  },

  // Sets the time (as an integer) this tag was executed.
  // Used for timing hits.
  i[r].l = 1 * new Date();

  // Insert the script tag asynchronously.
  // Inserts above current tag to prevent blocking in addition to using the
  // async attribute.
  a = s.createElement(o),
  m = s.getElementsByTagName(o)[0];
  a.async = 1;
  a.src = g;
  m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');

// Creates a default tracker with automatic cookie domain configuration.
ga('create', 'UA-XXXXX-Y', 'auto');

// Sends a pageview hit from the tracker just created.
ga('send', 'pageview');

And here is the minified version they provide (pretty version):

(function (i, s, o, g, r, a, m) {
    i['GoogleAnalyticsObject'] = r;
    i[r] = i[r] || function () {
            (i[r].q = i[r].q || []).push(arguments)
        }, i[r].l = 1 * new Date();
    a = s.createElement(o),
        m = s.getElementsByTagName(o)[0];
    a.async = 1;
    a.src = g;
    m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');

ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');

And <a href="https://closure-compiler.appspot.com/home#code%3D%252F%252F%2520%253D%253DClosureCompiler%253D%253D%250A%252F%252F%2520%2540compilation_level%2520SIMPLE_OPTIMIZATIONS%250A%252F%252F%2520%2540output_file_name%2520default.js%250A%252F%252F%2520%253D%253D%252FClosureCompiler%253D%253D%250A%250A%252F%252F%2520ADD%2520YOUR%2520CODE%2520HERE%250A(function(i%252C%2520s%252C%2520o%252C%2520g%252C%2520r%252C%2520a%252C%2520m)%257B%250A%2520%2520i%255B'GoogleAnalyticsObject'%255D%2520%253D%2520r%253B%2520%252F%252F%2520Acts%2520as%2520a%2520pointer%2520to%2520support%2520renaming.%250A%250A%2520%2520%252F%252F%2520Creates%2520an%2520initial%2520ga()%2520function.%250A%2520%2520%252F%252F%2520The%2520queued%2520commands%2520will%2520be%2520executed%2520once%2520analytics.js%2520loads.%250A%2520%2520i%255Br%255D%2520%253D%2520i%255Br%255D%2520%257C%257C%2520function()%2520%257B%250A%2520%2520%2520%2520(i%255Br%255D.q%2520%253D%2520i%255Br%255D.q%2520%257C%257C%2520%255B%255D).push(arguments)%250A%2520%2520%257D%252C%250A%250A%2520%2520%252F%252F%2520Sets%2520the%2520time%2520(as%2520an%2520integer)%2520this%2520tag%2520was%2520executed.%250A%2520%2520%252F%252F%2520Used%2520for%2520timing%2520hits.%250A%2520%2520i%255Br%255D.l%2520%253D%25201%2520*%2520new%2520Date()%253B%250A%250A%2520%2520%252F%252F%2520Insert%2520the%2520script%2520tag%2520asynchronously.%250A%2520%2520%252F%252F%2520Inserts%2520above%2520current%2520tag%2520to%2520prevent%2520blocking%2520in%2520addition%2520to%2520using%2520the%250A%2520%2520%252F%252F%2520async%2520attribute.%250A%2520%2520a%2520%253D%2520s.createElement(o)%252C%250A%2520%2520m%2520%253D%2520s.getElementsByTagName(o)%255B0%255D%253B%250A%2520%2520a.async%2520%253D%25201%253B%250A%2520%2520a.src%2520%253D%2520g%253B%250A%2520%2520m.parentNode.insertBefore(a%252C%2520m)%250A%257D)(window%252C%2520document%252C%2520'script'%252C%2520'%252F%252Fwww.google-analytics.com%252Fanalytics.js'%252C%2520'ga')%253B%250A%250A%252F%252F%2520Creates%2520a%2520default%2520tracker%2520with%2520automatic%2520cookie%2520domain%2520configuration.%250Aga('create'%252C%2520'UA-XXXXX-Y'%252C%2520'auto')%253B%250A%250A%252F%252F%2520Sends%2520a%2520pageview%2520hit%2520from%2520the%2520tracker%2520just%2520created.%250Aga('send'%252C%2520'pageview')%253B" rel="noreferrer">here the minified version with closure compiler tools

(function (a, e, f, g, b, c, d) {
    a.GoogleAnalyticsObject = b;
    a[b] = a[b] || function () {(a[b].q = a[b].q || []).push(arguments)};
    a[b].l = 1 * new Date;
    c = e.createElement(f);
    d = e.getElementsByTagName(f)[0];
    c.async = 1;
    c.src = g;
    d.parentNode.insertBefore(c, d)
})(window, document, "script", "//www.google-analytics.com/analytics.js", "ga");
ga("create", "UA-XXXXX-Y", "auto");
ga("send", "pageview");

It's look like the same.

You can find more details on the project on Github repository.


问:
MySQL GROUP_CONCAT Rearranges values
Suppose I have the following table:

```<code>ID|Col1    |Col2
1 |Test1   |Test12
2 |Test2   |Test22
2 |Test3   |Test32
</code>```

When I use a query like:

```<code>SELECT GROUP_CONCAT(Col1) as First, GROUP_CONCAT(Col2) as Second WHERE ID=2 GROUP BY ID
</code>```

It sometimes returns the GROUP_CONCAT's rearranged. For example:

```<code>ID|First      |Second
2 |Test2,Test3|Test32,Test22
</code>```

While I would expect it to return:

```<code>ID|First      |Second
2 |Test2,Test3|Test22,Test32
</code>```

As you can see, it switched the concatenated values in the column named 'Second'. How can I prevent this from happening?

答:
This table is missing common column (PK) to sort in group_concat.

ID|GroupID|Col1    |Col2

1|1       |Test1   |Test12

2|2       |Test2   |Test22

3|2       |Test3   |Test32

```<code>SELECT GROUP_CONCAT(Col1 ORDER BY ID) as First,
       GROUP_CONCAT(Col2 ORDER BY ID) as Second
FROM t
WHERE GroupID = 2
GROUP BY GroupID;
</code>```

This will retain the order of group concat of col1 and col2.

Title: MySQL GROUP_CONCAT Rearranges values

Body:
Suppose I have the following table:

ID|Col1    |Col2
1 |Test1   |Test12
2 |Test2   |Test22
2 |Test3   |Test32

When I use a query like:

SELECT GROUP_CONCAT(Col1) as First, GROUP_CONCAT(Col2) as Second WHERE ID=2 GROUP BY ID

It sometimes returns the GROUP_CONCAT's rearranged. For example:

ID|First      |Second
2 |Test2,Test3|Test32,Test22

While I would expect it to return:

ID|First      |Second
2 |Test2,Test3|Test22,Test32

As you can see, it switched the concatenated values in the column named 'Second'. How can I prevent this from happening?

Body:
This table is missing common column (PK) to sort in group_concat.

ID|GroupID|Col1    |Col2

1|1       |Test1   |Test12

2|2       |Test2   |Test22

3|2       |Test3   |Test32

SELECT GROUP_CONCAT(Col1 ORDER BY ID) as First,
       GROUP_CONCAT(Col2 ORDER BY ID) as Second
FROM t
WHERE GroupID = 2
GROUP BY GroupID;

This will retain the order of group concat of col1 and col2.


问:
To run SSIS package outside of SQL server Data Tools you must install File_creation of Integration services or higher
Getting this error while trying to run Package.dtsx from command file(.cmd).

To run SSIS package outside of SQL server Data Tools you must install %File_creation% of Integration services or higher

I've used package parameters & File System Tasks in the package. I used below script in command file.

```<code>DTEXEC /FILE "F:\SOME FOLDER\Package.dtsx" /CONFIGFILE "F:\SOME FOLDER\PackagedtsConfig"
</code>```

Appreciate any help on this.

答:
The main problem is that SSIS packages are deployed using a SSDT version newer that the one installed on the server you are trying to execute the package on it. You have to install the same version of SSDT on the server.

Useful Links

https://social.technet.microsoft.com/Forums/en-US/e5a149bf-a636-44bd-b825-36f9984ae720/to-run-a-ssis-package-outside-of-sql-server-data-tools-you-must-install-move-file-to-archive-of?forum=sqlintegrationservices

https://dba.stackexchange.com/questions/49786/error-to-run-a-ssis-package-outside-of-sql-server-data-tools-you-must-install

https://dba.stackexchange.com/questions/138850/ssis-to-run-the-package-outside-of-sql-server-data-tools-you-must-install-expre

Body:
Getting this error while trying to run Package.dtsx from command file(.cmd).

To run SSIS package outside of SQL server Data Tools you must install %File_creation% of Integration services or higher

I've used package parameters & File System Tasks in the package. I used below script in command file.

DTEXEC /FILE "F:\SOME FOLDER\Package.dtsx" /CONFIGFILE "F:\SOME FOLDER\PackagedtsConfig"

Appreciate any help on this.


问:
how to import excel sheet (.xlxs) to sql server 2012 db through asp.net and vb.net
It is my first time that am posting a question here.

I have research a lot on the web on how to upload excel sheet (.xlxs) to sql server 2012 database through asp.net and vb.net, however, unfortunately all those research was of no use.

can someone please help me with the source code.

thanks.

答:
SqlBulkCopy class as the name suggests does bulk insert from one source to another and hence all rows from the Excel sheet can be easily read and inserted using the SqlBulkCopy class.

```<code><add name = "constr" connectionString = "Data
 Source=.\SQL2008R2;Database=dbname;User Id=abc;password=xxxxx"/>
</code>```

I have specified the connection strings for the Excel files of both 2003 and 2007 or higher formats in the Web.Config file.

```<code><add name = "Excel03ConString" connectionString =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel
 8.0;HDR=YES'"/>
 <add name = "Excel07+ConString" connectionString =
 "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended
  Properties='Excel 8.0;HDR=YES'"/>
</code>```

The HTML Markup consists of ASP.Net FileUpload control and a Button to trigger the file upload process.

```<code><asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button Text="Upload" OnClick = "Upload" runat="server" />
</code>```

You will need to import the following namespaces.

```<code>using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Configuration;

protected void Upload(object sender, EventArgs e)
{
 //Upload and save the file
  string excelPath = Server.MapPath("~/Files/") +
  Path.GetFileName(FileUpload1.PostedFile.FileName);
  FileUpload1.SaveAs(excelPath);

string conString = string.Empty;
string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
switch (extension)
{
    case ".xls": //Excel 97-03
        conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
        break;
    case ".xlsx": //Excel 07 or higher
        conString =

ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString;
        break;

}
conString = string.Format(conString, excelPath);
using (OleDbConnection excel_con = new OleDbConnection(conString))
{
    excel_con.Open();
    string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
    null).Rows[0]["TABLE_NAME"].ToString();
    DataTable dtExcelData = new DataTable();

    //[OPTIONAL]: It is recommended as otherwise the data will be considered
    as String by default.
    dtExcelData.Columns.AddRange(new DataColumn[3] { new DataColumn("Id",
    typeof(int)),
            new DataColumn("Name", typeof(string)),
            new DataColumn("Salary",typeof(decimal)) });

    using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" +
   sheet1 + "]", excel_con))
    {
        oda.Fill(dtExcelData);
    }
    excel_con.Close();

    string consString =
    ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(consString))
    {
        using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
        {
            //Set the database table name
            sqlBulkCopy.DestinationTableName = "dbo.tblPersons";

            //[OPTIONAL]: Map the Excel columns with that of the database table
            sqlBulkCopy.ColumnMappings.Add("Id", "PersonId");
            sqlBulkCopy.ColumnMappings.Add("Name", "Name");
            sqlBulkCopy.ColumnMappings.Add("Salary", "Salary");
            con.Open();
            sqlBulkCopy.WriteToServer(dtExcelData);
            con.Close();
        }
    }
}
 }
</code>```

Source is
https://www.aspsnippets.com/Articles/Using-SqlBulkCopy-to-import-Excel-SpreadSheet-data-into-SQL-Server-in-ASPNet-using-C-and-VBNet.aspx
for further help visit this
Hope it  will helpful for you

Body:
SqlBulkCopy class as the name suggests does bulk insert from one source to another and hence all rows from the Excel sheet can be easily read and inserted using the SqlBulkCopy class.

<add name = "constr" connectionString = "Data
 Source=.\SQL2008R2;Database=dbname;User Id=abc;password=xxxxx"/>

I have specified the connection strings for the Excel files of both 2003 and 2007 or higher formats in the Web.Config file.

<add name = "Excel03ConString" connectionString =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel
 8.0;HDR=YES'"/>
 <add name = "Excel07+ConString" connectionString =
 "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended
  Properties='Excel 8.0;HDR=YES'"/>

The HTML Markup consists of ASP.Net FileUpload control and a Button to trigger the file upload process.

<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button Text="Upload" OnClick = "Upload" runat="server" />

You will need to import the following namespaces.

using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Configuration;

protected void Upload(object sender, EventArgs e)
{
 //Upload and save the file
  string excelPath = Server.MapPath("~/Files/") +
  Path.GetFileName(FileUpload1.PostedFile.FileName);
  FileUpload1.SaveAs(excelPath);

string conString = string.Empty;
string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
switch (extension)
{
    case ".xls": //Excel 97-03
        conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
        break;
    case ".xlsx": //Excel 07 or higher
        conString =

ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString;
        break;

}
conString = string.Format(conString, excelPath);
using (OleDbConnection excel_con = new OleDbConnection(conString))
{
    excel_con.Open();
    string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
    null).Rows[0]["TABLE_NAME"].ToString();
    DataTable dtExcelData = new DataTable();

    //[OPTIONAL]: It is recommended as otherwise the data will be considered
    as String by default.
    dtExcelData.Columns.AddRange(new DataColumn[3] { new DataColumn("Id",
    typeof(int)),
            new DataColumn("Name", typeof(string)),
            new DataColumn("Salary",typeof(decimal)) });

    using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" +
   sheet1 + "]", excel_con))
    {
        oda.Fill(dtExcelData);
    }
    excel_con.Close();

    string consString =
    ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(consString))
    {
        using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
        {
            //Set the database table name
            sqlBulkCopy.DestinationTableName = "dbo.tblPersons";

            //[OPTIONAL]: Map the Excel columns with that of the database table
            sqlBulkCopy.ColumnMappings.Add("Id", "PersonId");
            sqlBulkCopy.ColumnMappings.Add("Name", "Name");
            sqlBulkCopy.ColumnMappings.Add("Salary", "Salary");
            con.Open();
            sqlBulkCopy.WriteToServer(dtExcelData);
            con.Close();
        }
    }
}
 }

Source is
https://www.aspsnippets.com/Articles/Using-SqlBulkCopy-to-import-Excel-SpreadSheet-data-into-SQL-Server-in-ASPNet-using-C-and-VBNet.aspx
for further help visit this
Hope it  will helpful for you


问:
Java: how to trace/monitor GC times for the CMS garbage collector?
I'm having trouble figuring out a way to monitor the JVM GC for memory exhaustion issues.

With the serial GC, we could just look at the full GC pause times and have a pretty good notion if the JVM was in trouble (if it took more than a few seconds, for example).

CMS seems to behave differently.

When querying lastGcInfo from the java.lang:type=GarbageCollector,name=ConcurrentMarkSweep MXBean (via JMX), the reported duration is the sum of all GC steps, and is usually several seconds long. This does not indicate an issue with GC, to the contrary, I've found that too short GC times are usually more of an indicator of trouble (which happens, for example, if the JVM goes into a CMS-concurrent-mark-start-> concurrent mode failure loop).

I've tried jstat as well, which gives the cumulative time spent garbage collecting (unsure if it's for old or newgen GC). This can be graphed, but it's not trivial to use for monitoring purposes. For example, I could parse jstat -gccause output and calculate differences over time, and trace+monitor that (e.g. amount of time spent GC'ing over the last X minutes).

I'm using the following JVM arguments for GC logging:

```<code>-Xloggc:/xxx/gc.log
-XX:+PrintGCDetails
-verbose:gc
-XX:+PrintGCDateStamps
-XX:+PrintReferenceGC
-XX:+PrintPromotionFailure
</code>```

Parsing gc.log is also an option if nothing else is available, but the optimal solution would be to have a java-native way to get at the relevant information.

The information must be machine-readable (to send to monitoring platforms) so visual tools are not an option. I'm running a production environment with a mix of JDK 6/7/8 instances, so version-agnostic solutions are better.

Is there a simple(r) way to monitor CMS garbage collection? What indicators should I be looking at?

答:
For viewing GC logs:
If you have already enabled GC logging, I suggest GCViewer - this is an open source tool that can be used to view GC logs and look at parameters like throughput, pause times etc.

For profiling:
I don't see a JDK version mentioned in the question. For JDK 6, I would recommend visualvm to profile an application. For JDK 7/8 I would suggest mission control. You can find these in JDK\lib folder. These tools can be used to see how the application performs over a period of time and during GC (can trigger GC via visualvm UI).

Body:
I'm having trouble figuring out a way to monitor the JVM GC for memory exhaustion issues.

With the serial GC, we could just look at the full GC pause times and have a pretty good notion if the JVM was in trouble (if it took more than a few seconds, for example).

CMS seems to behave differently.

When querying lastGcInfo from the java.lang:type=GarbageCollector,name=ConcurrentMarkSweep MXBean (via JMX), the reported duration is the sum of all GC steps, and is usually several seconds long. This does not indicate an issue with GC, to the contrary, I've found that too short GC times are usually more of an indicator of trouble (which happens, for example, if the JVM goes into a CMS-concurrent-mark-start-> concurrent mode failure loop).

I've tried jstat as well, which gives the cumulative time spent garbage collecting (unsure if it's for old or newgen GC). This can be graphed, but it's not trivial to use for monitoring purposes. For example, I could parse jstat -gccause output and calculate differences over time, and trace+monitor that (e.g. amount of time spent GC'ing over the last X minutes).

I'm using the following JVM arguments for GC logging:

-Xloggc:/xxx/gc.log
-XX:+PrintGCDetails
-verbose:gc
-XX:+PrintGCDateStamps
-XX:+PrintReferenceGC
-XX:+PrintPromotionFailure

Parsing gc.log is also an option if nothing else is available, but the optimal solution would be to have a java-native way to get at the relevant information.

The information must be machine-readable (to send to monitoring platforms) so visual tools are not an option. I'm running a production environment with a mix of JDK 6/7/8 instances, so version-agnostic solutions are better.

Is there a simple(r) way to monitor CMS garbage collection? What indicators should I be looking at?


问:
How to show a image in database in the image control of Asp.net?
How to show a image in database in the image control of Asp.net? We have to show the image of employee along with his details in the asp.net page, but the issue is how to show the image on the asp.net image control for the image control takes picture by the property ImageUrl.

Kindly guide....

答:
This can also be done without creating a handler.

```<code>//get the image from the database as byte array
byte[] image = (byte[])dr["image"];

//set the ImageUrl of the Image Control as a Base64 string
Image1.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(image)
</code>```

Or if you want the with and height also, create an Image by using a MemoryStream and get the image properties.

```<code>using (MemoryStream ms = new MemoryStream(image))
{
    System.Drawing.Image imageFromDB = System.Drawing.Image.FromStream(ms);

    Image1.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(image);
    Image1.Width = imageFromDB.Width;
    Image1.Height = imageFromDB.Height;
}
</code>```

Body:
This can also be done without creating a handler.

//get the image from the database as byte array
byte[] image = (byte[])dr["image"];

//set the ImageUrl of the Image Control as a Base64 string
Image1.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(image)

Or if you want the with and height also, create an Image by using a MemoryStream and get the image properties.

using (MemoryStream ms = new MemoryStream(image))
{
    System.Drawing.Image imageFromDB = System.Drawing.Image.FromStream(ms);

    Image1.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(image);
    Image1.Width = imageFromDB.Width;
    Image1.Height = imageFromDB.Height;
}


问:
PHP Function to generate an infinite unique indentifier
I'm making a new project in Zend 3 that requires me to have a unique ID or HASH which I can use in several places later.

I looked at many examples on Google, and could not find a function that can satisfy my requirements because this needs to be 99% unique all the time, and it needs to be able to generate hundreds, millions of "hashes" unique all the time.

The following function caught my attention:

```<code>  function uniqidReal($lenght = 13) {
        // uniqid gives 13 chars, but you could adjust it to your needs.
        if (function_exists("random_bytes")) {
            $bytes = random_bytes(ceil($lenght / 2));
        } elseif (function_exists("openssl_random_pseudo_bytes")) {
            $bytes = openssl_random_pseudo_bytes(ceil($lenght / 2));
        } else {
            throw new Exception("no cryptographically secure random function available");
        }
        return substr(bin2hex($bytes), 0, $lenght);
    }
</code>```

A simple test:

```<code>echo "```";

for($i = 0; $i < 100; $i++)
{
    echo $this->uniqidReal(25) .PHP_EOL ;
}
```

<p>The result:</p>

```a8ba1942ad99d09f496d3d564
5b24746d09cada4b2dc9816bd
c6630c35bc9b4ed0907c803e0
48e04958b633e8a5ead137bb1
643a4ce1bcbca66cea397e85e
d2cd4c6f8dc7054dd0636075f
d9c78bae38720b7e0cc6361f2
54e5f852862adad2ad7bc3349
16c4e42e4f63f62bf9653f96e
c63d64af261e601e4b124e38f
29a3efa07a4d77406349e3020
107d78fdfca13571c152441f2
591b25ebdb695c8259ccc7fe9
105c4f2cc5266bb82222480ba
84e9ad8fd76226f86c89c1ac1
39381d31f494d320abc538a8e
7f8141db50a41b15a85599548
7b15055f6d9fb1228b7438d2a
659182c7bcd5b050befd3fc4c
06f70d134a3839677caa0d246
600b15c9dc53ef7a4551b8a90
a9c8af631c5361e8e1e1b8d9d
4b4b0aca3bbf15d35dd7d1050
f77024a07ee0dcee358dc1f5e
408c007b9d771718263b536e1
2de08e01684805a189224db75
c3838c034ae22d21f27e5d040
b15e9b0bab6ef6a56225a5983
251809396beb9d24b384f5fe8
cec6d262803311152db31b723
95d271ffdfe9df5861eefbaa4
7c11f3401530790b9ef510e55
e363390e2829097e7762bddc4
7ef34c69d9b8e38d72c6db29f
309a84490a7e387aaff1817ca
c214af2927c683954894365df
9f70859880b7ffa4b28265dbb
608e2f2f9e38025d92a1a4f03
c457a54d2da30a4a517edf14c
8670acbded737b1d2febdd954
99899b74b6469e366122b658c
3066408f5b4e86ef84bdb3fb9
010715f4955f66da3402bfa7b
fa01675690435b914631b46e1
2c5e234c5868799f31a6c983c
8345da31809ab2d9714a01d05
7b4e0e507dd0a8b6d7170a265
5aa71aded9fe7afa9a93a98c5
3714fb9f061398d4bb6af909d
165dd0af233cce64cefec12ed
849dda54070b868b50f356068
fe5f6e408eda6e9d429fa34ed
cd13f8da95c5b92b16d9d2781
65d0f69b41ea996ae2f8783a5
5742caf7a922eb3aaa270df30
f381ac4b84f3315e9163f169e
8c2afa1ab32b6fe402bf97ba3
a9f431efe6fc98aa64dbecbc2
8f0746e4e9529326d087f828b
bfc3cbea4d7f5c4495a14fc49
e4bf2d1468c6482570612360e
f1c7238766acdb7f199049487
60ae8a1ffd6784f7bbbc7b437
30afd67f207de6e893f7c9f42
dfa151daccb0e8d64d100f719
07be6a7d4aab21ccd9942401b
73ca1a54fcc40f7a46f46afbd
94ed2888fb93cb65d819d9d52
b7317773c6a15aa0bdf25fa01
edbb7f20f7523d9d941f3ebce
99a3c204b9f2036d3c38342bb
a0585424b8ab2ffcabee299d5
64e669fe2490522451cf10f85
18b8be34d4c560cda5280a103
9524d1f024b3c9864a3fccf75
0e7e94e7974894c98442241bc
4a17cc5e3d2baabaa338f592e
b070eaf38f390516f5cf61aa7
cc7832ea327b7426d8d2b8c2b
0df0a1d4833ebbb5d463c56bf
1bb610a8bb4e241996c9c756a
34ac2fdeb4b88fe6321a1d9c3
f0b20f8e79090dcb65195524c
307252efdd2b833228e0c301f
3908e63b405501782e629ac0b
29e66717adf14fb30c626103d
c8abd48af5f9332b322dffad0
80cd4e162bc7e8fb3a756b48c
825c00cec2294061eb328dd97
106205a2e24609652d149bc17
f1f896657fbc6f6287e7dee20
0fbd16ade658e24d69f76a225
4ab3b5eeeda86fa81afba796a
11d34f3d2ffb61d55da560ddb
013d6151bad187906fcc579a4
4509279a28f34bcf5327dd4c0
3c0eb47b3f9dc5a2f794bb9ad
1e6506906f23542c889330836
e7b1c5012390f3c7c48def9f3
d86caa695cb5fa1e0a2ead4cc
```

But I cannot confirm that this does guarantee me a 99% success rate for my production environment.

If someone can advise me, or provide me an example I would much appreciate it!

答:
This should be a comment, but its a bit long.

There is some confusion over your use of "unique" and "all the time". A token is either unique or it is not. Using a random number generator to create tokens alone is not sufficient to guarantee uniqueness - the whole point of a random number generator is that you don't know what the next value to be generated will be - meaning you also don't know that the next number won't be the same as a previous number. OTOH, using random_bytes() or openssl_random_pseudo_bytes() to generate a token which is "99% unique all the time" seems like a massive overkill.

To work out how unique this is likely to be we would need to know how many tokens will be considered within the populations at any one time (or to be able to calculate this from the expected rate of creation and the TTL).

That you are using large numbers rather implies you have a very good reason for not using the simplest and most obvious unique identifier - i.e. an incrementing integer. Hence the resistance to guessing an existing identifier is clearly critical to the implementation - but again you've told us nothing about that.

Pasting the title of your post into Google turns up your post as the top result - with PHP's uniqid() function immediately after it - yet for some reason you've either not found uniqid() or have rejected it for some reason.

The title of your post is also an oxymoron - In order to define an infinite set of identifiers, the identifiers would need to be of infinite length.

it needs to be able to generate hundreds, millions of "hashes"

....and you want it all to run within the Zend Framework? - LOL.

But I cannot confirm that this does guarantee me a 99% success rate for my production environment.

Why not? You have sufficient information here to confirm that the bitwise entropy is evenly distributed and should know the planned capacity of the production environment. The rest is basic arithmetic.

Body:
I'm making a new project in Zend 3 that requires me to have a unique ID or HASH which I can use in several places later.

I looked at many examples on Google, and could not find a function that can satisfy my requirements because this needs to be 99% unique all the time, and it needs to be able to generate hundreds, millions of "hashes" unique all the time.

The following function caught my attention:

  function uniqidReal($lenght = 13) {
        // uniqid gives 13 chars, but you could adjust it to your needs.
        if (function_exists("random_bytes")) {
            $bytes = random_bytes(ceil($lenght / 2));
        } elseif (function_exists("openssl_random_pseudo_bytes")) {
            $bytes = openssl_random_pseudo_bytes(ceil($lenght / 2));
        } else {
            throw new Exception("no cryptographically secure random function available");
        }
        return substr(bin2hex($bytes), 0, $lenght);
    }

A simple test:

echo "
";

for($i = 0; $i < 100; $i++)
{
    echo $this->uniqidReal(25) .PHP_EOL ;
}

The result:

a8ba1942ad99d09f496d3d564
5b24746d09cada4b2dc9816bd
c6630c35bc9b4ed0907c803e0
48e04958b633e8a5ead137bb1
643a4ce1bcbca66cea397e85e
d2cd4c6f8dc7054dd0636075f
d9c78bae38720b7e0cc6361f2
54e5f852862adad2ad7bc3349
16c4e42e4f63f62bf9653f96e
c63d64af261e601e4b124e38f
29a3efa07a4d77406349e3020
107d78fdfca13571c152441f2
591b25ebdb695c8259ccc7fe9
105c4f2cc5266bb82222480ba
84e9ad8fd76226f86c89c1ac1
39381d31f494d320abc538a8e
7f8141db50a41b15a85599548
7b15055f6d9fb1228b7438d2a
659182c7bcd5b050befd3fc4c
06f70d134a3839677caa0d246
600b15c9dc53ef7a4551b8a90
a9c8af631c5361e8e1e1b8d9d
4b4b0aca3bbf15d35dd7d1050
f77024a07ee0dcee358dc1f5e
408c007b9d771718263b536e1
2de08e01684805a189224db75
c3838c034ae22d21f27e5d040
b15e9b0bab6ef6a56225a5983
251809396beb9d24b384f5fe8
cec6d262803311152db31b723
95d271ffdfe9df5861eefbaa4
7c11f3401530790b9ef510e55
e363390e2829097e7762bddc4
7ef34c69d9b8e38d72c6db29f
309a84490a7e387aaff1817ca
c214af2927c683954894365df
9f70859880b7ffa4b28265dbb
608e2f2f9e38025d92a1a4f03
c457a54d2da30a4a517edf14c
8670acbded737b1d2febdd954
99899b74b6469e366122b658c
3066408f5b4e86ef84bdb3fb9
010715f4955f66da3402bfa7b
fa01675690435b914631b46e1
2c5e234c5868799f31a6c983c
8345da31809ab2d9714a01d05
7b4e0e507dd0a8b6d7170a265
5aa71aded9fe7afa9a93a98c5
3714fb9f061398d4bb6af909d
165dd0af233cce64cefec12ed
849dda54070b868b50f356068
fe5f6e408eda6e9d429fa34ed
cd13f8da95c5b92b16d9d2781
65d0f69b41ea996ae2f8783a5
5742caf7a922eb3aaa270df30
f381ac4b84f3315e9163f169e
8c2afa1ab32b6fe402bf97ba3
a9f431efe6fc98aa64dbecbc2
8f0746e4e9529326d087f828b
bfc3cbea4d7f5c4495a14fc49
e4bf2d1468c6482570612360e
f1c7238766acdb7f199049487
60ae8a1ffd6784f7bbbc7b437
30afd67f207de6e893f7c9f42
dfa151daccb0e8d64d100f719
07be6a7d4aab21ccd9942401b
73ca1a54fcc40f7a46f46afbd
94ed2888fb93cb65d819d9d52
b7317773c6a15aa0bdf25fa01
edbb7f20f7523d9d941f3ebce
99a3c204b9f2036d3c38342bb
a0585424b8ab2ffcabee299d5
64e669fe2490522451cf10f85
18b8be34d4c560cda5280a103
9524d1f024b3c9864a3fccf75
0e7e94e7974894c98442241bc
4a17cc5e3d2baabaa338f592e
b070eaf38f390516f5cf61aa7
cc7832ea327b7426d8d2b8c2b
0df0a1d4833ebbb5d463c56bf
1bb610a8bb4e241996c9c756a
34ac2fdeb4b88fe6321a1d9c3
f0b20f8e79090dcb65195524c
307252efdd2b833228e0c301f
3908e63b405501782e629ac0b
29e66717adf14fb30c626103d
c8abd48af5f9332b322dffad0
80cd4e162bc7e8fb3a756b48c
825c00cec2294061eb328dd97
106205a2e24609652d149bc17
f1f896657fbc6f6287e7dee20
0fbd16ade658e24d69f76a225
4ab3b5eeeda86fa81afba796a
11d34f3d2ffb61d55da560ddb
013d6151bad187906fcc579a4
4509279a28f34bcf5327dd4c0
3c0eb47b3f9dc5a2f794bb9ad
1e6506906f23542c889330836
e7b1c5012390f3c7c48def9f3
d86caa695cb5fa1e0a2ead4cc

But I cannot confirm that this does guarantee me a 99% success rate for my production environment.

If someone can advise me, or provide me an example I would much appreciate it!


问:
Access Violation in Multithreaded Application on Windows Server 2003
I have an application (writted using Delphi 2009) that allows a user to run a query on selected systems, then consolidates the results into a single report.

Brief Description of the app:

The user selects a query and a group of systems to run the query over. The query is run on all systems concurrently by creating a new thread to run the query in, and using TADOQuery to actually run the query from within the thread. When the query has finished running, TADOQuery.SaveToFile is called, passing pfXML as a parameter to save the results to an XML document. Once all queries have finished running, the application parses all of the XML documents and consolidates them into a single XML document. The user can then load the report, which calls TADOQuery.LoadFromFile to load the report and display it in a TListView.

In order to ensure that the user doesn't overload the PC by submitting too many queries (thereby launching too many threads), I have implemented a queue using an array of records. Each record holds information such as query name, system, status (running, finished or pending) etc. Another reason for implementing a queue is that the user can submit multiple queries at the same time (i.e. they don't have to wait for the first one to finish before submitting another). The array of records probably isn't the most efficient way of implementing the queue, but it works. I keep the number of concurrently running threads to 100 (this can be altered by the user) and launch new threads when running ones end by synchronising the completion of the query run within the thread with a procedure that manages the queue. At no point does memory usage rise about 25-30K.

The final piece of pertinent information is that the application also contains a job scheduler, which allows the user to specify when they want queries to run. This is used by customers that want to leave the software running unattended on a server and create reports on a daily basis at a certain time each day.

The problem:

The application runs fine on Windows XP. No matter how many queries are submitted. However, after a random amount of time running on Windows Server 2003, the application stops running. Attempting to interact with the application (or close it down) causes an Access Violation to be reported. I can't for the life of me work out where it's coming from or what is causing it.

My first thought was that it might have something to do with the implementation of the memory management in the operating system, but I can't see what could be causing the problem. I've compiled a version of the application using FastMM4 in full debug mode but it isn't reporting any issues with freeing memory that shouldn't have been freed or anything along those lines, and there are no memory leaks when running under normal circumstances, so although I'm still sure that there's an issue with memory management, I can't see what that would be.

I notice that after the access violations occur, there are a lot of report files in the temp folder of my application (meaning that some of the queries have run and returned results, but not all of the threads have finished and the reports haven't yet been consolidated). The job scheduler also reports that it has been running fine and submitting jobs into the queue, which haven't run because the maximum number of threads (100 by default) are running (I've been testing by submitting jobs via the scheduler every 20 minutes and leaving the application overnight).

This leads me to believe that there is probably an issue with the processing of the queue (the array of records). If a thread finishes and synchronises with the procedure that manages the queue, but there is a problem with the queue, then the next thread won't be started, and as not all of the queries have finished, the reports in the temp folder won't be consolidated. This seems to be the point at which the application is stuck.

I therefore have two problems:

1. What is causing the access violation? Is it something to do with the queue, or is it probably something else?

2. Why does the application work fine on Windows XP but falls over on Windows Server 2003?

UPDATE

I've managed to batter the application to such an extent during testing that I can now also produce the error on Windows XP, so it doesn't look like it's restricted to Windows Server 2003. It just seems to appear on Windows Server 2003 a lot faster than on XP.

If I run a group of queries over a group of systems, wait until all reports have been created, and then repeat the process, eventually, queries just stop being submitted and double clicking anywhere in the application (and trying to close down) results in an Access Violation (always write, although the memory address varies, and it isn't always write of address 0).

I've traced the callstack using MadExcept and it doesn't show anything unusual - only the line of code where the double click event is triggered.

Something is stopping the queries being submitted and also (I'd guess) causing the access violations, but I can't see what it might be.

答:
More of a troubleshooting tip than an actual answer...
For #2, is the hardware identical?  If not, this may really be an issue of single-core vs multi-core  (or processor).  Since it's a multi-threaded app, it's not unreasonable to expect it to behave differently with multiple processors/cores.  So make sure that you're not clouding the issue with too many variables (hardware vs OS).</p>


问:
Filter with VBA cells by several background colors at once
Can I filter cells with VBA by several background colors at once? The line below does not work.</p>

```<code>ActiveSheet.Range("$$A$5").AutoFilter Field:=2, Criteria1:=Array(RGB(228, 223, 236), RGB(218, 238, 243), RGB(183, 222, 232)), Operator:=xlFilterCellColor
</code>```

答:
No, you can't. At least not with the AutoFilter. You can't do it in raw Excel, Autofilter only ever lets you pick one colour.

You could write a macro that hides the unneeded rows though...

Body:
Can I filter cells with VBA by several background colors at once? The line below does not work.

ActiveSheet.Range("$$A$5").AutoFilter Field:=2, Criteria1:=Array(RGB(228, 223, 236), RGB(218, 238, 243), RGB(183, 222, 232)), Operator:=xlFilterCellColor


问:
Redis data recovery from Append Only File?
If we enable the AppendFileOnly in the redis.conf file, every operation which changes the redis database is loggged in that file.

Now, Suppose Redis has used all the memory allocated to it in the "maxmemory" direcive in the redis.conf file.

To store more data., it starts removing data by any one of the behaviours(volatile-lru, allkeys-lru etc.) specified in the redis.conf file.

Suppose some data gets removed from the main memory, But its log will still be there in the AppendOnlyFile(correct me if I am wrong). Can we get that data back using this AppendOnlyFile ?

Simply, I want to ask that if there is any way we can get that removed data back in the main memory ? Like Can we store that data into disk memory and load that data in the main memory when required.

答:
But its log will still be there in the AppendOnlyFile(correct me if I am wrong). Can we get that data back using this AppendOnlyFile ?

NO, you CANNOT get the data back. When Redis evicts a key, it also appends a delete command to AOF. After rewriting the AOF, anything about the evicted key will be removed.

if there is any way we can get that removed data back in the main memory ? Like Can we store that data into disk memory and load that data in the main memory when required.

NO, you CANNOT do that. You have to take another durable data store (e.g. Mysql, Mongodb) for saving data to disk, and use Redis as cache.


问:
ping multiple sub nets / bash
I'm trying to ping multiple sub nets
what I'm doing now is simply repeating the loop
but I believe should be much simpler solution to do it in one loop</p>

```<code>for i in 192.168.0.{1..254}
do
echo $1 >> live_host_list & disown
done
echo "net 192.168.0.0 Scanned"
echo "starting 10.0.0.0 network"
for i in 10.0.0.{1..254}
do
echo $1 >> live_host_list & disown
done
echo "net 10.0.0.0 Scanned"
</code>```

答:
```<code>   subnetlist=("10.0.0." "10.0.1." "192.168.5.")
 for subn in "${subnetlist[@]}"; do
        echo "starting ${subn}0 network"
        for oct in {1..254}; do
            echo "${subn}${oct}" & disown
       done
    echo "net ${subnetlist}0 Scanned"
    done
</code>```

Title: ping multiple sub nets / bash

Body:
I'm trying to ping multiple sub nets
what I'm doing now is simply repeating the loop
but I believe should be much simpler solution to do it in one loop

for i in 192.168.0.{1..254}
do
echo $1 >> live_host_list & disown
done
echo "net 192.168.0.0 Scanned"
echo "starting 10.0.0.0 network"
for i in 10.0.0.{1..254}
do
echo $1 >> live_host_list & disown
done
echo "net 10.0.0.0 Scanned"


问:
Python nested dict comprehension
I have a dictionary:

```<code>my_dict = {'a': [1, 2, 3], 'c': 3, 'b': 2}
</code>```

And I want a comprehension like add_dict = (x x +1 for x my_dict)
what would be the best approach to take when writing a comprehension to deal with keys with multiple values?

So the output would look like {'a': [2, 3, 4], 'c': 4, 'b':3} or maybe I might want to only +1 to values 1 and 2 of each key, keys 'b' and 'c' ... would be skipped.

I tried this (first two lines are kind redundant / was messing about)

```<code>my_dict = {'a': [1, 2, 3], 'b': 2, 'c': 3}
    D = {x: y for (x, y) in zip(my_dict.keys(), my_dict.values())}
    test = (v for v in D.values())

    for x in test:
        try:
            if len(x):
               for i in x:
                   print i +1
        except:
            print x +1
</code>```

if name == 'main':
    main()
output was

2
3
4
object of type 'int' has no len()
object of type 'int' has no len()

I was trying to find a more elegant way of doing this that worked using comprehensions.

答:
Here's a one-liner for you (in Python 3), assuming the dictionary values never become double-nested:

```<code>>>> {k:([x+1 for x in v] if not isinstance(v,int) else v+1) for k,v in my_dict.items()}
{'a': [2, 3, 4], 'b': 3, 'c': 4}
</code>```

Replace my_dict.items() with my_dict.iteritems() for Python 2

Title: Python nested dict comprehension

Body:
I have a dictionary:

my_dict = {'a': [1, 2, 3], 'c': 3, 'b': 2}

And I want a comprehension like add_dict = (x x +1 for x my_dict)
what would be the best approach to take when writing a comprehension to deal with keys with multiple values?

So the output would look like {'a': [2, 3, 4], 'c': 4, 'b':3} or maybe I might want to only +1 to values 1 and 2 of each key, keys 'b' and 'c' ... would be skipped.

I tried this (first two lines are kind redundant / was messing about)

my_dict = {'a': [1, 2, 3], 'b': 2, 'c': 3}
    D = {x: y for (x, y) in zip(my_dict.keys(), my_dict.values())}
    test = (v for v in D.values())

    for x in test:
        try:
            if len(x):
               for i in x:
                   print i +1
        except:
            print x +1

if name == 'main':
    main()
output was

2
3
4
object of type 'int' has no len()
object of type 'int' has no len()

I was trying to find a more elegant way of doing this that worked using comprehensions.

Body:
Here's a one-liner for you (in Python 3), assuming the dictionary values never become double-nested:

>>> {k:([x+1 for x in v] if not isinstance(v,int) else v+1) for k,v in my_dict.items()}
{'a': [2, 3, 4], 'b': 3, 'c': 4}

Replace my_dict.items() with my_dict.iteritems() for Python 2


问:
Jquery click event doesn't fire with Handlebars template
I have a problem with Jquery .on() function and Handlebars template. I wroted Handlebars template and add him dynamically in document:

```<code>$('.services-wrapper').append(serviceTemplate({index : ++maxIndex}));
</code>```

This template has a button:

```<code><p>
    <?= Html::buttonInput('Delete', [
    'class' => 'btn btn-danger delete-service',
    'id' => 'js-delete-service',
        'data' => [
        'index' => $index,
    ],
    ]) ?>
</p>
</code>```

So I wroted click handler on this button:

```<code>$('.service').on('click', '.delete-service', function (e) {
    alert('Clicked');
    //$(this).parent().parent().remove();
});
</code>```

When I add this template to document, click event doesn't fire. What is the problem?

答:
```<code>$("body").on('click','.delete-service',function(){
     alert('Clicked');
});
</code>```

Try this

Body:
I have a problem with Jquery .on() function and Handlebars template. I wroted Handlebars template and add him dynamically in document:

$('.services-wrapper').append(serviceTemplate({index : ++maxIndex}));

This template has a button:

    <?= Html::buttonInput('Delete', [
    'class' => 'btn btn-danger delete-service',
    'id' => 'js-delete-service',
        'data' => [
        'index' => $index,
    ],
    ]) ?>

So I wroted click handler on this button:

$('.service').on('click', '.delete-service', function (e) {
    alert('Clicked');
    //$(this).parent().parent().remove();
});

When I add this template to document, click event doesn't fire. What is the problem?

Body:
$("body").on('click','.delete-service',function(){
     alert('Clicked');
});

Try this


问:
Mutator/Accessor methods for object variable declared in private
I have a couple object variables declared in private of a class:

```<code>private:
a a1;
</code>```

This overloaded operator was originally friends with this class and accessed the objects as shown bellow:

```<code>istream & operator >>( istream & input, class & m )
{
    input >> m.a1;
    return input;
 }
  ostream & operator <<( ostream & os, const class & m )
 {
     os << m.uni;

     return os;
 }
</code>```

When the operator is unfriended it should no longer have access to the private variables.

How would I access the two objects? Would it be the use of accessor/mutator methods that return pointers to the object?

EDIT: changed the code so it explains the question a bit more.

答:
The point of the whole accessor idea is to prevent a programmer using a class from doing something he is not supposed to do. Something that the writer of said class did not anticipate.

Private functions by definition are not for use by "everyone using the class". For example it means stuff like input validity checks are not in place - because the code calling the private function is supposed to do those checks (this aviods checking for the same cases multiple times. But run the risk of unchecked results being entered if everyone has access).

Yes, you could work around accessors by throwing naked pointers at the problem. Access rights are only checked by the compiler at compile time and it can not predict wich function would be at "adress XYZ" at compile time.

But if you even consdier it, you are on the wrong track. There is a damn good reason the operator was unfriended. Propably because he kept doing stuff a friend was not supposed to do.
Friends and protected are two very speicific cases where you have a private with a few select exceptions.

Do you have control of both classes? If so, why are you removing the friend state?

If you do not have control: What did you do to loose friend status? And why would you go to such lenghts to outright sabotage the proper working of the class via naked pointers?

Body:
I have a couple object variables declared in private of a class:

private:
a a1;

This overloaded operator was originally friends with this class and accessed the objects as shown bellow:

istream & operator >>( istream & input, class & m )
{
    input >> m.a1;
    return input;
 }
  ostream & operator <<( ostream & os, const class & m )
 {
     os << m.uni;

     return os;
 }

When the operator is unfriended it should no longer have access to the private variables.

How would I access the two objects? Would it be the use of accessor/mutator methods that return pointers to the object?

EDIT: changed the code so it explains the question a bit more.


问:
Slime: the symbol "HOST-ENT-ADDRESS-TYPE" is not external in the SB-BSD-SOCKETS package
this is an error message that suddenly prevents me from using Slime:

; loading #P"/home/vince/quicklisp/dists/quicklisp/software/slime-v2.19/swank-loader.lisp"
;
; caught ERROR:
;   READ error during COMPILE-FILE:
;

;     The symbol "HOST-ENT-ADDRESS-TYPE" is not external in the SB-BSD-SOCKETS package.
;

;       Line: 117, Column: 76, File-Position: 3633
;

;       Stream: #<SB-SYS:FD-STREAM
;                 for "file /home/vince/quicklisp/dists/quicklisp/software/slime-v2.19/swank/sbcl.lisp"
;                 {10065BF923}>
;;
;; Error compiling /home/vince/quicklisp/dists/quicklisp/software/slime-v2.19/swank/sbcl.lisp:
;;   COMPILE-FILE returned NIL.
;

Do you have any idea of what's causing it and what I can do ? Thanks.

update: happened a second time, supposedly after a quicklisp update.

答:
The error message was explicit on the error location ("file /home/vince/quicklisp/dists/quicklisp/software/slime-v2.19/swank/sbcl.lisp") and Tamas' suggestion was a good one.

I created a symlink from slime-v2.18/swank/sbcl.lisp to its slime-v2.19 counterpart (I already had those two versions installed) and I can connect again to slime.

Removing the slime v2.19 directory was no good.

I still don't know why this stopped working and I don't have a cleaner workaround.


问:
something difficult when using ng-repeat with angular
I'm have two problem when using angular.

 I using ng-repeat to show all my item in database , but I want when click in img , go to review page , I have 30 item , but instead write 30 review page , is there another way better than it ? I'm using angular-ui  router

here is my code to show

```<code><tr ng-repeat ="data in mydata">
<td>{{data.code}}</td>
<td>{{data.name}}</td>
<td>{{data.price}}</td>
<td> <img ng-src={{data.img}}/>
</tr>
</code>```

I want when click img1 , go to url/code1 , click img2 , go to url/code2

And problem two is admin page

 I have form insert item in admin page , but I want when insert success , auto create review page item it . How can i do that.

Pls help me . Thank in advance

答:
in html you can use ui-sref="review({id: itemid})"

and in angular

```<code>state('/,{
  url:'yoururl/{review}',

}
</code>```

Body:
I'm have two problem when using angular.

 I using ng-repeat to show all my item in database , but I want when click in img , go to review page , I have 30 item , but instead write 30 review page , is there another way better than it ? I'm using angular-ui  router

here is my code to show

{{data.code}}
{{data.name}}
{{data.price}}

I want when click img1 , go to url/code1 , click img2 , go to url/code2

And problem two is admin page

 I have form insert item in admin page , but I want when insert success , auto create review page item it . How can i do that.

Pls help me . Thank in advance

Body:
in html you can use ui-sref="review({id: itemid})"

and in angular

state('/,{
  url:'yoururl/{review}',

}