问:
"TypeError: Cannot set property 'VibrantImg' in RactiveJS adaptor
I'm trying to create a simple Ractive adaptor to parse a value from the Color Thief (http://lokeshdhakar.com/projects/color-thief/) into a template with a defined mustache. (I know there may be better ways to achieve this, but there is a reason for why I'm using the adaptor route!)

I've set up a demo of what I have so far here - this the Ractive code part:

```<code>var colorThief = new ColorThief();
var img2 = document.getElementById('ctimage');
var imgColor;

Ractive.adapt.CTImg = {
  filter: function ( object ) {
    return object instanceof img2;
  },
  wrap: function ( ractive, img2, keypath, prefixer ) {
   // Setup

   return {
     teardown: function(){
       colorThief.destroy();
     },
     get: function(){
       imgColor = colorThief.getColor(img);
     },
     set: function(property, value){
       ractive.set('mainColor', imgColor);
     },
     reset: function(value){
     }
   }
  }
};

var ractive = new Ractive({
  target: '#container',
  template: '#template',
  adapt: [ 'CTImg' ],
  data: {
    mainColor: "rgb(97, 79, 112)"   // this is what should be returned
  }
});
</code>```

My aim is to get the prominent color from the image given in the Codepen (above), pass it into Ractive (and to Color Thief by the adaptor), then output the resulting color on screen in the relevant mustache.

I can display a hard coded color OK in the template, so I know that the data keypath / reference is OK. However, my issue is getting the color back from Color Thief via the adaptor - the error I'm getting is Uncaught "TypeError: Cannot set property 'CTImg' of undefined".

I've checked through SO and the Ractive Github site to see if I can figure out what is going wrong, but my head is starting to spin!

Can anyone please help me to at least get the color to come back from Color Thief via the adaptor?

答:
So adapt and adaptors are two different config objects. adaptors is a registry of adaptor definitions and adapt tells the component/instance what adaptors to use. There's no global adapt property.

For global registration of an adaptor, you need Ractive.adaptors.

```<code>Ractive.adaptors.CTImg = {...}
</code>```

The next problem is actually how you use the adaptor. Adaptors require you to put the non-POJO data into the instance. The filter is run on the data and determines if the data needs to be adapted, and if so, does the setup. Then, it's the usual adaptor setup. get returns the value to Ractive, set sets the value to your custom object, etc.

Here's an updated example:

```<code>Ractive.adaptors.CTImg = {
  filter: function ( object ) {
    // Detect if the data is an image element
    return object instanceof HTMLImageElement;
  },
  wrap: function ( ractive, object, keypath, prefixer ) {
    // Set up color thief for this piece of data because it's an image
    var colorThief = new ColorThief();

    return {
      teardown: function(){
        colorThief.destroy();
      },
      get: function(){
        // Return the replacement data
        return colorThief.getColor(object);
      },
      set: function(property, value){
        // We're not setting to color thief, leave empty
      },
      reset: function(value){
        // Always replace the data when the data is changed
        return false;
      }
    }
  }
};

var ractive = new Ractive({
  target: '#container',
  template: '#template',
  adapt: [ 'CTImg' ],
  data: {
    dominant: null
  },
  onrender: function(){
    // set image on data. adaptor will capture it.
    this.set('dominant', this.find('#ctimage'))
  }
});
</code>```

Body:
I'm trying to create a simple Ractive adaptor to parse a value from the Color Thief (http://lokeshdhakar.com/projects/color-thief/) into a template with a defined mustache. (I know there may be better ways to achieve this, but there is a reason for why I'm using the adaptor route!)

I've set up a demo of what I have so far here - this the Ractive code part:

var colorThief = new ColorThief();
var img2 = document.getElementById('ctimage');
var imgColor;

Ractive.adapt.CTImg = {
  filter: function ( object ) {
    return object instanceof img2;
  },
  wrap: function ( ractive, img2, keypath, prefixer ) {
   // Setup

   return {
     teardown: function(){
       colorThief.destroy();
     },
     get: function(){
       imgColor = colorThief.getColor(img);
     },
     set: function(property, value){
       ractive.set('mainColor', imgColor);
     },
     reset: function(value){
     }
   }
  }
};

var ractive = new Ractive({
  target: '#container',
  template: '#template',
  adapt: [ 'CTImg' ],
  data: {
    mainColor: "rgb(97, 79, 112)"   // this is what should be returned
  }
});

My aim is to get the prominent color from the image given in the Codepen (above), pass it into Ractive (and to Color Thief by the adaptor), then output the resulting color on screen in the relevant mustache.

I can display a hard coded color OK in the template, so I know that the data keypath / reference is OK. However, my issue is getting the color back from Color Thief via the adaptor - the error I'm getting is Uncaught "TypeError: Cannot set property 'CTImg' of undefined".

I've checked through SO and the Ractive Github site to see if I can figure out what is going wrong, but my head is starting to spin!

Can anyone please help me to at least get the color to come back from Color Thief via the adaptor?

Body:
So adapt and adaptors are two different config objects. adaptors is a registry of adaptor definitions and adapt tells the component/instance what adaptors to use. There's no global adapt property.

For global registration of an adaptor, you need Ractive.adaptors.

Ractive.adaptors.CTImg = {...}

The next problem is actually how you use the adaptor. Adaptors require you to put the non-POJO data into the instance. The filter is run on the data and determines if the data needs to be adapted, and if so, does the setup. Then, it's the usual adaptor setup. get returns the value to Ractive, set sets the value to your custom object, etc.

Here's an updated example:

Ractive.adaptors.CTImg = {
  filter: function ( object ) {
    // Detect if the data is an image element
    return object instanceof HTMLImageElement;
  },
  wrap: function ( ractive, object, keypath, prefixer ) {
    // Set up color thief for this piece of data because it's an image
    var colorThief = new ColorThief();

    return {
      teardown: function(){
        colorThief.destroy();
      },
      get: function(){
        // Return the replacement data
        return colorThief.getColor(object);
      },
      set: function(property, value){
        // We're not setting to color thief, leave empty
      },
      reset: function(value){
        // Always replace the data when the data is changed
        return false;
      }
    }
  }
};

var ractive = new Ractive({
  target: '#container',
  template: '#template',
  adapt: [ 'CTImg' ],
  data: {
    dominant: null
  },
  onrender: function(){
    // set image on data. adaptor will capture it.
    this.set('dominant', this.find('#ctimage'))
  }
});


来源: stackexchange

问:
IIS 7.5 Rewrite module loop
I'm having trouble with the this url rewrite rule in iis 7.5:

```<code><rewrite>
    <rewriteMaps configSource="rewriteMap.Custom.config" />
    <rules>
        <rule name="Redirects" patternSyntax="ECMAScript" stopProcessing="true">
            <match url=".*" />
            <conditions>
                <add input="{Custom:{REQUEST_URI}}" pattern="(.*)" />
            </conditions>
            <action type="Redirect" url="{C:1}" appendQueryString="false" redirectType="Permanent" />
        </rule>
    </rules>
</rewrite>
<httpRedirect enabled="true" destination="https://www.newsite.com" exactDestination="true" />
</code>```

rewriteMap.Custom.config:

```<code><rewriteMaps>
    <rewriteMap name="Custom">
        <add key="/home" value="https://www.newsite.com/index" />
        <add key="/contact" value="https://www.newsite.com/contactus" />
        <add key="/main" value="https://www.newsite.com/mainpage" />
    <rewriteMaps>
<rewriteMap>
</code>```

All the redirects in the rewrite map work, for example:

www.oldsite.com/home redirects correctly to www.newsite.com/index

The only exception is when I type in www.oldsite.com it does not redirect
to www.newsite.com, instead, it keeps looping thru requests to www.oldsite.com and Chrome gives a "Too many redirects" error.

I tried modifying the rule but I only broke it to the point of it not working at all.

答:
You rewrite maps config should be like that:

```<code><rewriteMaps>
    <rewriteMap name="Custom">
        <add key="/" value="https://www.newsite.com/" />
        <add key="/home" value="https://www.newsite.com/index" />
        <add key="/contact" value="https://www.newsite.com/contactus" />
        <add key="/main" value="https://www.newsite.com/mainpage" />
    </rewriteMap>
</rewriteMaps>
</code>```

And your rules section in web.config should be like that:

```<code><rules>
    <rule name="Redirects" patternSyntax="ECMAScript" stopProcessing="true">
        <match url=".*" />
        <conditions>
            <add input="{Custom:{REQUEST_URI}}" pattern="(.+)" />
        </conditions>
        <action type="Redirect" url="{C:1}" appendQueryString="false" redirectType="Permanent" />
    </rule>
</rules>
</code>```

Problem was in the wrong pattern

ContentLicense: CC BY-SA 3.0

Title: IIS 7.5 Rewrite module loop

Body:
I'm having trouble with the this url rewrite rule in iis 7.5:

<rewrite>
    <rewriteMaps configSource="rewriteMap.Custom.config" />
    <rules>
        <rule name="Redirects" patternSyntax="ECMAScript" stopProcessing="true">
            <match url=".*" />
            <conditions>
                <add input="{Custom:{REQUEST_URI}}" pattern="(.*)" />
            </conditions>
            <action type="Redirect" url="{C:1}" appendQueryString="false" redirectType="Permanent" />
        </rule>
    </rules>
</rewrite>
<httpRedirect enabled="true" destination="https://www.newsite.com" exactDestination="true" />

rewriteMap.Custom.config:

<rewriteMaps>
    <rewriteMap name="Custom">
        <add key="/home" value="https://www.newsite.com/index" />
        <add key="/contact" value="https://www.newsite.com/contactus" />
        <add key="/main" value="https://www.newsite.com/mainpage" />
    <rewriteMaps>
<rewriteMap>

All the redirects in the rewrite map work, for example:

www.oldsite.com/home redirects correctly to www.newsite.com/index

The only exception is when I type in www.oldsite.com it does not redirect
to www.newsite.com, instead, it keeps looping thru requests to www.oldsite.com and Chrome gives a "Too many redirects" error.

I tried modifying the rule but I only broke it to the point of it not working at all.

Body:
You rewrite maps config should be like that:

<rewriteMaps>
    <rewriteMap name="Custom">
        <add key="/" value="https://www.newsite.com/" />
        <add key="/home" value="https://www.newsite.com/index" />
        <add key="/contact" value="https://www.newsite.com/contactus" />
        <add key="/main" value="https://www.newsite.com/mainpage" />
    </rewriteMap>
</rewriteMaps>

And your rules section in web.config should be like that:

<rules>
    <rule name="Redirects" patternSyntax="ECMAScript" stopProcessing="true">
        <match url=".*" />
        <conditions>
            <add input="{Custom:{REQUEST_URI}}" pattern="(.+)" />
        </conditions>
        <action type="Redirect" url="{C:1}" appendQueryString="false" redirectType="Permanent" />
    </rule>
</rules>

Problem was in the wrong pattern


问:
How to get Response variables in a Laravel PHPUnit test?
I am testing a controller method and I am accessing a route in a test.

Then I would like to make sure that the correct model was returned in the view and was loaded with all of the correct relationships.

I know that I can do this:

```<code>$this->assertViewHas("content");
</code>```

But can how can I verify that the content model that was returned into the view has the correct, for example, category? i.e. how can I get the content model object and then do something like

```<code>$this->assertEquals($content->category->name, "category 1");
</code>```

?

答:
You can get your content from the response like this:

$content = $response->getOriginalContent()->getData()['content'];
```

getData() returns the data sent to the view as an array.

Body:
I am testing a controller method and I am accessing a route in a test.

Then I would like to make sure that the correct model was returned in the view and was loaded with all of the correct relationships.

I know that I can do this:

$this->assertViewHas("content");

But can how can I verify that the content model that was returned into the view has the correct, for example, category? i.e. how can I get the content model object and then do something like

$this->assertEquals($content->category->name, "category 1");

?

Body:
You can get your content from the response like this:

$content = $response->getOriginalContent()->getData()['content'];

getData() returns the data sent to the view as an array.

ContentLicense: CC BY-SA 4.0


问:
How to prevent style propagation to the next LI element?
I have an article with a list (ol) of sentences, one per line. A user can hit Enter to create another sentence on a new line, which appends a new li. A user can also emphasize some text in a sentence (using a button, but it's irrelevant for the sake of the question). The problem is that when hitting Enter after an emphasized text, the next li also "inherits" the emphasis. How can I make the new lis vanilla?

HTML

```<code><article id="xml" contenteditable="true">
  <ol>
    <li>hello</li>
    <li><em>world</em></li>
  </ol>
</article>
</code>```

CSS

```<code>body {
  counter-reset: item !important;
}

article#xml ol {
  list-style: none;
}

article#xml ol li {
  line-height: 1.5;
  font-family: sans-serif;
  margin-top: 14px;
  counter-increment: item;
}

#xml ol li:before {
  content: counter(item);
  color: #888;
  border-right: solid 1px #c4c4c4;
  margin-right: 14px;
  text-align: center;
  font-size: 12px;
  display: inline-block;
}
</code>```

E.g. adding an item after 'hello' creates a vanilla li, while doing so after 'world' creates an emphasized one.

Demo

答:
I've managed to do it by disabling the default browser callback, and implementing everything manually. This also solved another bug I had (hitting Enter twice in a row would remove an li, instead of creating a new one).

```<code>$('#xml').on('keydown', function(e) {
  // 13 is Enter
  if(e.keyCode == 13) {
    e.preventDefault();

    // traverse ancestors till the LI
    let oldLi = document.getSelection().anchorNode;
    while (oldLi.nodeName != 'LI') {
      oldLi = oldLi.parentNode;
    }
    const newLi = document.createElement('li');
    $(oldLi).after(newLi);

    // set cursor to the beginning of the new LI
    const range = document.createRange();
    const sel = window.getSelection();
    const newText = document.createTextNode('');
    newLi.appendChild(newText);
    range.setStart(newText, 0);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
  }
});
</code>```

The only downside is that the cursor is first shifted before the number, and returns to its correct position after the first char entered.

Demo

Body:
I have an article with a list (ol) of sentences, one per line. A user can hit Enter to create another sentence on a new line, which appends a new li. A user can also emphasize some text in a sentence (using a button, but it's irrelevant for the sake of the question). The problem is that when hitting Enter after an emphasized text, the next li also "inherits" the emphasis. How can I make the new lis vanilla?

HTML

hello

world

CSS

body {
  counter-reset: item !important;
}

article#xml ol {
  list-style: none;
}

article#xml ol li {
  line-height: 1.5;
  font-family: sans-serif;
  margin-top: 14px;
  counter-increment: item;
}

#xml ol li:before {
  content: counter(item);
  color: #888;
  border-right: solid 1px #c4c4c4;
  margin-right: 14px;
  text-align: center;
  font-size: 12px;
  display: inline-block;
}

E.g. adding an item after 'hello' creates a vanilla li, while doing so after 'world' creates an emphasized one.

Demo

Body:
I've managed to do it by disabling the default browser callback, and implementing everything manually. This also solved another bug I had (hitting Enter twice in a row would remove an li, instead of creating a new one).

$('#xml').on('keydown', function(e) {
  // 13 is Enter
  if(e.keyCode == 13) {
    e.preventDefault();

    // traverse ancestors till the LI
    let oldLi = document.getSelection().anchorNode;
    while (oldLi.nodeName != 'LI') {
      oldLi = oldLi.parentNode;
    }
    const newLi = document.createElement('li');
    $(oldLi).after(newLi);

    // set cursor to the beginning of the new LI
    const range = document.createRange();
    const sel = window.getSelection();
    const newText = document.createTextNode('');
    newLi.appendChild(newText);
    range.setStart(newText, 0);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
  }
});

The only downside is that the cursor is first shifted before the number, and returns to its correct position after the first char entered.

Demo


问:
Which is more efficient: Python docstrings or type-hints?
I want to add some support for auto-completion to my Python code with Jedi. This can be done by using either function docstrings or type hints (or both).

```<code>def function_with_types_in_docstring(param1, param2):
    """Example function with types documented in the docstring.

    :type param1: int
    :type param2: str
    :rtype: bool
    """

def function_with_pep484_type_annotations(param1: int, param2: str) -> bool:
    """Example function with PEP 484 type annotations."""
</code>```

Which method of documenting types adds less overhead in terms of memory usage and running time? I'm interested in the efficiency of the Python code itself first, then Jedi.

答:
Not a proper answer but for the autocompletion part alone, neither docstrings nor type hints are required. Also note that you'll find very very very few "type-hinted" code in the stdlib and 3rd part packages anyway.

Finally and FWIW : I've been using Jedi in Emacs for quite a few years now and never had performance issues so I don't think you should really worry...

Body:
I want to add some support for auto-completion to my Python code with Jedi. This can be done by using either function docstrings or type hints (or both).

def function_with_types_in_docstring(param1, param2):
    """Example function with types documented in the docstring.

    :type param1: int
    :type param2: str
    :rtype: bool
    """

def function_with_pep484_type_annotations(param1: int, param2: str) -> bool:
    """Example function with PEP 484 type annotations."""

Which method of documenting types adds less overhead in terms of memory usage and running time? I'm interested in the efficiency of the Python code itself first, then Jedi.


问:
Using Entity manager and JPA, returns object only
When i run the following code it was return only object list. i want the list in vehicle. what is the error in my code?

My Dao Class Is:

```<code>public class VehicleDao {

HibernateTemplate template;
private EntityManager emManager;

@PersistenceContext
public void setEm(EntityManager emManager) {
    this.emManager = emManager;
}
public List<Vehicle> getVehicleDataUsing_Sp()
{
Properties prop= new Properties();
    try {
        InputStream input = new FileInputStream("E:\\spring4AndHibernate5\\src\\Query.properties");
        prop.load(input);
        Query query = emManager.createNativeQuery(prop.getProperty("vehicleQuery"));
        List<Vehicle> list = query.getResultList();
        return list;
        }
}
</code>```

答:
Because it's a native query, it doesn't know what to try mapping it to, unless you tell it.

Try:

```<code>Query query = emManager.createNativeQuery(prop.getProperty("vehicleQuery"), Vehicle.class);
</code>```

Body:
When i run the following code it was return only object list. i want the list in vehicle. what is the error in my code?

My Dao Class Is:

public class VehicleDao {

HibernateTemplate template;
private EntityManager emManager;

@PersistenceContext
public void setEm(EntityManager emManager) {
    this.emManager = emManager;
}
public List<Vehicle> getVehicleDataUsing_Sp()
{
Properties prop= new Properties();
    try {
        InputStream input = new FileInputStream("E:\\spring4AndHibernate5\\src\\Query.properties");
        prop.load(input);
        Query query = emManager.createNativeQuery(prop.getProperty("vehicleQuery"));
        List<Vehicle> list = query.getResultList();
        return list;
        }
}

Body:
Because it's a native query, it doesn't know what to try mapping it to, unless you tell it.

Try:

Query query = emManager.createNativeQuery(prop.getProperty("vehicleQuery"), Vehicle.class);


问:
Android currency localization based upon download location
We want to launch an Android app that captures currency based upon where the app is downloaded.

Of course we can get currency based upon device locale, but the issue is that many users around the world set locale as English (US) but the user could still be in india for example, but we don't want currency symbol to be dollar we want that to be indian rupee.

答:
I would suggest you to get the Locale based on the Country Code which you can easily get from the TELEPHONY_SERVICE from the code as below:

```<code>TelephonyManager teleMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
String countryCode = teleMgr.getSimCountryIso();
</code>```

Next, you can get the locale from the countryCode you get using the below snippet:

```<code>Locale loc = new Locale(countryCode.toUpperCase());
</code>```

Hope this helps you out.

Body:
I would suggest you to get the Locale based on the Country Code which you can easily get from the TELEPHONY_SERVICE from the code as below:

TelephonyManager teleMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
String countryCode = teleMgr.getSimCountryIso();

Next, you can get the locale from the countryCode you get using the below snippet:

Locale loc = new Locale(countryCode.toUpperCase());

Hope this helps you out.


问:
How to create animated gif in .NET Core
How can I create animated gif from multiple jpeg-s in ASP.NET Core?

I prefer library that is not attach to windows environment.

答:
You should try using Magick.Net which is a good image manipulation library and is also available for .net core.  An example of how to create a .gif can be found here.

To add Magick.Net to your .net core project you'll need to modify your project.json as follows:

```<code>"dependencies":
{
   "Magick.NET.Core-Q8": "7.0.0.0102"
}
</code>```

Hope this helps!

Title: How to create animated gif in .NET Core

Body:
You should try using Magick.Net which is a good image manipulation library and is also available for .net core.  An example of how to create a .gif can be found here.

To add Magick.Net to your .net core project you'll need to modify your project.json as follows:

"dependencies":
{
   "Magick.NET.Core-Q8": "7.0.0.0102"
}

Hope this helps!


问:
Why the Broadcast receiver does not work after killing Android app?
I am using a broadcast receiver in my app to record calls. Everything works fine in Android 5.0 emulator device. If I kill the app, it automatically starts recording calls. But the same app when I installed on my device running Android 6.0, it works until the app is running. When I kill the app the recording is not started, the broadcast receiver is not triggered.</p>

答:
String manufacturer = "xiaomi";

```<code> if(manufacturer.equalsIgnoreCase(android.os.Build.MANUFACTURER)) {
        //this will open auto start screen where user can enable
             permission for your app
                Intent intent = new Intent();
                intent.setComponent(new
                ComponentName("com.miui.securitycenter",
               "com.miui.permcenter.autostart.AutoStartManagementActivity"));
                startActivity(intent);
            }
</code>```

I used this code and now its working fine.

Body:
String manufacturer = "xiaomi";

 if(manufacturer.equalsIgnoreCase(android.os.Build.MANUFACTURER)) {
        //this will open auto start screen where user can enable
             permission for your app
                Intent intent = new Intent();
                intent.setComponent(new
                ComponentName("com.miui.securitycenter",
               "com.miui.permcenter.autostart.AutoStartManagementActivity"));
                startActivity(intent);
            }

I used this code and now its working fine.


问:
if form in exceptions: TypeError: unhashable type: 'list' in Python nltk
I got following error.

```<code> if form in exceptions: TypeError: unhashable type: 'list'
</code>```

Following is my code.

```<code>from nltk.tokenize import word_tokenize
from nltk.stem.wordnet import WordNetLemmatizer

sentence = 'missed you'
w_tokenize = (word_tokenize(sentence))

for word in w_tokenize:
  print WordNetLemmatizer().lemmatize(w_tokenize,'v')
</code>```

Can anyone tell me how can I fix this error.

答:
Seems like you have the variables mixed up, it should be </p>

```<code>for word in w_tokenize:
  print WordNetLemmatizer().lemmatize(word,'v')
</code>```

Body:
I got following error.

 if form in exceptions: TypeError: unhashable type: 'list'

Following is my code.

from nltk.tokenize import word_tokenize
from nltk.stem.wordnet import WordNetLemmatizer

sentence = 'missed you'
w_tokenize = (word_tokenize(sentence))

for word in w_tokenize:
  print WordNetLemmatizer().lemmatize(w_tokenize,'v')

Can anyone tell me how can I fix this error.

Body:
Seems like you have the variables mixed up, it should be

for word in w_tokenize:
  print WordNetLemmatizer().lemmatize(word,'v')


问:
Replace multiple characters with multiple replacers in Perl
I am updating a piece of code to read a table into R. The delimiters in the table should be semicolons. Some of the elements in the table have semicolons and should be replaced with colons. At the same time, the code is replacing tabs with semicolons and this should be kept.

The current script has the line

```<code>sprintf("%s -e '%s' | perl -pe 's/\t/;/g' > %s", hive.cmd, sql, tmp_file)
</code>```

and should be updated to, in order:

Replace ; with :

Replace \t with ;

Edit: I should add I have no experience in Perl.

答:
Perl has the "transliteration" operator (tr/.../.../) for doing work like this.

```<code>$string =~ tr/\t;/;:/;
</code>```

Using the substitution operator for this is overkill.

Body:
I am updating a piece of code to read a table into R. The delimiters in the table should be semicolons. Some of the elements in the table have semicolons and should be replaced with colons. At the same time, the code is replacing tabs with semicolons and this should be kept.

The current script has the line

sprintf("%s -e '%s' | perl -pe 's/\t/;/g' > %s", hive.cmd, sql, tmp_file)

and should be updated to, in order:

Replace ; with :

Replace \t with ;

Edit: I should add I have no experience in Perl.

Body:
Perl has the "transliteration" operator (tr/.../.../) for doing work like this.

$string =~ tr/\t;/;:/;

Using the substitution operator for this is overkill.


问:
How to manage shared_ptr that points to internal data of already referenced object?
Suppose I have these classes:

```<code>struct Engine {
  int engine_data;
};

struct Car {
  shared_ptr<Engine> engine;
  int car_data;
};
</code>```

For performance reasons, I want to make them tightly packed in memory (but I don't want to lose the flexibility of the design). So, I can create a "packed" structure, and a factory that will transparently return a new B instance:

```<code>struct PackedCarAndEngine {
    Engine engine;
    Car car;
};

shared_ptr<Car> new_Car() {
    shared_ptr<PackedCarAndEngine> packed = make_shared<PackedCarAndEngine>();

    // uses aliasing shared_ptr constructor
    packed->car.engine = shared_ptr<Engine>(packed, &packed->engine);

    // again
    shared_ptr<Car> car = shared_ptr<Car>(packed, &packed->car);

    return car;
}
</code>```

The problem is that this "car" instance will never be destroyed, because it have a reference count of two. When it dies, it will have a reference count of one, forever. Do you know a better way to keep using the internal shared_ptr's (so that I can attribute an "unpacked" reference if I want), and still make this packed structure?

UPDATE

I could use a no-op deleter, but then it would be very dangerous if I decide to keep the engine but not the car:

```<code>    // ...
    packed->car.engine = shared_ptr<Engine>(&packed->engine, do_nothing_deleter);
    // ...

shared_ptr<Car> my_car = new_Car();
shared_ptr<Engine> my_engine = my_car->engine;
my_car.reset(); // Danger: engine was destroyed here!!!
cout << my_engine->engine_data; // Crash!
</code>```

答:
```<code>void nop(Engine*) { /* do nothing */ }

packed->car.engine = shared_ptr<Engine>(&packed->engine, nop);
</code>```

Explanation: This code creates a shared_ptr that thinks that it owns the engine but in fact it has a separate reference counter AND it does nothing when the deleter is called.

ContentLicense: CC BY-SA 2.5

Body:
Suppose I have these classes:

struct Engine {
  int engine_data;
};

struct Car {
  shared_ptr<Engine> engine;
  int car_data;
};

For performance reasons, I want to make them tightly packed in memory (but I don't want to lose the flexibility of the design). So, I can create a "packed" structure, and a factory that will transparently return a new B instance:

struct PackedCarAndEngine {
    Engine engine;
    Car car;
};

shared_ptr<Car> new_Car() {
    shared_ptr<PackedCarAndEngine> packed = make_shared<PackedCarAndEngine>();

    // uses aliasing shared_ptr constructor
    packed->car.engine = shared_ptr<Engine>(packed, &packed->engine);

    // again
    shared_ptr<Car> car = shared_ptr<Car>(packed, &packed->car);

    return car;
}

The problem is that this "car" instance will never be destroyed, because it have a reference count of two. When it dies, it will have a reference count of one, forever. Do you know a better way to keep using the internal shared_ptr's (so that I can attribute an "unpacked" reference if I want), and still make this packed structure?

UPDATE

I could use a no-op deleter, but then it would be very dangerous if I decide to keep the engine but not the car:

    // ...
    packed->car.engine = shared_ptr<Engine>(&packed->engine, do_nothing_deleter);
    // ...

shared_ptr<Car> my_car = new_Car();
shared_ptr<Engine> my_engine = my_car->engine;
my_car.reset(); // Danger: engine was destroyed here!!!
cout << my_engine->engine_data; // Crash!

Body:
void nop(Engine*) { /* do nothing */ }

packed->car.engine = shared_ptr<Engine>(&packed->engine, nop);

Explanation: This code creates a shared_ptr that thinks that it owns the engine but in fact it has a separate reference counter AND it does nothing when the deleter is called.


问:
how to group by the array values dynamically in javascript
hi all i am using javascript i have a set of array i need to group by the object

code

```<code> var data = [{BuildingID: "5", FloorId: "65", one: 12, two: 15,three: 12},
            {BuildingID: "5", FloorId: "65", one: 12, two: 15,three: 12},
            {BuildingID: "6", FloorId: "65", one: 12, two: 15,three: 12},
            {BuildingID: "6", FloorId: "65", one: 12, two: 15,three: 12}]
</code>```

i am trying to do group by the BuildingID add one,two,three
NOTE:one two three is not static

Excepted Output

```<code>  var data = [{BuildingID: "5", FloorId: "65", one: 24, two: 30,three: 24},
              {BuildingID: "6", FloorId: "65", one: 24, two: 30,three: 24} ]
</code>```

答:
You could use a dynamic approach by using a hash table and an array for the static keys of the object.

var data = [{ BuildingID: "5", FloorId: "65", one: 12, two: 15, three: 12 }, { BuildingID: "5", FloorId: "65", one: 12, two: 15, three: 12 }, { BuildingID: "6", FloorId: "65", one: 12, two: 15, three: 12 }, { BuildingID: "6", FloorId: "65", one: 12, two: 15, three: 12 }],
    staticKeys = ['BuildingID', 'FloorId'] ,
    grouped = data.reduce(function (hash) {
        return function (r, a) {
            var key = a[staticKeys[0]];
            if (!hash[key]) {
                hash[key] = {};
                staticKeys.forEach(function (k) {
                    hash[key][k] = a[k];
                });
                r.push(hash[key]);
            }
            Object.keys(a).forEach(function (k) {
                if (staticKeys.indexOf(k) === -1) {
                    hash[key][k] = (hash[key][k] || 0) + a[k];
                }
            });
            return r;
        };
    }(Object.create(null)), []);

console.log(grouped);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
hi all i am using javascript i have a set of array i need to group by the object

code

 var data = [{BuildingID: "5", FloorId: "65", one: 12, two: 15,three: 12},
            {BuildingID: "5", FloorId: "65", one: 12, two: 15,three: 12},
            {BuildingID: "6", FloorId: "65", one: 12, two: 15,three: 12},
            {BuildingID: "6", FloorId: "65", one: 12, two: 15,three: 12}]

i am trying to do group by the BuildingID add one,two,three
NOTE:one two three is not static

Excepted Output

  var data = [{BuildingID: "5", FloorId: "65", one: 24, two: 30,three: 24},
              {BuildingID: "6", FloorId: "65", one: 24, two: 30,three: 24} ]

Body:
You could use a dynamic approach by using a hash table and an array for the static keys of the object.

var data = [{ BuildingID: "5", FloorId: "65", one: 12, two: 15, three: 12 }, { BuildingID: "5", FloorId: "65", one: 12, two: 15, three: 12 }, { BuildingID: "6", FloorId: "65", one: 12, two: 15, three: 12 }, { BuildingID: "6", FloorId: "65", one: 12, two: 15, three: 12 }],
    staticKeys = ['BuildingID', 'FloorId'] ,
    grouped = data.reduce(function (hash) {
        return function (r, a) {
            var key = a[staticKeys[0]];
            if (!hash[key]) {
                hash[key] = {};
                staticKeys.forEach(function (k) {
                    hash[key][k] = a[k];
                });
                r.push(hash[key]);
            }
            Object.keys(a).forEach(function (k) {
                if (staticKeys.indexOf(k) === -1) {
                    hash[key][k] = (hash[key][k] || 0) + a[k];
                }
            });
            return r;
        };
    }(Object.create(null)), []);

console.log(grouped);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Android Developer Console - wrong fingerprint after release build with Android Studio
I started building an Android app with Adobe Air so I needed a .p12 key for building the release version .apk
Next I ported the app to Unity3d so I converted the .p12 to .keystore. Up to this point there was no problem uploading new versions to the Developer Console.

Now I rewrote and redesigned the app with Android Studio. When I upload the release version build with Android Studio I'm not able to publish it because of different fingerprints.
I tried to sign the release build in Android Studio with v1, v2 and both.

Any idea on how to solve the issue?

答:
On Unity apk fingerprints creating like "com.companyname.apkname" but On Android Studio fingerprints as default creating like "com.company.name.apkname" and these are diffrent fingerprints as you can see :)

It probably solve your problem, try this out and inform me please :)


问:
Calling React native method which should return data(string for Instance) to android activity on android button click
I have an android app on which I have a Button.On click of this button I need to invoke a method in react-native and after some computation on react-native server, I need to get the result like a string on my Textview.
I am new to react-native and timelines are less so need to know how this can be achieved.
Till now I am able to run a helloworld sample react-native demo project on android.
I think there could be something related to callbacks, emitting events
or promise.But don't know exact answer.</p>

答:
Take a look at Native Modules iOS and Native Modules Android.

It has everything you want.

For iOS there is one more reference Communication between native and React Native

I think it has more than enough documentation, go through it and you will get success.

Check Link1 , Link2 and Link3 also.


问:
java parsing a string like "0:ADD(10)"
i am having a string array like this {"0:ADD(10)","1:ADD(20)"} how can i parse this and get the value '10','20' from this string ,

Scenario is : i am trying to write a client and server app using Apache Mina server , when i sent message between client and server i am getting response as "0:ADD(10)"

答:
this single line does the work:</p>

```<code>String[] arr = str.replace("{", "").replace("}", "").replaceAll("\"\\d+:ADD\\((\\d+)\\)\"", "$1").split(",");
</code>```

Title: java parsing a string like "0:ADD(10)"

Body:
this single line does the work:

String[] arr = str.replace("{", "").replace("}", "").replaceAll("\"\\d+:ADD\\((\\d+)\\)\"", "$1").split(",");


问:
How can I change the url for a project in GitLab?
I have a project in Gitlab that is available over HTTP/SSH:

```<code>git@192.168.1.10:MyGroup/MyProject.git
</code>```

I want to change that using another IP, i.e.:

```<code>git@192.168.1.20:MyGroup/MyProject.git
</code>```

Where or how can I change that?

答:
You can use below command to set new URL for your repository.</p>

```<code>git remote set-url origin git://git@192.168.1.20:MyGroup/MyProject.git
</code>```

Body:
I have a project in Gitlab that is available over HTTP/SSH:

git@192.168.1.10:MyGroup/MyProject.git

I want to change that using another IP, i.e.:

git@192.168.1.20:MyGroup/MyProject.git

Where or how can I change that?

Body:
You can use below command to set new URL for your repository.

git remote set-url origin git://git@192.168.1.20:MyGroup/MyProject.git


问:
Get table name of entity class
Do you know how to get the table name from an Entity declaration in my controller class

Entity Class

```<code><?php

namespace Acme\StoreBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Acme\StoreBundle\Entity\User
 *
 * @ORM\Table(name="users")
 * @ORM\Entity
 */
class User
</code>```

I now would like to get the table name of the User entity, how would i do this in  my Symfony2 controller?

答:
I needed to find out the name of a mapping Table in a many-to-many relationship (using FOSUserBundle). Maybe this helps someone:</p>

```<code>    $groupAssociation = $this->getEntityManager()
                             ->getClassMetadata('UOACLBundle:User')
                             ->getAssociationsByTargetClass(Group::class);

    // 'groups' is the name of the property in my User Class
    $mappingTable = $groupAssociation['groups']['joinTable']['name'];
</code>```

Title: Get table name of entity class

Body:
Do you know how to get the table name from an Entity declaration in my controller class

Entity Class

<?php

namespace Acme\StoreBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Acme\StoreBundle\Entity\User
 *
 * @ORM\Table(name="users")
 * @ORM\Entity
 */
class User

I now would like to get the table name of the User entity, how would i do this in  my Symfony2 controller?

Body:
I needed to find out the name of a mapping Table in a many-to-many relationship (using FOSUserBundle). Maybe this helps someone:

    $groupAssociation = $this->getEntityManager()
                             ->getClassMetadata('UOACLBundle:User')
                             ->getAssociationsByTargetClass(Group::class);

    // 'groups' is the name of the property in my User Class
    $mappingTable = $groupAssociation['groups']['joinTable']['name'];


问:
Defined a custom action in controllers and added routes but still get no route matches error. Rails 5 app
I have a links controller and I have defined two custom actions called upvote and downvote. The action definitions:-

```<code>  def upvote
    @link = Link.find_by(id: params[:id])
    @link.vote_count += 1
    flash[:message]="Vote successfully registered"
    redirect_to root_path
  end

  def downvote
    @link = Link.find_by(id: params[:id])
    @link.vote_count -= 1
    flash[:message]="Vote successfully registered"
    redirect_to root_path
  end
</code>```

I have added the routes for these actions in the routes.rb file:-

```<code>  post '/links/:id', to: 'links#upvote', as: 'upvote'
  post '/links/:id', to: 'links#downvote', as: 'downvote'
</code>```

rails routes shows:-

```<code>upvote POST   /links/:id(.:format)     links#upvote
downvote POST   /links/:id(.:format)     links#downvote
</code>```

I'm calling the actions from the view as below:-

```<code><% if link.user != current_user %>
  <span class="vote-buttons">
    <div class="btn-group-vertical" role="group" aria-label="vote-buttons">
      <%= button_to 'Up', 'upvote_path', type:"button", class:"btn btn-xs btn-success" %>
      <%= button_to 'Down', 'downvote_path', type:"button", class:"btn btn-xs btn-danger" %>
    </div>
  </span>
<% end %>
</code>```

But I keep getting this error:-

```<code>No route matches [POST] "/upvote_path"
</code>```

Why am I seeing this even though rails routes shows that the route exists?

I tried restarting the server too.

答:
```<code><%= button_to 'Up', 'upvote_path', ...
</code>```

The URL for your button here is literally "upvote_path". Naturally, this url doesn't exist. I think you meant something like this:

```<code><%= button_to 'Up', upvote_path(link), ...
</code>```

Body:
I have a links controller and I have defined two custom actions called upvote and downvote. The action definitions:-

  def upvote
    @link = Link.find_by(id: params[:id])
    @link.vote_count += 1
    flash[:message]="Vote successfully registered"
    redirect_to root_path
  end

  def downvote
    @link = Link.find_by(id: params[:id])
    @link.vote_count -= 1
    flash[:message]="Vote successfully registered"
    redirect_to root_path
  end

I have added the routes for these actions in the routes.rb file:-

  post '/links/:id', to: 'links#upvote', as: 'upvote'
  post '/links/:id', to: 'links#downvote', as: 'downvote'

rails routes shows:-

upvote POST   /links/:id(.:format)     links#upvote
downvote POST   /links/:id(.:format)     links#downvote

I'm calling the actions from the view as below:-

<% if link.user != current_user %>

      <%= button_to 'Up', 'upvote_path', type:"button", class:"btn btn-xs btn-success" %>
      <%= button_to 'Down', 'downvote_path', type:"button", class:"btn btn-xs btn-danger" %>

<% end %>

But I keep getting this error:-

No route matches [POST] "/upvote_path"

Why am I seeing this even though rails routes shows that the route exists?

I tried restarting the server too.

Body:
<%= button_to 'Up', 'upvote_path', ...

The URL for your button here is literally "upvote_path". Naturally, this url doesn't exist. I think you meant something like this:

<%= button_to 'Up', upvote_path(link), ...


问:
Is it possible to set a custom type in jOOQ not only based on the column name or data type, but on the table name?
I have one project with IDs in the database named like FOO_ID (for the table FOO). I find it convenient to define a small class in Java called FooId wrapping the actual value, and map the FOO_ID column's type to FooId in Java. This allows for better type checking, as I can't accidentally write a "foo id" into a "bar id" column without the compiler giving me an error.

On a new project, all the ID columns are simply called ID in every table. I can't change the database schema, that's out of my hands alas. I would love for <forcedType> to be able to match "column named 'ID' in table named 'FOO'" but right now I can't see how to do that, I don't think it's possible.

Is it possible to constrain <forcedType> based on the table name in addition to the column name? If so, what's the syntax?

Thanks in advance!

答:
Existing feature request

This idea has been discussed on the jOOQ mailing list a couple of times and there's also a pending feature request that will add support for a special generated key type: #6124.

In addition to what you suggested, foreign key types should match their referenced primary key types. The challenge with these types is to make it work for all edge cases including:

Composite keys

Unique keys (which can also be referenced by foreign keys in many databases)

Columns participating in several unique keys / foreign keys

While this is certainly an interesting feature, it is not yet available in jOOQ 3.9.

Workaround

You can work around this limitation yourself by:

Extending the JavaGenerator in order to generate your own type per primary key / foreign key

Using <forcedType/> to replace all single-column key types by your own generated types

This is best done by using the programmatic code generation configuration - otherwise you'd be typing quite a bit of XML (of course, you could also use XSLT to generate the config).


问:
Xcode 6 Bug: Unknown class in Interface Builder file
I upgraded to Xcode 6 beta 4 and now my App continuously crashes with the message

Unknown class X in Interface Builder file.

It crashes because supposedly Xcode can't find my custom classes that I have linked in my Storyboard but it shows that they are linked correctly in the Xcode interface.

I'm positive everything is linked correctly. My only other option may be to delete the entire storyboard file and start from scratch because it might be corrupted somehow.

Edit: I would also like to add that I tried cleaning, reseting simulator, messing with build phases etc. None of that works.

答: In my case, I added a flag -ObjC to Other Linker Flags in project settings to make it work. Also I tried with -all_load flag and it worked well too.


答:
Might be a bit of overkill, but this should work</p>

```<code>    String input="{\"0:ADD(10)\",\"1:ADD(20)\"}";
    Pattern r= Pattern.compile(":ADD\\(([0-9]*)\\)");
    Matcher m = r.matcher(input);
    while(m.find()){
        System.out.println(m.group(1)); //Result is here
    }
</code>```

Title: java parsing a string like "0:ADD(10)"

Body:
i am having a string array like this {"0:ADD(10)","1:ADD(20)"} how can i parse this and get the value '10','20' from this string ,

Scenario is : i am trying to write a client and server app using Apache Mina server , when i sent message between client and server i am getting response as "0:ADD(10)"

Body:
Might be a bit of overkill, but this should work

    String input="{\"0:ADD(10)\",\"1:ADD(20)\"}";
    Pattern r= Pattern.compile(":ADD\\(([0-9]*)\\)");
    Matcher m = r.matcher(input);
    while(m.find()){
        System.out.println(m.group(1)); //Result is here
    }


问:
Java 8: How to create DateTimeFormatter with milli, micro or nano seconds?
I need to create the formatter for parsing timestamps with optional milli, micro or nano fractions of second.

For example, for my needs I see the following opportunity:

```<code>DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                                   .append(DateTimeFormatter.BASIC_ISO_DATE)
                                   .appendLiteral('-')
                                   .append(DateTimeFormatter.ISO_LOCAL_TIME)
                                   .appendOffset("+HH:mm", "Z")
                                   .toFormatter();
</code>```

Or it is also possible to use appendFraction(field, minWidth, maxWidth, decimalPoint).

However in these cases will it be possible to parse timestamps with any number of decimals (up to 9 or maxWidth). How to achieve that we can parse (optionally) only 3, 6 or 9 numbers after the comma?

It should be possible to parse the following time parts:

HH:mm:ss.SSS

HH:mm:ss.SSSSSS

HH:mm:ss.SSSSSSSSS

But impossible to parse: HH:mm:ss.SSSS.

答:
You can use the optional sections pattern (delimited by []), and create 3 optional sections: 1 for 9 digits, another for 6 digits and another one for 3 digits.

According to DateTimeFormatterBuilder docs, you can use the S pattern (which is equivalent to NANO_OF_SECOND field):

```<code>Pattern  Count  Equivalent builder methods
-------  -----  --------------------------
S..S     1..n   appendFraction(ChronoField.NANO_OF_SECOND, n, n, false)
</code>```

In the old API (SimpleDateFormat), S is the pattern used for milliseconds, but in the new API it was changed to nanoseconds.

So the formatter will be created like this:

```<code>DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    // here is the same as your code
    .append(DateTimeFormatter.BASIC_ISO_DATE).appendLiteral('-')
    // time (hour/minute/seconds)
    .appendPattern("HH:mm:ss")
    // optional nanos, with 9, 6 or 3 digits
    .appendPattern("[.SSSSSSSSS][.SSSSSS][.SSS]")
    // offset
    .appendOffset("+HH:mm", "Z")
    // create formatter
    .toFormatter();
</code>```

Some tests:

```<code>// 3 digits
System.out.println(OffsetDateTime.parse("20161201-10:30:45.123Z", formatter)); // 2016-12-01T10:30:45.123Z

// 6 digits
System.out.println(OffsetDateTime.parse("20161201-10:30:45.123456Z", formatter)); // 2016-12-01T10:30:45.123456Z

// 9 digits
System.out.println(OffsetDateTime.parse("20161201-10:30:45.123456789Z", formatter)); // 2016-12-01T10:30:45.123456789Z

// 4 digits (throws DateTimeParseException: Text '20161201-10:30:45.1234Z' could not be parsed at index 21)
System.out.println(OffsetDateTime.parse("20161201-10:30:45.1234Z", formatter));
</code>```

The output is:

2016-12-01T10:30:45.123Z

  2016-12-01T10:30:45.123456Z

  2016-12-01T10:30:45.123456789Z

  Exception in thread "main" java.time.format.DateTimeParseException: Text '20161201-10:30:45.1234Z' could not be parsed at index 21

Notes:

This instance of DateTimeFormatter is not good for formatting, because it prints all optional sections (so the nanosecond will be printed 3 times):

```<code>// don't use it to format, it prints all optional sections
// (so nanos are printed 3 times: with 9, 6 and 3 digits)
OffsetDateTime odt = OffsetDateTime.parse("20161201-10:30:45.123Z", formatter);
System.out.println(formatter.format(odt));
// output is 20161201Z-10:30:45.123000000.123000.123Z
</code>```

So if you want to display your dates in another format, consider creating another DateTimeFormatter.

In your code you used DateTimeFormatter.ISO_LOCAL_TIME. According to javadoc, in this formatter the seconds are optional. If you want to have the same behaviour, just change the time pattern to:

```<code>// time (hour/minute) with optional seconds
.appendPattern("HH:mm[:ss]")
</code>```

The [] pattern is a nice shortcut to make optional sections, but you could also create them using optionalStart() with appendFraction():

```<code>DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    // here is the same as your code
    .append(DateTimeFormatter.BASIC_ISO_DATE).appendLiteral('-')
    // time (hour/minute/seconds)
    .appendPattern("HH:mm:ss")
    // optional nanos with 9 digits (including decimal point)
    .optionalStart()
    .appendFraction(ChronoField.NANO_OF_SECOND, 9, 9, true)
    .optionalEnd()
    // optional nanos with 6 digits (including decimal point)
    .optionalStart()
    .appendFraction(ChronoField.NANO_OF_SECOND, 6, 6, true)
    .optionalEnd()
    // optional nanos with 3 digits (including decimal point)
    .optionalStart()
    .appendFraction(ChronoField.NANO_OF_SECOND, 3, 3, true)
    .optionalEnd()
    // offset
    .appendOffset("+HH:mm", "Z")
    // create formatter
    .toFormatter();
</code>```

This formatter works exactly the same way as the first one created with [] pattern.

Side effect

As @SeanVanGorder noticed in his comment, this formatter has the side effect of accepting multiple patterns for the nanosecond field, but it works only if the values are the same:

```<code>// side effect
// multiple nanos values (accepts multiple values if they're all the same)
System.out.println(OffsetDateTime.parse("20161201-10:30:45.123000.123Z", formatter)); // 2016-12-01T10:30:45.123Z
System.out.println(OffsetDateTime.parse("20161201-10:30:45.123000000.123Z", formatter)); // 2016-12-01T10:30:45.123Z
System.out.println(OffsetDateTime.parse("20161201-10:30:45.123000000.123000.123Z", formatter)); // 2016-12-01T10:30:45.123Z
</code>```

All the lines above output 2016-12-01T10:30:45.123Z, but notice that they accept all the optional values (like .123000000.123). As the values are the same, the parsing is done without errors.

If the values are different, though, it throws an exception:

```<code>// multiple nanos values (throws exception if values are different)
System.out.println(OffsetDateTime.parse("20161201-10:30:45.123000.124Z", formatter)); // exception
</code>```

If this behaviour is not desired, the only alternative is to create lots of different formatters (one for each case) and do a for loop until you get a valid parsed value (very similar to this answer).

First I created a method receives a list of DateTimeFormatter's and a TemporalQuery to convert the parsed string to any object you want:

```<code>// method to parse, it receives a list of DateTimeFormatter and a TemporalQuery to convert the parsed string
public <T> T parse(String input, TemporalQuery<T> query, DateTimeFormatter... formatters) {
    for (DateTimeFormatter fmt : formatters) {
        try {
            // try to parse
            return fmt.parse(input, query);
        } catch (Exception e) {}
    }

    // none worked, throw exception
    throw new DateTimeParseException("Text '" + input + "' could not be parsed", input, 0);
}
</code>```

Now you just need to create the formatters and use them in the parse method:

```<code>// alternative: have 3 different formatters
DateTimeFormatter f1 = new DateTimeFormatterBuilder()
    // here is the same as your code
    .append(DateTimeFormatter.BASIC_ISO_DATE).appendLiteral('-')
    // time (hour/minute/seconds/3 digit nanos)
    .appendPattern("HH:mm:ss.SSS")
    // offset
    .appendOffset("+HH:mm", "Z")
    // create formatter
    .toFormatter();
DateTimeFormatter f2 = new DateTimeFormatterBuilder()
    // here is the same as your code
    .append(DateTimeFormatter.BASIC_ISO_DATE).appendLiteral('-')
    // time (hour/minute/seconds/6 digit nanos)
    .appendPattern("HH:mm:ss.SSSSSS")
    // offset
    .appendOffset("+HH:mm", "Z")
    // create formatter
    .toFormatter();
DateTimeFormatter f3 = new DateTimeFormatterBuilder()
    // here is the same as your code
    .append(DateTimeFormatter.BASIC_ISO_DATE).appendLiteral('-')
    // time (hour/minute/seconds/9 digit nanos)
    .appendPattern("HH:mm:ss.SSSSSSSSS")
    // offset
    .appendOffset("+HH:mm", "Z")
    // create formatter
    .toFormatter();

// all formatters
DateTimeFormatter[] formatters = new DateTimeFormatter[] { f1, f2, f3 };

// 3 digits
System.out.println(parse("20161201-10:30:45.123Z", OffsetDateTime::from, formatters)); // 2016-12-01T10:30:45.123Z
// 6 digits
System.out.println(parse("20161201-10:30:45.123456Z", OffsetDateTime::from, formatters)); // 2016-12-01T10:30:45.123456Z
// 9 digits
System.out.println(parse("20161201-10:30:45.123456789Z", OffsetDateTime::from, formatters)); // 2016-12-01T10:30:45.123456789Z

// 4 digits (throws exception)
System.out.println(parse("20161201-10:30:45.1234Z", OffsetDateTime::from, formatters));
// java.time.format.DateTimeParseException: Text '20161201-10:30:45.1234Z' could not be parsed

// multiple values (throws exception)
System.out.println(parse("20161201-10:30:45.123000.123Z", OffsetDateTime::from, formatters));
// java.time.format.DateTimeParseException: Text '20161201-10:30:45.123000.123Z' could not be parsed
</code>```

Note that I used the method reference OffsetDateTime::from as a TemporalQuery, but you can change it to any query you need.

Body:
I need to create the formatter for parsing timestamps with optional milli, micro or nano fractions of second.

For example, for my needs I see the following opportunity:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                                   .append(DateTimeFormatter.BASIC_ISO_DATE)
                                   .appendLiteral('-')
                                   .append(DateTimeFormatter.ISO_LOCAL_TIME)
                                   .appendOffset("+HH:mm", "Z")
                                   .toFormatter();

Or it is also possible to use appendFraction(field, minWidth, maxWidth, decimalPoint).

However in these cases will it be possible to parse timestamps with any number of decimals (up to 9 or maxWidth). How to achieve that we can parse (optionally) only 3, 6 or 9 numbers after the comma?

It should be possible to parse the following time parts:

HH:mm:ss.SSS

HH:mm:ss.SSSSSS

HH:mm:ss.SSSSSSSSS

But impossible to parse: HH:mm:ss.SSSS.

Body:
You can use the optional sections pattern (delimited by []), and create 3 optional sections: 1 for 9 digits, another for 6 digits and another one for 3 digits.

According to DateTimeFormatterBuilder docs, you can use the S pattern (which is equivalent to NANO_OF_SECOND field):

Pattern  Count  Equivalent builder methods
-------  -----  --------------------------
S..S     1..n   appendFraction(ChronoField.NANO_OF_SECOND, n, n, false)

In the old API (SimpleDateFormat), S is the pattern used for milliseconds, but in the new API it was changed to nanoseconds.

So the formatter will be created like this:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    // here is the same as your code
    .append(DateTimeFormatter.BASIC_ISO_DATE).appendLiteral('-')
    // time (hour/minute/seconds)
    .appendPattern("HH:mm:ss")
    // optional nanos, with 9, 6 or 3 digits
    .appendPattern("[.SSSSSSSSS][.SSSSSS][.SSS]")
    // offset
    .appendOffset("+HH:mm", "Z")
    // create formatter
    .toFormatter();

Some tests:

// 3 digits
System.out.println(OffsetDateTime.parse("20161201-10:30:45.123Z", formatter)); // 2016-12-01T10:30:45.123Z

// 6 digits
System.out.println(OffsetDateTime.parse("20161201-10:30:45.123456Z", formatter)); // 2016-12-01T10:30:45.123456Z

// 9 digits
System.out.println(OffsetDateTime.parse("20161201-10:30:45.123456789Z", formatter)); // 2016-12-01T10:30:45.123456789Z

// 4 digits (throws DateTimeParseException: Text '20161201-10:30:45.1234Z' could not be parsed at index 21)
System.out.println(OffsetDateTime.parse("20161201-10:30:45.1234Z", formatter));

The output is:

2016-12-01T10:30:45.123Z

  2016-12-01T10:30:45.123456Z

  2016-12-01T10:30:45.123456789Z

  Exception in thread "main" java.time.format.DateTimeParseException: Text '20161201-10:30:45.1234Z' could not be parsed at index 21

Notes:

This instance of DateTimeFormatter is not good for formatting, because it prints all optional sections (so the nanosecond will be printed 3 times):

// don't use it to format, it prints all optional sections
// (so nanos are printed 3 times: with 9, 6 and 3 digits)
OffsetDateTime odt = OffsetDateTime.parse("20161201-10:30:45.123Z", formatter);
System.out.println(formatter.format(odt));
// output is 20161201Z-10:30:45.123000000.123000.123Z

So if you want to display your dates in another format, consider creating another DateTimeFormatter.

In your code you used DateTimeFormatter.ISO_LOCAL_TIME. According to javadoc, in this formatter the seconds are optional. If you want to have the same behaviour, just change the time pattern to:

// time (hour/minute) with optional seconds
.appendPattern("HH:mm[:ss]")

The [] pattern is a nice shortcut to make optional sections, but you could also create them using optionalStart() with appendFraction():

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    // here is the same as your code
    .append(DateTimeFormatter.BASIC_ISO_DATE).appendLiteral('-')
    // time (hour/minute/seconds)
    .appendPattern("HH:mm:ss")
    // optional nanos with 9 digits (including decimal point)
    .optionalStart()
    .appendFraction(ChronoField.NANO_OF_SECOND, 9, 9, true)
    .optionalEnd()
    // optional nanos with 6 digits (including decimal point)
    .optionalStart()
    .appendFraction(ChronoField.NANO_OF_SECOND, 6, 6, true)
    .optionalEnd()
    // optional nanos with 3 digits (including decimal point)
    .optionalStart()
    .appendFraction(ChronoField.NANO_OF_SECOND, 3, 3, true)
    .optionalEnd()
    // offset
    .appendOffset("+HH:mm", "Z")
    // create formatter
    .toFormatter();

This formatter works exactly the same way as the first one created with [] pattern.

Side effect

As @SeanVanGorder noticed in his comment, this formatter has the side effect of accepting multiple patterns for the nanosecond field, but it works only if the values are the same:

// side effect
// multiple nanos values (accepts multiple values if they're all the same)
System.out.println(OffsetDateTime.parse("20161201-10:30:45.123000.123Z", formatter)); // 2016-12-01T10:30:45.123Z
System.out.println(OffsetDateTime.parse("20161201-10:30:45.123000000.123Z", formatter)); // 2016-12-01T10:30:45.123Z
System.out.println(OffsetDateTime.parse("20161201-10:30:45.123000000.123000.123Z", formatter)); // 2016-12-01T10:30:45.123Z

All the lines above output 2016-12-01T10:30:45.123Z, but notice that they accept all the optional values (like .123000000.123). As the values are the same, the parsing is done without errors.

If the values are different, though, it throws an exception:

// multiple nanos values (throws exception if values are different)
System.out.println(OffsetDateTime.parse("20161201-10:30:45.123000.124Z", formatter)); // exception

If this behaviour is not desired, the only alternative is to create lots of different formatters (one for each case) and do a for loop until you get a valid parsed value (very similar to this answer).

First I created a method receives a list of DateTimeFormatter's and a TemporalQuery to convert the parsed string to any object you want:

// method to parse, it receives a list of DateTimeFormatter and a TemporalQuery to convert the parsed string
public <T> T parse(String input, TemporalQuery<T> query, DateTimeFormatter... formatters) {
    for (DateTimeFormatter fmt : formatters) {
        try {
            // try to parse
            return fmt.parse(input, query);
        } catch (Exception e) {}
    }

    // none worked, throw exception
    throw new DateTimeParseException("Text '" + input + "' could not be parsed", input, 0);
}

Now you just need to create the formatters and use them in the parse method:

// alternative: have 3 different formatters
DateTimeFormatter f1 = new DateTimeFormatterBuilder()
    // here is the same as your code
    .append(DateTimeFormatter.BASIC_ISO_DATE).appendLiteral('-')
    // time (hour/minute/seconds/3 digit nanos)
    .appendPattern("HH:mm:ss.SSS")
    // offset
    .appendOffset("+HH:mm", "Z")
    // create formatter
    .toFormatter();
DateTimeFormatter f2 = new DateTimeFormatterBuilder()
    // here is the same as your code
    .append(DateTimeFormatter.BASIC_ISO_DATE).appendLiteral('-')
    // time (hour/minute/seconds/6 digit nanos)
    .appendPattern("HH:mm:ss.SSSSSS")
    // offset
    .appendOffset("+HH:mm", "Z")
    // create formatter
    .toFormatter();
DateTimeFormatter f3 = new DateTimeFormatterBuilder()
    // here is the same as your code
    .append(DateTimeFormatter.BASIC_ISO_DATE).appendLiteral('-')
    // time (hour/minute/seconds/9 digit nanos)
    .appendPattern("HH:mm:ss.SSSSSSSSS")
    // offset
    .appendOffset("+HH:mm", "Z")
    // create formatter
    .toFormatter();

// all formatters
DateTimeFormatter[] formatters = new DateTimeFormatter[] { f1, f2, f3 };

// 3 digits
System.out.println(parse("20161201-10:30:45.123Z", OffsetDateTime::from, formatters)); // 2016-12-01T10:30:45.123Z
// 6 digits
System.out.println(parse("20161201-10:30:45.123456Z", OffsetDateTime::from, formatters)); // 2016-12-01T10:30:45.123456Z
// 9 digits
System.out.println(parse("20161201-10:30:45.123456789Z", OffsetDateTime::from, formatters)); // 2016-12-01T10:30:45.123456789Z

// 4 digits (throws exception)
System.out.println(parse("20161201-10:30:45.1234Z", OffsetDateTime::from, formatters));
// java.time.format.DateTimeParseException: Text '20161201-10:30:45.1234Z' could not be parsed

// multiple values (throws exception)
System.out.println(parse("20161201-10:30:45.123000.123Z", OffsetDateTime::from, formatters));
// java.time.format.DateTimeParseException: Text '20161201-10:30:45.123000.123Z' could not be parsed

Note that I used the method reference OffsetDateTime::from as a TemporalQuery, but you can change it to any query you need.


问:
Automatically scroll table when the selected row is the row before last row
I have an issue related to scrolling table.

When the page is loaded, the first row (ROW 1) will be default selected row (highlighted row). If we click next button the next row will be selected and highlighted. The issue is if the ROW >= 8 (e.g ROW 9, 10...) being selected, the table do not automatically scroll so we can not see the current selected is also being highlighted.
Behaviours should be as follow  image:

When the ROW 8 is being selected, the table should be scrolled automatically. At this time, the next row (ROW 9) is VISIBLE and the top rows should be invisible.

My purpose is at current selected row I also can see the next row. The table should be scrolled when I click next/previous button until reach the last visible row and then that row will become the row before the last row.

I don't have any idea to solve this issue.
Please help me.

Best Regards,
Ken.

答:
The below snippet makes use of window to scroll to specific tr of the table.

On each next/prev click increment/decrease the selectedIndex respectively and scroll to that index of row in table.

var app = angular.module("app", []);

app.controller("ctrl", function($scope) {
  $scope.selectedIndex = 0;
  $scope.rows = ["Row1", "Row2", "Row3", "Row4", "Row5", "Row6", "Row7", "Row8", "Row9", "Row10", "Row11", "Row12", "Row13", "Row14", "Row15", "Row16", "Row17", "Row18"];

  $scope.NextRow = function() {
    $scope.selectedIndex = $scope.selectedIndex === $scope.rows.length - 1 ? $scope.rows.length - 1 : $scope.selectedIndex + 1;
    var w = $(window);
    var row = $('table').find('tr').eq($scope.selectedIndex);
    if (row.length) {
      w.scrollTop(row.offset().top - (w.height() / 2));
    }
  }

  $scope.PrevRow = function() {
    $scope.selectedIndex = $scope.selectedIndex === 0 ? 0 : $scope.selectedIndex - 1;;
    var w = $(window);
    var row = $('table').find('tr').eq($scope.selectedIndex);

    if (row.length) {
      w.scrollTop(row.offset().top - (w.height() / 2));
    }
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  padding-top: 50px;
}

.anchor {
  border: 2px dashed DarkOrchid;
  padding: 5px 5px 5px 5px;
}

.fixed-header {
  background-color: rgba(0, 0, 0, 0.2);
  height: 50px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
}

.fixed-header>a {
  display: inline-block;
  margin: 5px 15px;
}</code>```

    <button ng-click="PrevRow()">Previous button </button>
    <button href="" ng-click="NextRow()">Next button </button>

          {{row}}

```

Body:
The below snippet makes use of window to scroll to specific tr of the table.

On each next/prev click increment/decrease the selectedIndex respectively and scroll to that index of row in table.

var app = angular.module("app", []);

app.controller("ctrl", function($scope) {
  $scope.selectedIndex = 0;
  $scope.rows = ["Row1", "Row2", "Row3", "Row4", "Row5", "Row6", "Row7", "Row8", "Row9", "Row10", "Row11", "Row12", "Row13", "Row14", "Row15", "Row16", "Row17", "Row18"];

  $scope.NextRow = function() {
    $scope.selectedIndex = $scope.selectedIndex === $scope.rows.length - 1 ? $scope.rows.length - 1 : $scope.selectedIndex + 1;
    var w = $(window);
    var row = $('table').find('tr').eq($scope.selectedIndex);
    if (row.length) {
      w.scrollTop(row.offset().top - (w.height() / 2));
    }
  }

  $scope.PrevRow = function() {
    $scope.selectedIndex = $scope.selectedIndex === 0 ? 0 : $scope.selectedIndex - 1;;
    var w = $(window);
    var row = $('table').find('tr').eq($scope.selectedIndex);

    if (row.length) {
      w.scrollTop(row.offset().top - (w.height() / 2));
    }
  }
});

body {
  padding-top: 50px;
}

.anchor {
  border: 2px dashed DarkOrchid;
  padding: 5px 5px 5px 5px;
}

.fixed-header {
  background-color: rgba(0, 0, 0, 0.2);
  height: 50px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
}

.fixed-header>a {
  display: inline-block;
  margin: 5px 15px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="app" ng-controller="ctrl">

  <div class="fixed-header">
    <button ng-click="PrevRow()">Previous button </button>
    <button href="" ng-click="NextRow()">Next button </button>
  </div>

  <div>
    <table>
      <tbody>
        <tr ng-repeat="row in rows">
          <td class="anchor" ng-style="selectedIndex == $index && {'background-color':'lightblue'}">{{row}}</td>
        </tr>
      </tbody>
    </table>
  </div>

</body>


问:
Ext-gwt stacked bar chart
Anyone knows of a reference/tutorial for making a stacked bar chart in ext-gwt. Also is there any other gwt widget library which supports simultaneous stacked bar chart and line chart.</p>

答: The chart system in Ext GWT is a wrapper around Open Flash Charts 2. At present I believe the stacked bar chart is not wrapped fully and so not available in Ext GWT out of the box.</p>

Title: Ext-gwt stacked bar chart


问:
TCPDF gray outline on transparent PNG
I'm creating pdfs that have a PNG image with transparency, it almost works fine, but the PNG have a grey border around anything that isn't transparent.

PNG in PDF

Original picture

Any ideas?

答:
In Adobe's PDF viewer, you can turn it off with Preferences > Page Display > Rendering > Smooth images: NO

Reference
https://forum.openoffice.org/en/forum/viewtopic.php?f=7&t=22920&start=0

Title: TCPDF gray outline on transparent PNG


问:
Kotlin : Interface Queue does not have constructors
I'm trying to instantiate an object of Queue using below code

var queue: Queue<Int> = Queue()

But I get this

Interface Queue does not have constructors

No idea what's going on, while searching I found this link.

But I don't understand anything.
Please help.

答:
Queue is an interface. So you can't instantiate an interface, you have to implement it or instantiate a class that implement it.

For example, you can do var queue: Queue<Int> = ArrayDeque<Int>(). ArrayDeque implements Queue.


问:
How to select the first record from group?
I have a list/array of records, and I'm using explode to extract data from the list.  I'd like to pick the first record from the exploded result, using Spark SQL in Java.

```<code>Dataset<Row> ds= ds.select(
  json.col("*"),
  explode(json.col("records.record.newrecord")).as("newrecord"));
ds= ds.select(ds.col("EVENT_SEQ"), ds.col("newrecord").apply("event").as("EVENTTYPE"));
</code>```

Current Data:

```<code>|           EVENT_SEQ|EVENTTYPE|
+--------------------+---------+
|5a694d77-bc65-4bf...|        0|
|5a694d77-bc65-4bf...|        0|
+--------------------+---------+
</code>```

Requirements:

```<code>|           EVENT_SEQ|EVENTTYPE|
+--------------------+---------+
|5a694d77-bc65-4bf...|        0|
+--------------------+---------+
</code>```

I have seen documentation that suggests Cloumn.apply for this purpose, but I haven't found enough help to get me started.

Body:
I have a list/array of records, and I'm using explode to extract data from the list.  I'd like to pick the first record from the exploded result, using Spark SQL in Java.

Dataset<Row> ds= ds.select(
  json.col("*"),
  explode(json.col("records.record.newrecord")).as("newrecord"));
ds= ds.select(ds.col("EVENT_SEQ"), ds.col("newrecord").apply("event").as("EVENTTYPE"));

Current Data:

|           EVENT_SEQ|EVENTTYPE|
+--------------------+---------+
|5a694d77-bc65-4bf...|        0|
|5a694d77-bc65-4bf...|        0|
+--------------------+---------+

Requirements:

|           EVENT_SEQ|EVENTTYPE|
+--------------------+---------+
|5a694d77-bc65-4bf...|        0|
+--------------------+---------+

I have seen documentation that suggests Cloumn.apply for this purpose, but I haven't found enough help to get me started.

Body:
That's certainly groupBy operator with first function.

val ds = Seq(
  ("5a694d77-bc65-4bf...", 0),
  ("5a694d77-bc65-4bf...", 0)
).toDF("EVENT_SEQ", "EVENTTYPE")
scala> ds.show
+--------------------+---------+
|           EVENT_SEQ|EVENTTYPE|
+--------------------+---------+
|5a694d77-bc65-4bf...|        0|
|5a694d77-bc65-4bf...|        0|
+--------------------+---------+

scala> ds.groupBy("EVENT_SEQ").agg(first("EVENTTYPE")).show
+--------------------+-----------------------+
|           EVENT_SEQ|first(EVENTTYPE, false)|
+--------------------+-----------------------+
|5a694d77-bc65-4bf...|                      0|
+--------------------+-----------------------+


问:
simple html dom failed to open stream for a site
I'm trying to parse throught http://whatismyip.com page and get my location (state and country). The data seems to be inside
 tags, so i'm looking for "table".
  But I get a mistake Warning: file_get_contents(https://whatismyip.com): failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden in C:\xampp4\htdocs\scraping\libs\simple_html_dom.php on line 1081

Can't figure out what's wrong.

```<code> <?php
        require_once('libs/simple_html_dom.php');
        $html=new simple_html_dom();

        $html->load_file('https://whatismyip.com');

        $element=$html->find("table");

    ?>
</code>```

答:
try changing the user agent using below command -

```<code>ini_set("user_agent","Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0");
</code>```

it will work fine then!

Body:
I'm trying to parse throught http://whatismyip.com page and get my location (state and country). The data seems to be inside
 tags, so i'm looking for "table".
  But I get a mistake Warning: file_get_contents(https://whatismyip.com): failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden in C:\xampp4\htdocs\scraping\libs\simple_html_dom.php on line 1081

Can't figure out what's wrong.

 <?php
        require_once('libs/simple_html_dom.php');
        $html=new simple_html_dom();

        $html->load_file('https://whatismyip.com');

        $element=$html->find("table");

    ?>

Body:
try changing the user agent using below command -

ini_set("user_agent","Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0");

it will work fine then!


问:
Digitally Sign a protected PDF (Printing not allowed, signing allowed)
I have a password protected document (not allowing the printing) and I want to Digitally sign it. When opening the file with iText I have BadPasswordException.

I read in the book that iText needs the password to manipulate the document so I gave the PDFReader constructor the password and I have this exception:

java.lang.AbstractMethodError: javax.xml.parsers.DocumentBuilderFactory.setFeature(Ljava/lang/String;Z)V

It seems that the metadata is encrypted too.

My questions:

Is there a way to digitally sign the document without the password? Signing is allowed

The document is not created from iText so how to bypass the metadata encryption?(DO_NOT_ENCRYPT_METADATA)

Thanks
Jamil

答:
As per this post https://forums.adobe.com/thread/1661225 it is impossible to digitally sign a secured document except if a blank digital signature fields are presented.

I was trying to add a digital signature without a blank digital signature field which it seems impossible

Any confirmation from iText?

Jamil


问:
Apache Nifi PutElasticsearch can wait forever to fill up batch size?
I am trying to write streaming data into elasticsearch with apache-nifi.putElasticSearch processor,

PutElasticSearch has property named "Batch Size", when I set this value to 1 all events are written to elasticsearch ASAP.

But such a low "batch size" obviously not working when the load is high. So in order to have a reasonable throughput I need to set it to 1000.

My question is, does PutElasticSearch waits till the batch size of events available. If yes it can wait hours when there are 999 events waiting on processor.

I am searching to understand how logstash doing same job on elasticsearch output plugin. There may be some flushing logic implemented based on time ( if events are waiting ~2 sec flush events to elasticsearch )..

You have any idea?

Edit: I just found logstash implemented this https://www.elastic.co/guide/en/logstash/current/plugins-outputs-elasticsearch.html#plugins-outputs-elasticsearch-idle_flush_time :)

How can I do same functionality on nifi

答:
According to the code the batch size parameter is a maximum number of FlowFiles from the incoming queue.

For example in case of value batch size = 1000:

1/ if incoming queue contains 1001 flow files - only 1000 will be taken in one transaction.

2/ if incoming queue contains 999 flow files - 999  will be taken in one transaction.

And everything will be processed as soon as there is something in the incoming queue and there are available threads in nifi.

references:

PutElasticsearch.java

ProcessSession.java


问:
Send message through Ring (Circular) Buffer between Threads (in C)
I need to send a message from Main thread to my Created Thread using WinAPI and Ring Buffer.

I defined structures and wrote functions for my Ring buffer.
Ring Buffer - it contains head, tail, size and pointer to the structure Descriptor which has length of Data and data itself. As I need to send 2 parameters to CreateThread function, I created the third structure ThreadParams to keep 2 parameters.

I want to leave this structures how they are now, not changeable.

```<code>typedef struct _Descriptor
{
    uint32_t dataLen;
    void * data;
} Descriptor;

typedef struct _ringBuffer
{
    Descriptor *bufferData;
    int head;
    int tail;
    int size;
} ringBuffer;

typedef struct _ThreadParams
{
    void * ptr1;
    void * ptr2;
} ThreadParams;
</code>```

There are my realisations of Ring Buffer functions:

```<code>void bufferFree(ringBuffer *buffer)
{
    free(buffer->bufferData);
}

void ringInitialization(ringBuffer *buffer, int size)
{
    buffer->size = size;
    buffer->head = 0;
    buffer->tail = 0;
    buffer->bufferData = (Descriptor*)malloc(sizeof(Descriptor) * size);
}

int pushBack(ringBuffer *buffer, void * data) // fill buffer
{
    buffer->bufferData[buffer->tail++] = *(Descriptor*)data;
    if (buffer->tail == buffer->size)
    {
        buffer->tail = 0;
    }
    return 0;
}

int popFront(ringBuffer *buffer)
{
    if (buffer->head != buffer->tail)
    {
        buffer->head++;
        if (buffer->head == buffer->size)
        {
            buffer->head = 0;
        }
    }
    return 0;
}
</code>```

My main: I checked that I can send a few bytes (the memory is shared between threads), now I need to send a big message (> BUFF_SIZE) though Ring Buffer what I'm trying to do in while() cycle. Here is the question: how should I do it? My thing doesn't work because I catch an exception in printf() function (memory acces violation).

```<code>#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#include <strsafe.h>
#include <stdint.h>

#define RING_SIZE 256
#define BUFFER_SIZE 1024

DWORD WINAPI HandleSendThread(LPVOID params);

uint8_t * getPointer(uint8_t *buffer, uint32_t index)
{
    uint8_t * ptr = ((uint8_t*)buffer) + index * BUFFER_SIZE;
    return ptr;
}

int main(int argc, char * argv[])
{
    //Descriptor * ringData = (Descriptor *)malloc(sizeof(Descriptor) * RING_SIZE);

    ringBuffer ring;
    ringInitialization(&ring, RING_SIZE);
    void * packetBuffer = malloc(BUFFER_SIZE * RING_SIZE);
    uint8_t * currentBuffer = getPointer(packetBuffer, 0);
    uint8_t * str = "Mr. and Mrs. Dursley, of number four, Privet Drive, were proud to say that they were perfectly normal, thank you very much. They were the last people you'd expect to be involved in anything strange or mysterious, because they just didn't hold with such nonsense. Mr.Dursley was the director of a firm called Grunnings, which made drills.He was a big, beefy man with hardly any neck, although he did have a very large mustache.Mrs.Dursley was thin and blonde and had nearly twice the usual amount of neck, which came in very useful as she spent so much of her time craning over garden fences, spying on the neighbors.The Dursleys had a small son called Dudley and in their opinion there was no finer boy anywhere.";

    strcpy(currentBuffer, str);
    ring.bufferData[0].data = currentBuffer;
    ring.bufferData[0].dataLen = strlen(str);

    int currentSize = 0;
    int ringSize = RING_SIZE;
    while(ring.bufferData[0].data != '\0')
    {
        for (int i = currentSize; i < ringSize; i + RING_SIZE)
        {
            pushBack(&ring, currentBuffer);
            printf("h = %s, tail = %s, dataBuffer = %s\n", (char*)ring.head, (char*)ring.tail, (char*)ring.bufferData[i].data);
        }
        currentSize = ringSize;
        ringSize = 2 * ringSize;
        popFront(&ring);
    }

    ThreadParams params = { &ring, packetBuffer };
    HANDLE MessageThread = 0;
    MessageThread = CreateThread(NULL, 0, HandleSendThread, &params, 0, NULL);
    if (MessageThread == NULL)
    {
        ExitProcess(MessageThread);
    }

    WaitForSingleObject(MessageThread, INFINITE);
    CloseHandle(MessageThread);
    system("pause");
    return 0;
}
</code>```

And my CreateThread function:

```<code>DWORD WINAPI HandleSendThread(LPVOID params)
{
    ringBuffer * ring = ((ThreadParams*)params)->ptr1;
    void * buffer = ((ThreadParams*)params)->ptr2;
    //ring->bufferData[0].dataLen = sizeof(buffer) + sizeof(ring->bufferData[0])*1024;

    printf("Shared memory check: ringBuffer data = \"%s\", \nlength = %d\n", (char*)ring->bufferData[0].data, ring->bufferData[0].dataLen);
    return 0;
}
</code>```

答:
Found a solution</p>

```<code>int main(int argc, char * argv[])
{
    ringBuffer ring;
    ringInitialization(&ring, RING_SIZE);
    void * packetBuffer = malloc(BUFFER_SIZE * RING_SIZE);
    Descriptor temp = { 0 };
    uint8_t * currentBuffer = getPointer(packetBuffer, 0);
    uint8_t * str = "Mr. and Mrs. Dursley, of number four, Privet Drive, were proud to say that they were perfectly normal, thank you very much. They were the last people you'd expect to be involved in anything strange or mysterious, because they just didn't hold with such nonsense. Mr.Dursley was the director of a firm called Grunnings, which made drills.He was a big, beefy man with hardly any neck, although he did have a very large mustache.Mrs.Dursley was thin and blonde and had nearly twice the usual amount of neck, which came in very useful as she spent so much of her time craning over garden fences, spying on the neighbors.The Dursleys had a small son called Dudley and in their opinion there was no finer boy anywhere.";

    strcpy(currentBuffer, str);
    temp.dataLen = strlen(str);
    temp.data = currentBuffer;

    pushBack(&ring, &temp);
    ThreadParams params = { &ring, packetBuffer };
    HANDLE MessageThread = 0;
    MessageThread = CreateThread(NULL, 0, HandleSendThread, &params, 0, NULL);
    if (MessageThread == NULL)
    {
        ExitProcess(MessageThread);
    }
    WaitForSingleObject(MessageThread, INFINITE);
    CloseHandle(MessageThread);
    system("pause");
    return 0;
}

DWORD WINAPI HandleSendThread(LPVOID params)
{
    ringBuffer * ring = ((ThreadParams*)params)->ptr1;
    void * buffer = ((ThreadParams*)params)->ptr2;
    Descriptor * temp = &ring->bufferData[ring->head];

    for (int i = 0; i < temp->dataLen; i++)
    {
        printf("%c", ((char*)temp->data)[i]);
    }
    printf("\n");
    return 0;
}
</code>```

Body:
I need to send a message from Main thread to my Created Thread using WinAPI and Ring Buffer.

I defined structures and wrote functions for my Ring buffer.
Ring Buffer - it contains head, tail, size and pointer to the structure Descriptor which has length of Data and data itself. As I need to send 2 parameters to CreateThread function, I created the third structure ThreadParams to keep 2 parameters.

I want to leave this structures how they are now, not changeable.

typedef struct _Descriptor
{
    uint32_t dataLen;
    void * data;
} Descriptor;

typedef struct _ringBuffer
{
    Descriptor *bufferData;
    int head;
    int tail;
    int size;
} ringBuffer;

typedef struct _ThreadParams
{
    void * ptr1;
    void * ptr2;
} ThreadParams;

There are my realisations of Ring Buffer functions:

void bufferFree(ringBuffer *buffer)
{
    free(buffer->bufferData);
}

void ringInitialization(ringBuffer *buffer, int size)
{
    buffer->size = size;
    buffer->head = 0;
    buffer->tail = 0;
    buffer->bufferData = (Descriptor*)malloc(sizeof(Descriptor) * size);
}

int pushBack(ringBuffer *buffer, void * data) // fill buffer
{
    buffer->bufferData[buffer->tail++] = *(Descriptor*)data;
    if (buffer->tail == buffer->size)
    {
        buffer->tail = 0;
    }
    return 0;
}

int popFront(ringBuffer *buffer)
{
    if (buffer->head != buffer->tail)
    {
        buffer->head++;
        if (buffer->head == buffer->size)
        {
            buffer->head = 0;
        }
    }
    return 0;
}

My main: I checked that I can send a few bytes (the memory is shared between threads), now I need to send a big message (> BUFF_SIZE) though Ring Buffer what I'm trying to do in while() cycle. Here is the question: how should I do it? My thing doesn't work because I catch an exception in printf() function (memory acces violation).

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#include <strsafe.h>
#include <stdint.h>

#define RING_SIZE 256
#define BUFFER_SIZE 1024

DWORD WINAPI HandleSendThread(LPVOID params);

uint8_t * getPointer(uint8_t *buffer, uint32_t index)
{
    uint8_t * ptr = ((uint8_t*)buffer) + index * BUFFER_SIZE;
    return ptr;
}

int main(int argc, char * argv[])
{
    //Descriptor * ringData = (Descriptor *)malloc(sizeof(Descriptor) * RING_SIZE);

    ringBuffer ring;
    ringInitialization(&ring, RING_SIZE);
    void * packetBuffer = malloc(BUFFER_SIZE * RING_SIZE);
    uint8_t * currentBuffer = getPointer(packetBuffer, 0);
    uint8_t * str = "Mr. and Mrs. Dursley, of number four, Privet Drive, were proud to say that they were perfectly normal, thank you very much. They were the last people you'd expect to be involved in anything strange or mysterious, because they just didn't hold with such nonsense. Mr.Dursley was the director of a firm called Grunnings, which made drills.He was a big, beefy man with hardly any neck, although he did have a very large mustache.Mrs.Dursley was thin and blonde and had nearly twice the usual amount of neck, which came in very useful as she spent so much of her time craning over garden fences, spying on the neighbors.The Dursleys had a small son called Dudley and in their opinion there was no finer boy anywhere.";

    strcpy(currentBuffer, str);
    ring.bufferData[0].data = currentBuffer;
    ring.bufferData[0].dataLen = strlen(str);

    int currentSize = 0;
    int ringSize = RING_SIZE;
    while(ring.bufferData[0].data != '\0')
    {
        for (int i = currentSize; i < ringSize; i + RING_SIZE)
        {
            pushBack(&ring, currentBuffer);
            printf("h = %s, tail = %s, dataBuffer = %s\n", (char*)ring.head, (char*)ring.tail, (char*)ring.bufferData[i].data);
        }
        currentSize = ringSize;
        ringSize = 2 * ringSize;
        popFront(&ring);
    }

    ThreadParams params = { &ring, packetBuffer };
    HANDLE MessageThread = 0;
    MessageThread = CreateThread(NULL, 0, HandleSendThread, &params, 0, NULL);
    if (MessageThread == NULL)
    {
        ExitProcess(MessageThread);
    }

    WaitForSingleObject(MessageThread, INFINITE);
    CloseHandle(MessageThread);
    system("pause");
    return 0;
}

And my CreateThread function:

DWORD WINAPI HandleSendThread(LPVOID params)
{
    ringBuffer * ring = ((ThreadParams*)params)->ptr1;
    void * buffer = ((ThreadParams*)params)->ptr2;
    //ring->bufferData[0].dataLen = sizeof(buffer) + sizeof(ring->bufferData[0])*1024;

    printf("Shared memory check: ringBuffer data = \"%s\", \nlength = %d\n", (char*)ring->bufferData[0].data, ring->bufferData[0].dataLen);
    return 0;
}

Body:
Found a solution

int main(int argc, char * argv[])
{
    ringBuffer ring;
    ringInitialization(&ring, RING_SIZE);
    void * packetBuffer = malloc(BUFFER_SIZE * RING_SIZE);
    Descriptor temp = { 0 };
    uint8_t * currentBuffer = getPointer(packetBuffer, 0);
    uint8_t * str = "Mr. and Mrs. Dursley, of number four, Privet Drive, were proud to say that they were perfectly normal, thank you very much. They were the last people you'd expect to be involved in anything strange or mysterious, because they just didn't hold with such nonsense. Mr.Dursley was the director of a firm called Grunnings, which made drills.He was a big, beefy man with hardly any neck, although he did have a very large mustache.Mrs.Dursley was thin and blonde and had nearly twice the usual amount of neck, which came in very useful as she spent so much of her time craning over garden fences, spying on the neighbors.The Dursleys had a small son called Dudley and in their opinion there was no finer boy anywhere.";

    strcpy(currentBuffer, str);
    temp.dataLen = strlen(str);
    temp.data = currentBuffer;

    pushBack(&ring, &temp);
    ThreadParams params = { &ring, packetBuffer };
    HANDLE MessageThread = 0;
    MessageThread = CreateThread(NULL, 0, HandleSendThread, &params, 0, NULL);
    if (MessageThread == NULL)
    {
        ExitProcess(MessageThread);
    }
    WaitForSingleObject(MessageThread, INFINITE);
    CloseHandle(MessageThread);
    system("pause");
    return 0;
}

DWORD WINAPI HandleSendThread(LPVOID params)
{
    ringBuffer * ring = ((ThreadParams*)params)->ptr1;
    void * buffer = ((ThreadParams*)params)->ptr2;
    Descriptor * temp = &ring->bufferData[ring->head];

    for (int i = 0; i < temp->dataLen; i++)
    {
        printf("%c", ((char*)temp->data)[i]);
    }
    printf("\n");
    return 0;
}


问:
Creating an extension method in C#
I'm trying to create an extension method in C# for the HtmlHelper class. I've read the MSDN page for it, and I'm sure I'm referencing the correct namespaces. I wonder what I could be doing wrong.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; //Correctly referencing the necessary namespaces, right?

namespace MvcApplication1.HelperMethods
{
    public static class NavigationalMenu
    {
        public static string MyMenu(this HtmlHelper helper)
        {
            CategoryRepository categoryRepo = new CategoryRepository();
            var categories = categoryRepo.FindAllCategories();

            foreach (Category c in categories)
            {
                helper.RouteLink(blablabla); //Construct links and return them.
            }

            //helper.RouteLink doesn't show up! C# wipeouuuuuttttt.
            //It's as if 'helper' doesn't have the RouteLink method there.
        }
    }
}
</code>```

First time that this happens to me when programming in C#. Anyone else encounter this problem?

答:
Your namespace may be wrong.  Try using System.Web.Mvc.Html;

http://msdn.microsoft.com/en-us/library/system.web.mvc.htmlhelper(VS.90).aspx

OwnerDisplayName: delete

Title: Creating an extension method in C#

Body:
I'm trying to create an extension method in C# for the HtmlHelper class. I've read the MSDN page for it, and I'm sure I'm referencing the correct namespaces. I wonder what I could be doing wrong.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; //Correctly referencing the necessary namespaces, right?

namespace MvcApplication1.HelperMethods
{
    public static class NavigationalMenu
    {
        public static string MyMenu(this HtmlHelper helper)
        {
            CategoryRepository categoryRepo = new CategoryRepository();
            var categories = categoryRepo.FindAllCategories();

            foreach (Category c in categories)
            {
                helper.RouteLink(blablabla); //Construct links and return them.
            }

            //helper.RouteLink doesn't show up! C# wipeouuuuuttttt.
            //It's as if 'helper' doesn't have the RouteLink method there.
        }
    }
}

First time that this happens to me when programming in C#. Anyone else encounter this problem?


问:
Is there a way to inject JavaScript into WebView for latter use?
I have a JavaScript script that looks for the location of an element in page using jQuery in a loaded WebView.

For some reason this script works only sometimes and I suspect that it's related to the time it takes to load the script or maybe the page.
I'm trying to evaluate the script only on onPageFinished of the WebViewClient interface, So I don't think that the loading of the page has something to do with it, but maybe I'm wrong.

I am an Android developer and have a very limited understanding in JavaScript and jQuery but I know the script works because the same script is used in the iOS platform and returns good results always.

Chances are there is some timing problem with loading the script itself.

So the question is: Is there a way to load the script before its usage, or load it and make sure it loaded into the WebView.

答:
Scripts are loaded whenever you call the script tag .
They stay loaded until that page is destroyed.
They are reachable by any page.

If my thoughts are right, I believe the direct answer for your question is YES. However you would like to know is HOW.

In a webpage you can check if the script is loaded with jQuery, put that piece of code in the end of your

```<code>$(function() {
  //anything here is executed after page is loaded
});
</code>```

If you are trying to execute a javascript over a page you don't have control of it's source, I'm afraid you can't do what you want, because of security rules of web standards... You would have to hack it someway I can't help.

Body:
Scripts are loaded whenever you call the script tag .
They stay loaded until that page is destroyed.
They are reachable by any page.

If my thoughts are right, I believe the direct answer for your question is YES. However you would like to know is HOW.

In a webpage you can check if the script is loaded with jQuery, put that piece of code in the end of your

$(function() {
  //anything here is executed after page is loaded
});

If you are trying to execute a javascript over a page you don't have control of it's source, I'm afraid you can't do what you want, because of security rules of web standards... You would have to hack it someway I can't help.


问:
clicking on dynamic values in a web table in selenium
Below is my Table structure:

I want to click on the first cell of "policyno " column only if value is not empty

How do I achieve this?

答:
Since you didn't specified, I have no idea what programming language do you need, but the idea is the same for all. I've used C# for the code below:

Get all the policy number elements. This can be easily achieved by getting the elements by xpath. In your case, I expect the lblPolicyNumber to be present in all:

IList allPolicyElems = driver.FindElements(By.Xpath(".//*[contains(@id,'lblPolicyElements')]"));

Now, you have 2 options to click on the element you need. First, you click on an element using his position in the list: allPolicyElems[0].Click(); (not the best way to do it) or by using LINQ (or lambda expressions for Java) to get the element by the text (perhaps you have the text stored in a variable from some previous actions): allPolicyElems.FirstOrDefault(t => t.Text == "your_text_here").Click();

This can be further expanded by applying the same logic in case you need to get the correct element by knowing other cell values from the same row.


问:
How to compare two XML files ignoring specific tags in java JDK7
I am trying to compare the two XML files where certain tags has to be ignored. How can this be achieved? Since I am using JDK 7, lambda expressions cannot be used.</p>

答:
The lambda expression really only is syntactic sugar for an anonymous inner class. The example of Java: How do I ignore certain elements when comparing XML?

```<code>.withNodeFilter(node -> !node.getNodeName().equals(someName))
</code>```

is really just

```<code>import org.xmlunit.util.Predicate;
import org.w3c.dom.Node;

.withNodeFilter(new Predicate<Node>() {
    public boolean test(Node node) {
        return !node.getNodeName().equals(someName);
    }
})
</code>```

No need for Java8.

Body:
The lambda expression really only is syntactic sugar for an anonymous inner class. The example of Java: How do I ignore certain elements when comparing XML?

.withNodeFilter(node -> !node.getNodeName().equals(someName))

is really just

import org.xmlunit.util.Predicate;
import org.w3c.dom.Node;

.withNodeFilter(new Predicate<Node>() {
    public boolean test(Node node) {
        return !node.getNodeName().equals(someName);
    }
})

No need for Java8.