问:
Dagger 2 customizing provided retrofit
I'm looking for a better way to manage my retrofit DI. My app could call for several variations of retrofit: non-retryable, longer timeouts, cached or non-cached etc.

I've worked out I can use named params and specify a different kind of okhttp/retrofit to be provided when I use it, but it means I have to make a different provided function for every possible combination, and maintain the strings for the named params. I can see my NetworkModule class becoming very large then.

NetworkModule.kt

```<code>@Module
class NetworkModule {

    @Provides
    @Singleton
    fun provideHttpLoggingInterceptor(): HttpLoggingInterceptor {
        val loggingInterceptor = HttpLoggingInterceptor { message -> Timber.d(message) }
        loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        return loggingInterceptor
    }

    @Provides
    @Named("standard")
    @Singleton
    fun provideOkHttpClient(httpLoggingInterceptor: HttpLoggingInterceptor): OkHttpClient {
        val httpClientBuilder = OkHttpClient.Builder()
        if (BuildConfig.DEBUG) httpClientBuilder.addInterceptor(httpLoggingInterceptor)
        return httpClientBuilder.build()
    }

    @Provides
    @Named("standard")
    @Singleton
    fun provideRetrofit(@Named("baseUrl") baseUrl: String, @Named("standard") okHttpClient: OkHttpClient): Retrofit {
        return Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
    }
}
</code>```

LoginApiModule.kt

```<code>@Module(includes = arrayOf(NetworkModule::class))
class LoginApiModule {

    @Provides
    @Singleton
    internal fun provideLoginApi( @Named("standard") retrofit: Retrofit): LoginService {
        return retrofit.create(LoginService::class.java)
    }
}
</code>```

In this example I would need a provide<some specialization>OkHttpClient() function for every specialization:

one for a longer timeout

one for non-retryability

one for both

one for caching

one for caching with a longer timeout

one for cachine with non-retryability etc. etc.

答: You can play with multiple instances of OkHttpClient (that share stuff, see: https://github.com/square/okhttp/wiki/Recipes#per-call-configuration) and network interceptors with custom headers. People used to do this for caching in the past (see: https://krtkush.github.io/2016/06/02/caching-using-okhttp-part-2.html). Also, instead of using @Named, try @Qualifiers!

Title: Dagger 2 customizing provided retrofit

Body:
I'm looking for a better way to manage my retrofit DI. My app could call for several variations of retrofit: non-retryable, longer timeouts, cached or non-cached etc.

I've worked out I can use named params and specify a different kind of okhttp/retrofit to be provided when I use it, but it means I have to make a different provided function for every possible combination, and maintain the strings for the named params. I can see my NetworkModule class becoming very large then.

NetworkModule.kt

@Module
class NetworkModule {

    @Provides
    @Singleton
    fun provideHttpLoggingInterceptor(): HttpLoggingInterceptor {
        val loggingInterceptor = HttpLoggingInterceptor { message -> Timber.d(message) }
        loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        return loggingInterceptor
    }

    @Provides
    @Named("standard")
    @Singleton
    fun provideOkHttpClient(httpLoggingInterceptor: HttpLoggingInterceptor): OkHttpClient {
        val httpClientBuilder = OkHttpClient.Builder()
        if (BuildConfig.DEBUG) httpClientBuilder.addInterceptor(httpLoggingInterceptor)
        return httpClientBuilder.build()
    }

    @Provides
    @Named("standard")
    @Singleton
    fun provideRetrofit(@Named("baseUrl") baseUrl: String, @Named("standard") okHttpClient: OkHttpClient): Retrofit {
        return Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
    }
}

LoginApiModule.kt

@Module(includes = arrayOf(NetworkModule::class))
class LoginApiModule {

    @Provides
    @Singleton
    internal fun provideLoginApi( @Named("standard") retrofit: Retrofit): LoginService {
        return retrofit.create(LoginService::class.java)
    }
}

In this example I would need a provide<some specialization>OkHttpClient() function for every specialization:

one for a longer timeout

one for non-retryability

one for both

one for caching

one for caching with a longer timeout

one for cachine with non-retryability etc. etc.


来源: stackexchange

问:
How can we destroy child objects in edit mode(Unity3d)?
It is kind of strange things, but if you'll try to destroy child objects with DestroyImmediate function, then you will have unpredictabe result.

In my case Unity did not destroyed all childs, but did it for only half of them.

```<code>        foreach(var child in parent)
        {
            DestroyImmediate(child);
        }
</code>```

答:
This is how i destroy children in Edit Mode:</p>

```<code>for (int i = this.transform.childCount; i > 0; --i)
    DestroyImmediate(this.transform.GetChild(0).gameObject);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
It is kind of strange things, but if you'll try to destroy child objects with DestroyImmediate function, then you will have unpredictabe result.

In my case Unity did not destroyed all childs, but did it for only half of them.

        foreach(var child in parent)
        {
            DestroyImmediate(child);
        }

Body:
This is how i destroy children in Edit Mode:

for (int i = this.transform.childCount; i > 0; --i)
    DestroyImmediate(this.transform.GetChild(0).gameObject);


问:
DynamoDB api omit data type from scan
According to the documentation, the result of a scan returns the data type like so:

```<code>'Items' => [
    [
        '<AttributeName>' => [
            'B' => <string || resource || Psr\Http\Message\StreamInterface>,
            'BS' => [<string || resource || Psr\Http\Message\StreamInterface>, ...],
            'N' => '<string>',
            'NS' => ['<string>', ...],
            'S' => '<string>',
            'SS' => ['<string>', ...],
        ],
    ],
</code>```

So, if I want to access the attribute 'price' on the first item, in PHP, I would do $result['Items'][0]['price']['N']. Any way to return the result without the data type?

答:
I figured it out. Just need to use Marshaler.</p>

```<code>use Aws\DynamoDb\Marshaler;

$dynamodb = $aws_sdk->createDynamoDb();
$marshaler = new Marshaler();

$params = [
    'TableName' => $table
];

try {
    while (true) {
        $result = $dynamodb->scan($params);
        foreach ($result['Items'] as $i) {
            $item = $marshaler->unmarshalItem($i);
        }
    }
} catch (DynamoDbException $e) {
    echo "Unable to scan:\n";
    echo $e->getMessage() . "\n";
}
</code>```

Title: DynamoDB api omit data type from scan

Body:
According to the documentation, the result of a scan returns the data type like so:

'Items' => [
    [
        '<AttributeName>' => [
            'B' => <string || resource || Psr\Http\Message\StreamInterface>,
            'BS' => [<string || resource || Psr\Http\Message\StreamInterface>, ...],
            'N' => '<string>',
            'NS' => ['<string>', ...],
            'S' => '<string>',
            'SS' => ['<string>', ...],
        ],
    ],

So, if I want to access the attribute 'price' on the first item, in PHP, I would do $result['Items'][0]['price']['N']. Any way to return the result without the data type?

Body:
I figured it out. Just need to use Marshaler.

use Aws\DynamoDb\Marshaler;

$dynamodb = $aws_sdk->createDynamoDb();
$marshaler = new Marshaler();

$params = [
    'TableName' => $table
];

try {
    while (true) {
        $result = $dynamodb->scan($params);
        foreach ($result['Items'] as $i) {
            $item = $marshaler->unmarshalItem($i);
        }
    }
} catch (DynamoDbException $e) {
    echo "Unable to scan:\n";
    echo $e->getMessage() . "\n";
}


问:
loop throgh all the data to search particular string
I want to loop throgh all the column of all the tables available in my database to check which column containts string "Kroki Homes".

I have approx. 56 tables in my database. So it is hard to check in all the columns of these 56 tables. is there any easy way to achieve this in sql server?

答:
You need to write a stored procedure to scan through all the tables. </p>

<p>The script below gives to the tables and columns. From this you should create a SQL in-flight and execute dynamically to SELECT from tables. Let us know if you need more details. </p>

```<code>SELECT tb.name AS table_name,
       c.name AS column_name,
       c.column_id,
       tp.name AS column_data_type,
       c.max_length,
       c.precision,
       c.scale,
       CASE c.is_nullable WHEN 1 THEN 'YES' ELSE 'NO' END AS is_nullable
  FROM sys.tables tb,
       sys.columns c,
       sys.types   tp
  WHERE tb.object_id = c.object_id
    AND SCHEMA_NAME(tb.schema_id) = 'dbo'
    AND c.user_type_id = tp.user_type_id
  ORDER BY table_name, column_id;
</code>```

Body:
You need to write a stored procedure to scan through all the tables.

The script below gives to the tables and columns. From this you should create a SQL in-flight and execute dynamically to SELECT from tables. Let us know if you need more details.

SELECT tb.name AS table_name,
       c.name AS column_name,
       c.column_id,
       tp.name AS column_data_type,
       c.max_length,
       c.precision,
       c.scale,
       CASE c.is_nullable WHEN 1 THEN 'YES' ELSE 'NO' END AS is_nullable
  FROM sys.tables tb,
       sys.columns c,
       sys.types   tp
  WHERE tb.object_id = c.object_id
    AND SCHEMA_NAME(tb.schema_id) = 'dbo'
    AND c.user_type_id = tp.user_type_id
  ORDER BY table_name, column_id;


问:
Very Advanced Javascript WYSIWYG editor
I need a solution where a user could enter the URL of a web page in my system. The page would load, and then the user could click a certain section that he wants to change. So basically what I need is, a way to display a web page inside my app (could possibly be done with frames but I'd prefer not to have a horizontal scroll bar), and then another way to let users select a block of text or a page element.

I.e if a block of text is in a div, hovering above the text would outline that div using a faint green color (hovering away would remove this border/outline), and clicking the text would draw a solid green border around it to show that its been selected, and then some content on my page will show the id of the div, and let the user specify some other info that i need.

So I probably need a way to get all the
s,
s, s,
s and any other 'container' tags, and then have the ability to cause hovering/clicking of them to change their style.border property, and the ability to retrieve their id/name,

For a block of text the border could probably work, but what about images and such? Also, what if a
 doesn't have an ID/Name, how could it be specified?

答:
You could use  tags, then set contentEditable = on. This way, the browser supplies the WYSIWYG features. The borders, etc. may not work, though. Some code:

```<code>var idno = 0;

function addEditor(parent, url) {
    parent.innerHTML += '<iframe src="' + url + '" id="edit' + idno + '"></iframe>';
    var el = document.getElementById("edit" + idno);
    el.contentEditable = true;
    return el;
}

addEditor(document.body, "http://google.com").innerHTML += "Hello!";
</code>```

Should work.

OwnerDisplayName: Click Upvote

ContentLicense: CC BY-SA 2.5

Title: Very Advanced Javascript WYSIWYG editor

LastEditorDisplayName: Tom

Body:
You could use <iframe> tags, then set contentEditable = on. This way, the browser supplies the WYSIWYG features. The borders, etc. may not work, though. Some code:

var idno = 0;

function addEditor(parent, url) {
    parent.innerHTML += '<iframe src="' + url + '" id="edit' + idno + '"></iframe>';
    var el = document.getElementById("edit" + idno);
    el.contentEditable = true;
    return el;
}

addEditor(document.body, "http://google.com").innerHTML += "Hello!";

Should work.

OwnerDisplayName: person-b


问:
methodtest.c:(.text+0x47): undefined reference to `pritnf'
So im trying to work with methods for the first time in c and when i compile i get this as an output

```<code>gcc -o methodtest methodtest.o
methodtest.o: In function `main':
methodtest.c:(.text+0x47): undefined reference to `pritnf'
collect2: ld returned 1 exit status
make: *** [methodtest] Error 1
</code>```

the code looks like this

```<code>void main(void)
{
  int num, num2, num3;
  num = 3;
  num2 = 2;
  num3 = 1;
  int ans = addem(num, num2, num3);
  pritnf("%d\n", ans);
}

int addem(int num, int num2, int num3)
{
  return(num+num2+num3);
}
</code>```

why why am i getting this error or whatever it is?

答:
Apart from the printf typo, you can't allocate variables in the middle of main like that. In C, all variables must be allocated at the beginning of the scope (directly after the "{" ).

Though perhaps you have set the compiler to compile the code as C++?

Body:
So im trying to work with methods for the first time in c and when i compile i get this as an output

gcc -o methodtest methodtest.o
methodtest.o: In function `main':
methodtest.c:(.text+0x47): undefined reference to `pritnf'
collect2: ld returned 1 exit status
make: *** [methodtest] Error 1

the code looks like this

void main(void)
{
  int num, num2, num3;
  num = 3;
  num2 = 2;
  num3 = 1;
  int ans = addem(num, num2, num3);
  pritnf("%d\n", ans);
}

int addem(int num, int num2, int num3)
{
  return(num+num2+num3);
}

why why am i getting this error or whatever it is?


问:
how to create a pipe module Angular
I have a module which is a a group of pipes. When I try to install this module in my app, it says that the xxx pipe is not found

my app.module looks something like this:

```<code>import { PipesModule } from '@Pricetravel/pipes.module';
@NgModule({
  declarations: [
    AppComponent,

  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    routing,
    PipesModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

Is there a special way to create the pipe module? or a special way to import it?

thanks and greetings!

答:
you have to export your piple classes also , to export pipe classes in you module you have to write name of classes in export property of module.

In your code given in comment you forgot to export that is the reason why you are not getting piple declared in module in another module where you are using piple module.

```<code>@NgModule({
  declarations: [ MyFilter],
  imports: [],
  exports:[MyFilter],//export list here
  providers: []
})
export class PipleModule { }
</code>```

ContentLicense: CC BY-SA 4.0

Title: how to create a pipe module Angular

Body:
I have a module which is a a group of pipes. When I try to install this module in my app, it says that the xxx pipe is not found

my app.module looks something like this:

import { PipesModule } from '@Pricetravel/pipes.module';
@NgModule({
  declarations: [
    AppComponent,

  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    routing,
    PipesModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Is there a special way to create the pipe module? or a special way to import it?

thanks and greetings!

Body:
you have to export your piple classes also , to export pipe classes in you module you have to write name of classes in export property of module.

In your code given in comment you forgot to export that is the reason why you are not getting piple declared in module in another module where you are using piple module.

@NgModule({
  declarations: [ MyFilter],
  imports: [],
  exports:[MyFilter],//export list here
  providers: []
})
export class PipleModule { }


问:
Does WordPress escape data to prevent SQL injections when using the Settings API?
I'm having a difficult time finding any information on this topic. I'm creating a plugin that allows users to add custom JS code such as, but not limited to, Google Analytics. To do this, I used the Settings API to create a settings page with a few textarea fields. I used the following page as a guide: https://developer.wordpress.org/plugins/settings/custom-settings-page/.

My question is, what do I need to do make sure the data going into the database is safe? Or is it already safe (i.e. escaped by WordPress)? I thought about using the sanitize_textarea_field function in a callback in the register_setting function, however, the data (e.g. ) looks exactly the same with or without the sanitize function after it's serialized by WordPress.

Am I safe to assume that WordPress escapes all data going into the database if I use the Settings API, or do I need to write custom code to do this? If so, what is the process to escape data if I'm using the Settings API?

答:
Yes, when you're using the WP API (not just for settings, but the other functions too, like update_post_meta, wp_insert_post etc), WP will make sure that data is properly escaped before it is sent to the database.

The few exceptions will state explicitly that you can input SQL (e.g. the posts_orderby filter).

Unless you have unsafe characters (single quotes!) in your data, you won't see a change before and after escaping. Note that the sanitize_* functions don't deal with SQL injections, but try to clean up the content.


问:
vue.js how do I bind a class on click to a list item created by v-for utilising a template component?
I am trying to apply an active class to a list item in a template component when it is clicked upon, this should be exclusive and remove the class from all other list items.

I have tried passing through a new data object on click and referencing that, I have even used the example in the official documentation to no avail, I have no idea why it isn't working.

Vue.component('delivery-options', {
      props: ['deliveries'],
      template: '

{{ deliveries.price }}{{ deliveries.title }}

{{ deliveries.desc }}

'
    })
    Vue.component('ledger', {
      props: ['values'],
      template: '

{{ values.title }}{{ values.price }}

'
    })
    var checkout = new Vue({
      el: '#checkout-app',
      data: {
        deliveryList: [
          { id: 0, price: '£3.99 ', title: 'Home delivery', desc: 'Lorem ipsum dolor sit amet.' },
          { id: 1, price: 'Free ', title: 'Store collection', desc: 'Lorem ipsum dolor sit amet.' },
          { id: 2, price: '£5.99 ', title: 'Precise delivery', desc: 'Lorem ipsum dolor sit amet.' }
        ],
        valuesList: [
          { id: 0, price: '£1233.99', title: 'Order value', desc: 'Lorem ipsum dolor sit amet.' },
          { id: 1, price: '£3.99', title: 'Delivery', desc: 'Lorem ipsum dolor sit amet.' },
          { id: 2, price: '£5.99', title: 'Total', desc: 'Your total including delivery.' }
        ]
      }
    })```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul {
  padding: 0;
}

ul li {
  list-style-type: none;
}

.delivery-options li {
  padding: 1rem;
  margin: 1rem;
  border-radius: 3px;
  border: 1px solid grey;
}

.ledger {
  padding: 1rem;
  margin: 1rem;
  border-radius: 3px;
  border: 1px solid grey;
}</code>```

      <delivery-options
        v-for="option in deliveryList"
        v-bind:deliveries="option"
        v-bind:key="option.id">
      </delivery-options>

      <ledger
        v-for="value in valuesList"
        v-bind:values="value"
        v-bind:key="value.id">
      </ledger>

```

答:
You would need to do something like this:

console.clear()

Vue.component('delivery-options', {
      props: ['deliveries', "isActive"],
      template: `<li @click="$emit('set-active', deliveries)" :class="{active: isActive}"><p><strong>{{ deliveries.price }}</strong>{{ deliveries.title }}</p><p>{{ deliveries.desc }}</p></li>`
    })
    Vue.component('ledger', {
      props: ['values'],
      template: '

{{ values.title }}{{ values.price }}

'
    })
    var checkout = new Vue({
      el: '#checkout-app',
      data: {
        activeDelivery: null,
        deliveryList: [
          { id: 0, price: '£3.99 ', title: 'Home delivery', desc: 'Lorem ipsum dolor sit amet.' },
          { id: 1, price: 'Free ', title: 'Store collection', desc: 'Lorem ipsum dolor sit amet.' },
          { id: 2, price: '£5.99 ', title: 'Precise delivery', desc: 'Lorem ipsum dolor sit amet.' }
        ],
        valuesList: [
          { id: 0, price: '£1233.99', title: 'Order value', desc: 'Lorem ipsum dolor sit amet.' },
          { id: 1, price: '£3.99', title: 'Delivery', desc: 'Lorem ipsum dolor sit amet.' },
          { id: 2, price: '£5.99', title: 'Total', desc: 'Your total including delivery.' }
        ]
      },
    })```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul {
  padding: 0;
}

ul li {
  list-style-type: none;
}

.delivery-options li {
  padding: 1rem;
  margin: 1rem;
  border-radius: 3px;
  border: 1px solid grey;
}

.ledger {
  padding: 1rem;
  margin: 1rem;
  border-radius: 3px;
  border: 1px solid grey;
}

.active {
  color: red
}</code>```

      <delivery-options
        v-for="option in deliveryList"
        v-bind:deliveries="option"
        v-bind:key="option.id"
        v-bind:is-active="option === activeDelivery"
        v-on:set-active="v => activeDelivery = v">
      </delivery-options>

      <ledger
        v-for="value in valuesList"
        v-bind:values="value"
        v-bind:key="value.id">
      </ledger>

```

Basically, track which delivery is active using a data property, then set the class in the component based on whether it is the active delivery or not. In order to set the active delivery on click, the component needs to emit an event letting the parent know which delivery was clicked.

Body:
I am trying to apply an active class to a list item in a template component when it is clicked upon, this should be exclusive and remove the class from all other list items.

I have tried passing through a new data object on click and referencing that, I have even used the example in the official documentation to no avail, I have no idea why it isn't working.

Vue.component('delivery-options', {
      props: ['deliveries'],
      template: '

{{ deliveries.price }}{{ deliveries.title }}

{{ deliveries.desc }}

'
    })
    Vue.component('ledger', {
      props: ['values'],
      template: '

{{ values.title }}{{ values.price }}

'
    })
    var checkout = new Vue({
      el: '#checkout-app',
      data: {
        deliveryList: [
          { id: 0, price: '£3.99 ', title: 'Home delivery', desc: 'Lorem ipsum dolor sit amet.' },
          { id: 1, price: 'Free ', title: 'Store collection', desc: 'Lorem ipsum dolor sit amet.' },
          { id: 2, price: '£5.99 ', title: 'Precise delivery', desc: 'Lorem ipsum dolor sit amet.' }
        ],
        valuesList: [
          { id: 0, price: '£1233.99', title: 'Order value', desc: 'Lorem ipsum dolor sit amet.' },
          { id: 1, price: '£3.99', title: 'Delivery', desc: 'Lorem ipsum dolor sit amet.' },
          { id: 2, price: '£5.99', title: 'Total', desc: 'Your total including delivery.' }
        ]
      }
    })

ul {
  padding: 0;
}

ul li {
  list-style-type: none;
}

.delivery-options li {
  padding: 1rem;
  margin: 1rem;
  border-radius: 3px;
  border: 1px solid grey;
}

.ledger {
  padding: 1rem;
  margin: 1rem;
  border-radius: 3px;
  border: 1px solid grey;
}

      <delivery-options
        v-for="option in deliveryList"
        v-bind:deliveries="option"
        v-bind:key="option.id">
      </delivery-options>

      <ledger
        v-for="value in valuesList"
        v-bind:values="value"
        v-bind:key="value.id">
      </ledger>

Body:
You would need to do something like this:

console.clear()

Vue.component('delivery-options', {
      props: ['deliveries', "isActive"],
      template: `<li @click="$emit('set-active', deliveries)" :class="{active: isActive}"><p><strong>{{ deliveries.price }}</strong>{{ deliveries.title }}</p><p>{{ deliveries.desc }}</p></li>`
    })
    Vue.component('ledger', {
      props: ['values'],
      template: '<li><p>{{ values.title }}<span>{{ values.price }}</span></p></li>'
    })
    var checkout = new Vue({
      el: '#checkout-app',
      data: {
        activeDelivery: null,
        deliveryList: [
          { id: 0, price: '£3.99 ', title: 'Home delivery', desc: 'Lorem ipsum dolor sit amet.' },
          { id: 1, price: 'Free ', title: 'Store collection', desc: 'Lorem ipsum dolor sit amet.' },
          { id: 2, price: '£5.99 ', title: 'Precise delivery', desc: 'Lorem ipsum dolor sit amet.' }
        ],
        valuesList: [
          { id: 0, price: '£1233.99', title: 'Order value', desc: 'Lorem ipsum dolor sit amet.' },
          { id: 1, price: '£3.99', title: 'Delivery', desc: 'Lorem ipsum dolor sit amet.' },
          { id: 2, price: '£5.99', title: 'Total', desc: 'Your total including delivery.' }
        ]
      },
    })

ul {
  padding: 0;
}

ul li {
  list-style-type: none;
}

.delivery-options li {
  padding: 1rem;
  margin: 1rem;
  border-radius: 3px;
  border: 1px solid grey;
}

.ledger {
  padding: 1rem;
  margin: 1rem;
  border-radius: 3px;
  border: 1px solid grey;
}

.active {
  color: red
}

<script src="https://unpkg.com/vue"></script>
<div id="checkout-app">
    <ul class="delivery-options">
      <delivery-options
        v-for="option in deliveryList"
        v-bind:deliveries="option"
        v-bind:key="option.id"
        v-bind:is-active="option === activeDelivery"
        v-on:set-active="v => activeDelivery = v">
      </delivery-options>
    </ul>
    <ul class="ledger">
      <ledger
        v-for="value in valuesList"
        v-bind:values="value"
        v-bind:key="value.id">
      </ledger>
    </ul>
  </div>

Basically, track which delivery is active using a data property, then set the class in the component based on whether it is the active delivery or not. In order to set the active delivery on click, the component needs to emit an event letting the parent know which delivery was clicked.


问:
wxPython PopUp notifications
We are building an app where in there will be a need to display the updates/notification (ex : like status updates/wall posts on FB). These needs to be displyed at the lower right corner of the window(like any other notifications). So was trying on some alternatives to best display the updates. Some option explored are PopupWindow (which was not that great for status update) and dialog (seems ok). Are there any other good options for this and is there any pre-defined end corners position constants? Plz suggest.</p>

答: I second the ToasterBox suggestion. You can also create your own Dialog though and position it by grabbing the screen resolution and the size of the dialog and setting its position. I've done the latter for a custom popup. On Macs, you can access Growl through a Python API that's mentioned on their website.</p>

Title: wxPython PopUp notifications


问:
Django: Custom Middleware results in NoneType Error
i got this Error:

```

     Internal Server Error: /
    Traceback (most recent call last):
      File "/home/cena/AjiiMajii/.venv/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
        response = get_response(request)
      File "/home/cena/AjiiMajii/.venv/local/lib/python2.7/site-packages/django/utils/deprecation.py", line 142, in __call__
        response = self.process_response(request, response)
      File "/home/cena/AjiiMajii/.venv/local/lib/python2.7/site-packages/django/middleware/clickjacking.py", line 32, in process_response
        if response.get('X-Frame-Options') is not None:
    AttributeError: 'NoneType' object has no attribute 'get'
    [04/Dec/2017 20:08:25] "GET / HTTP/1.1" 500 65880

    ```

my middleware is :

    ```</p>

```MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'cms.Middleware.Visits',
]

```
</code>```

and my custom middleware 'cms.Middleware.Visits'

class Visits(MiddlewareMixin):
    def __init__(self,get_response):
        self.get_response = get_response
    def __call__(self, request):
            print '*'*22
            print self.get_client_ip(request)
            print '*'*22

    def get_client_ip(self,request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[-1].strip()
        else:
            ip = request.META.get('REMOTE_ADDR')
        return ip
    def RedisConnection(self):
        Connection=redis.Redis(host='localhost',port='6379')
        self.Connection=Connection
        return     self.Connection
    def IpCheker(self):
        # just set and count of visit[s] for ever ip
        print '%'*30
        print self.get_client_ip()
        print '%'*30
        self.RedisConnection()
        if self.Connection.get(self.CliReq):
            HashPattern=self.HashSetter(self.CliReq)
            UserId=self.Connection.get(self.CliReq)
            UserPattern="User:Id:{}".format(UserId)
            print UserPattern
            self.Connection.hincrby(UserPattern,'vcount')
        else:
            IDnum=self.IdGenerator(self.CliReq)
            self.Connection.set(self.CliReq,IDnum)
            HashPattern=self.HashSetter(self.CliReq)
            Location=self.GetLoc(self.CliReq)
            self.Connection.hset(HashPattern,'ip',self.CliReq)
            self.Connection.hset(HashPattern,'vcount',1)
            self.Connection.hset(HashPattern,'loc',Location)
    def HashSetter(self,ip):
         id=self.IdGenerator(ip)
         IdStyle='User:Id:{}'.format(id)
         return IdStyle
    def IdGenerator(self,ip):
        Count=self.Connection.keys('User:Id:*')
        id= len(Count) + 1
        return id
    def GetLoc(self,ip):
        #GetLocation oF ip's
        print 'f' * 80
        ApiLoc='http://www.freegeoip.net/json/'
        ABSLOC=requests.get('http://www.freegeoip.net/json/{}'.format(ip))
        LocInfo=json.loads(ABSLOC.content)
        return LocInfo['country_name']

```
</code>```

i cant resolve or debug this,
why this happen?

答:
I think in the middleware  call method you should return the response. Please check the document for reference:

Writing custom middleware

The error seems to happen since you are not returning the response in the call() method.

Body:
i got this Error:

     Internal Server Error: /
    Traceback (most recent call last):
      File "/home/cena/AjiiMajii/.venv/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
        response = get_response(request)
      File "/home/cena/AjiiMajii/.venv/local/lib/python2.7/site-packages/django/utils/deprecation.py", line 142, in __call__
        response = self.process_response(request, response)
      File "/home/cena/AjiiMajii/.venv/local/lib/python2.7/site-packages/django/middleware/clickjacking.py", line 32, in process_response
        if response.get('X-Frame-Options') is not None:
    AttributeError: 'NoneType' object has no attribute 'get'
    [04/Dec/2017 20:08:25] "GET / HTTP/1.1" 500 65880

my middleware is :

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'cms.Middleware.Visits',
]

and my custom middleware 'cms.Middleware.Visits'

class Visits(MiddlewareMixin):
    def __init__(self,get_response):
        self.get_response = get_response
    def __call__(self, request):
            print '*'*22
            print self.get_client_ip(request)
            print '*'*22

    def get_client_ip(self,request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[-1].strip()
        else:
            ip = request.META.get('REMOTE_ADDR')
        return ip
    def RedisConnection(self):
        Connection=redis.Redis(host='localhost',port='6379')
        self.Connection=Connection
        return     self.Connection
    def IpCheker(self):
        # just set and count of visit[s] for ever ip
        print '%'*30
        print self.get_client_ip()
        print '%'*30
        self.RedisConnection()
        if self.Connection.get(self.CliReq):
            HashPattern=self.HashSetter(self.CliReq)
            UserId=self.Connection.get(self.CliReq)
            UserPattern="User:Id:{}".format(UserId)
            print UserPattern
            self.Connection.hincrby(UserPattern,'vcount')
        else:
            IDnum=self.IdGenerator(self.CliReq)
            self.Connection.set(self.CliReq,IDnum)
            HashPattern=self.HashSetter(self.CliReq)
            Location=self.GetLoc(self.CliReq)
            self.Connection.hset(HashPattern,'ip',self.CliReq)
            self.Connection.hset(HashPattern,'vcount',1)
            self.Connection.hset(HashPattern,'loc',Location)
    def HashSetter(self,ip):
         id=self.IdGenerator(ip)
         IdStyle='User:Id:{}'.format(id)
         return IdStyle
    def IdGenerator(self,ip):
        Count=self.Connection.keys('User:Id:*')
        id= len(Count) + 1
        return id
    def GetLoc(self,ip):
        #GetLocation oF ip's
        print 'f' * 80
        ApiLoc='http://www.freegeoip.net/json/'
        ABSLOC=requests.get('http://www.freegeoip.net/json/{}'.format(ip))
        LocInfo=json.loads(ABSLOC.content)
        return LocInfo['country_name']

i cant resolve or debug this,
why this happen?


问:
Post With C# WebClient Multiple Json Object
I want to send Post Request with C# WebClient with this Json Schema :

```<code> [
  {
    "id": "00000000-0000-0000-0000-000000000000",
    "points": [
      {
        "timestamp": "2017-12-04T16:07:44.562Z",
        "value": 0
      }
    ]
  }
]
</code>```

I've tried This :

```<code>public class RequestData
{
    public string id {get; set; }
    public points points { get; set; }
}

public class points
{
     public DateTime timestamp { get; set; }
     public float value { get; set; }
}
</code>```

My Program :

```<code>Random number = new Random();
var req = new RequestData();
req.id = "0e13d9c-571c-44f4-b796-7c40c0e20a1d";
req.points = new points { timestamp = DateTime.UtcNow, value =
number.Next(100, 99999) };

JsonSerializerSettings settings = new JsonSerializerSettings();
var data = JsonConvert.SerializeObject(req);

WebClient client = new WebClient();

client.Headers.Add(HttpRequestHeader.Authorization,
AquaAtuhorization.accessToken);

client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
client.UploadString ("http://localhost:8080/api/v1/data/writeNumericValues",
data  );
</code>```

And I always get Http 415 (Unsupported Media Type).

How could I format my C# Object as the restApi accepeted Format.

答:
Look at the JSON, the square brackets [ ] denote that something is an array. In this case both RequestData and points have to be an array, see the example below:

```<code>public class RequestData
{
    public string id { get; set; }
    public List<points> points { get; set; }  // I use list, could be an array
}

public class points
{
    public DateTime timestamp { get; set; }
    public float value { get; set; }
}
</code>```

Then construct your req object like this:

```<code>var req = new List<RequestData> // Again I use list, could be an array
{
    new RequestData
    {
        id = "0e740d9c-571c-44f4-b796-7c40c0e20a1d",
        points = new List<points> // Defined as a list, even though it has one entry
        {
            new points
            {
                timestamp = DateTime.UtcNow,
                value = number.Next(100, 99999)
            }
        }
    }
};
</code>```

Then just serialize it as normal, the result will be the below:

```<code>[
  {
    "id":"0e740d9c-571c-44f4-b796-7c40c0e20a1d",
    "points":[
      {
        "timestamp":"2017-12-04T17:12:25.8957648Z",
        "value":59522.0
      }
    ]
  }
]
</code>```

Body:
I want to send Post Request with C# WebClient with this Json Schema :

 [
  {
    "id": "00000000-0000-0000-0000-000000000000",
    "points": [
      {
        "timestamp": "2017-12-04T16:07:44.562Z",
        "value": 0
      }
    ]
  }
]

I've tried This :

public class RequestData
{
    public string id {get; set; }
    public points points { get; set; }
}

public class points
{
     public DateTime timestamp { get; set; }
     public float value { get; set; }
}

My Program :

Random number = new Random();
var req = new RequestData();
req.id = "0e13d9c-571c-44f4-b796-7c40c0e20a1d";
req.points = new points { timestamp = DateTime.UtcNow, value =
number.Next(100, 99999) };

JsonSerializerSettings settings = new JsonSerializerSettings();
var data = JsonConvert.SerializeObject(req);

WebClient client = new WebClient();

client.Headers.Add(HttpRequestHeader.Authorization,
AquaAtuhorization.accessToken);

client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
client.UploadString ("http://localhost:8080/api/v1/data/writeNumericValues",
data  );

And I always get Http 415 (Unsupported Media Type).

How could I format my C# Object as the restApi accepeted Format.

Body:
Look at the JSON, the square brackets [ ] denote that something is an array. In this case both RequestData and points have to be an array, see the example below:

public class RequestData
{
    public string id { get; set; }
    public List<points> points { get; set; }  // I use list, could be an array
}

public class points
{
    public DateTime timestamp { get; set; }
    public float value { get; set; }
}

Then construct your req object like this:

var req = new List<RequestData> // Again I use list, could be an array
{
    new RequestData
    {
        id = "0e740d9c-571c-44f4-b796-7c40c0e20a1d",
        points = new List<points> // Defined as a list, even though it has one entry
        {
            new points
            {
                timestamp = DateTime.UtcNow,
                value = number.Next(100, 99999)
            }
        }
    }
};

Then just serialize it as normal, the result will be the below:

[
  {
    "id":"0e740d9c-571c-44f4-b796-7c40c0e20a1d",
    "points":[
      {
        "timestamp":"2017-12-04T17:12:25.8957648Z",
        "value":59522.0
      }
    ]
  }
]


问:
This property is read-only and can't be set
I'm using Access 2010 and I'm rusty as heck...  So I create a main form and an unbound subform.  Unbound to the main form, I should say, but bound to a record source.  Things work fine.

In the subform, I have a dropdown called cboGIReqNbr with IDs in it.  I also have a textbox called txtGIReqNbr.  What's supposed to happen is that when you choose a cboGIReqNbr from the dropdown, txtGIReqNbr is supposed to populate with the description.

I've got this in the AfterUpdate event of cboGIReqNbr:

```<code>Dim db As Database
Dim rec As Recordset
Dim sSql As String

Set db = CurrentDb

sSql = "Select GI_Request_Name from tblGIRequest where GI_Request_Nbr = '" & Me.cboGIReqNbr.Text & "'"

Set rec = db.OpenRecordset(sSql)

Me!txtGIReqNbr.SetFocus

Me!txtGIReqNbr.Text = rec(0)  <-- PROBLEM

Me.txtLanID = Forms!frmHoursAssigned.cboEmployee.Value
</code>```

rec(0) does, in fact, populate with the correct text.

The error I get on the problem line is; "This property is read-only and can't be set".  None of my objects should be read-only, and all the examples I could find online pointed to people using reserved words (i.e. using "Name" as a field name).

Anyone know how to solve this?

答:
You should use the .Value property to assign values to a text box. .Text changes the visible value and can only be used when the field has focus. .Value stores the actual value and can be used at any time.

```<code>Me!txtGIReqNbr.Value = rec(0)
</code>```

Also see: Distinction between using .text and .value in VBA Access

Body:
I'm using Access 2010 and I'm rusty as heck...  So I create a main form and an unbound subform.  Unbound to the main form, I should say, but bound to a record source.  Things work fine.

In the subform, I have a dropdown called cboGIReqNbr with IDs in it.  I also have a textbox called txtGIReqNbr.  What's supposed to happen is that when you choose a cboGIReqNbr from the dropdown, txtGIReqNbr is supposed to populate with the description.

I've got this in the AfterUpdate event of cboGIReqNbr:

Dim db As Database
Dim rec As Recordset
Dim sSql As String

Set db = CurrentDb

sSql = "Select GI_Request_Name from tblGIRequest where GI_Request_Nbr = '" & Me.cboGIReqNbr.Text & "'"

Set rec = db.OpenRecordset(sSql)

Me!txtGIReqNbr.SetFocus

Me!txtGIReqNbr.Text = rec(0)  <-- PROBLEM

Me.txtLanID = Forms!frmHoursAssigned.cboEmployee.Value

rec(0) does, in fact, populate with the correct text.

The error I get on the problem line is; "This property is read-only and can't be set".  None of my objects should be read-only, and all the examples I could find online pointed to people using reserved words (i.e. using "Name" as a field name).

Anyone know how to solve this?

Body:
You should use the .Value property to assign values to a text box. .Text changes the visible value and can only be used when the field has focus. .Value stores the actual value and can be used at any time.

Me!txtGIReqNbr.Value = rec(0)

Also see: Distinction between using .text and .value in VBA Access


问:
Java scanner works from second time
I am trying to call a method after enter in console is pressed. Problem is method is called from second time I press enter. How can call my method after first Enter press?</p>

```<code>public void read() {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Press Enter to continue");
    try {
        System.in.read();
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (scanner.hasNextLine()) {
        this.win();
    }
}
public void win() {
    if (true) {
        this.read();
    }
}
</code>```

答:
You don't need System.in.read();. The java.util.Scanner.hasNextLine() method returns true if there is another line in the input of this scanner. This method may block while waiting for input.

```<code>public class MyClass {
    public static void main(String args[]) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Press Enter to continue");

        if (scanner.hasNextLine()) {
             System.out.println("Victory!");
        }
    }
}
</code>```

Basically, your code waits for user to press any key at two points. First at System.in.read(); and then at scanner.hasNextLine(). That's why you need to press Enter key twice before victory gets printed on the console. Removing either System.in.read(); or scanner.hasNextLine() from your code will fix the issue.

Title: Java scanner works from second time

Body:
I am trying to call a method after enter in console is pressed. Problem is method is called from second time I press enter. How can call my method after first Enter press?

public void read() {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Press Enter to continue");
    try {
        System.in.read();
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (scanner.hasNextLine()) {
        this.win();
    }
}
public void win() {
    if (true) {
        this.read();
    }
}

Body:
You don't need System.in.read();. The java.util.Scanner.hasNextLine() method returns true if there is another line in the input of this scanner. This method may block while waiting for input.

public class MyClass {
    public static void main(String args[]) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Press Enter to continue");

        if (scanner.hasNextLine()) {
             System.out.println("Victory!");
        }
    }
}

Basically, your code waits for user to press any key at two points. First at System.in.read(); and then at scanner.hasNextLine(). That's why you need to press Enter key twice before victory gets printed on the console. Removing either System.in.read(); or scanner.hasNextLine() from your code will fix the issue.


问:
Validate Sql Column Names
I have 4-5 tables in one database (not SQL Server).

In my UI, users can enter some SQL conditions together with column names in a textbox. I need to verify if the SQL is correct and if these columns exist, and show any errors accordingly. I am using C# for server side.

I have a SQL Server database where our UI stores all the UI related information.

One approach is to create all these tables (just the table structure) in my SQL Server as well and then query a simple select on each table and show the errors or success message(s) accordingly.

So basically I would have the where clause as below or more conditions:

```<code>where a = b and c in(1,2)
</code>```

As mentioned above I would execute the above where clause against each table I created in SQL Server which would return error if column does not exist.

Is there a better way to approach this? I was thinking in case there is some other way to work without creating so many tables on my SQL Server.

I don't want to hard code these as the structure might change in near future. So looking for some maintainable solution. May be create a single table and store all this information in it.

Any suggestions are appreciated.

答:
use dmv function in MS sql server to validate the query string.
assign user string to the variable @Str_query

declare @Str_query as nvarchar(max);
set @Str_query ='SELECT [role_code],[role_description] FROM [dbname].[dbo].[Roles]'
SELECT error_message FROM sys.dm_exec_describe_first_result_set(@Str_query, NULL, 0) WHERE column_ordinal = 0

if there is an error message then query string is not valid for execution.

Title: Validate Sql Column Names

Body:
I have 4-5 tables in one database (not SQL Server).

In my UI, users can enter some SQL conditions together with column names in a textbox. I need to verify if the SQL is correct and if these columns exist, and show any errors accordingly. I am using C# for server side.

I have a SQL Server database where our UI stores all the UI related information.

One approach is to create all these tables (just the table structure) in my SQL Server as well and then query a simple select on each table and show the errors or success message(s) accordingly.

So basically I would have the where clause as below or more conditions:

where a = b and c in(1,2)

As mentioned above I would execute the above where clause against each table I created in SQL Server which would return error if column does not exist.

Is there a better way to approach this? I was thinking in case there is some other way to work without creating so many tables on my SQL Server.

I don't want to hard code these as the structure might change in near future. So looking for some maintainable solution. May be create a single table and store all this information in it.

Any suggestions are appreciated.


问:
Search a list of floats
I have a sorted list of floats where

```<code>l = [50.1234,50.1221,50.1200,51.5022,51.5021,51.4999,60,002,60.0023,60.0021]
</code>```

I want to group all the floats based on parts per million differences. I have a function:

```<code>def ComputePPMError(t,e):
    return (((e- t) /t) * 1e6)
</code>```

What is the most efficient way of doing this? In general I will have a list of objects that have a float property and I will want to do the same thing with a list of objects. For example:

```<code>class MZ:
    def __init__(self):
        self.FileID = ""
        self.Mass = 0
        self.Intensity = 0
        self.RT = 0
        self.ScanNumber = 0
</code>```

And now the list will be list = [MZ objects]

So the final results will be dictionary of {average mass : list of mz objects} In this example there should be three entries

The result is this:

```<code>l = [{mz1:list of mz Objects (3 entries)},{mz2:list of mz Objects (3 entries)},{mz3:list of mz Objects (3 entries)}
</code>```

So in the above result, the final list contains a dict where the key is the mz values as averages and the values a list of the mz objects that were used to be grouped.

答:
Here is solution for a sorted float list:

```<code>def interval_groups(l, interval):
    return [[item for item in l if item >= i and item < (i + interval)] for i in range(int(l[0]), int(l[-1])+1, interval)]

l = [50.1234, 50.1221, 50.1200, 51.5022, 51.5021, 51.4999, 60.002, 60.0023, 60.0021]

group_list = interval_groups(l, 1)
print(group_list)

group_dict = {sum(group)/len(group):group for group in group_list if group}
print(group_dict)
</code>```

Output:

```<code>[[50.1234, 50.1221, 50.12], [51.5022, 51.5021, 51.4999], [], [], [], [], [], [], [], [], [60.002, 60.0023, 60.0021]]
{50.121833333333335: [50.1234, 50.1221, 50.12], 51.5014: [51.5022, 51.5021, 51.4999], 60.002133333333326: [60.002, 60.0023, 60.0021]}
</code>```

Here is a clearer version of interval_groups function:

```<code>def interval_groups(l, interval):
    """interval must be integer"""
    ret_list = []
    first_item_as_int = int(l[0])
    last_item_as_int = int(l[-1])
    for i in range(first_item_as_int, last_item_as_int + 1, interval):
        interval_list = [item for item in l if item >= i and item < (i + interval)]
        ret_list.append(interval_list)

    return ret_list
</code>```

EDIT:

I deleted start_valueand you can modify function for list MZ objects as:

```<code>def interval_groups(list_of_MZ, interval):
    return [[item for item in list_of_MZ if item.mass >= i and item.mass < (i + interval)] for i in range(int(list_of_MZ[0].mass), int(list_of_MZ[-1].mass)+1, interval)]
</code>```

Title: Search a list of floats

Body:
I have a sorted list of floats where

l = [50.1234,50.1221,50.1200,51.5022,51.5021,51.4999,60,002,60.0023,60.0021]

I want to group all the floats based on parts per million differences. I have a function:

def ComputePPMError(t,e):
    return (((e- t) /t) * 1e6)

What is the most efficient way of doing this? In general I will have a list of objects that have a float property and I will want to do the same thing with a list of objects. For example:

class MZ:
    def __init__(self):
        self.FileID = ""
        self.Mass = 0
        self.Intensity = 0
        self.RT = 0
        self.ScanNumber = 0

And now the list will be list = [MZ objects]

So the final results will be dictionary of {average mass : list of mz objects} In this example there should be three entries

The result is this:

l = [{mz1:list of mz Objects (3 entries)},{mz2:list of mz Objects (3 entries)},{mz3:list of mz Objects (3 entries)}

So in the above result, the final list contains a dict where the key is the mz values as averages and the values a list of the mz objects that were used to be grouped.

Body:
Here is solution for a sorted float list:

def interval_groups(l, interval):
    return [[item for item in l if item >= i and item < (i + interval)] for i in range(int(l[0]), int(l[-1])+1, interval)]

l = [50.1234, 50.1221, 50.1200, 51.5022, 51.5021, 51.4999, 60.002, 60.0023, 60.0021]

group_list = interval_groups(l, 1)
print(group_list)

group_dict = {sum(group)/len(group):group for group in group_list if group}
print(group_dict)

Output:

[[50.1234, 50.1221, 50.12], [51.5022, 51.5021, 51.4999], [], [], [], [], [], [], [], [], [60.002, 60.0023, 60.0021]]
{50.121833333333335: [50.1234, 50.1221, 50.12], 51.5014: [51.5022, 51.5021, 51.4999], 60.002133333333326: [60.002, 60.0023, 60.0021]}

Here is a clearer version of interval_groups function:

def interval_groups(l, interval):
    """interval must be integer"""
    ret_list = []
    first_item_as_int = int(l[0])
    last_item_as_int = int(l[-1])
    for i in range(first_item_as_int, last_item_as_int + 1, interval):
        interval_list = [item for item in l if item >= i and item < (i + interval)]
        ret_list.append(interval_list)

    return ret_list

EDIT:

I deleted start_valueand you can modify function for list MZ objects as:

def interval_groups(list_of_MZ, interval):
    return [[item for item in list_of_MZ if item.mass >= i and item.mass < (i + interval)] for i in range(int(list_of_MZ[0].mass), int(list_of_MZ[-1].mass)+1, interval)]


问:
How do I segment a document using Tesseract then output the resulting bounding boxes and labels
I'm trying to get Tesseract to output a file with labelled bounding boxes that result from page segmentation (pre OCR). I know it must be capable of doing this 'out of the box' because of the results shown at the ICDAR competitions where contestants had to segment and various documents (academic paper here). Here's an example from that paper illustrating what I want to create:

I have built the latest version of tesseract using brew, brew install tesseract --HEAD, and have been trying to edit config files located in /usr/local/Cellar/tesseract/HEAD/share/tessdata/configs/ to output labelled boxes. The output received using hocr as the config, i.e.

```<code>tesseract infile.tiff outfile_stem -l eng -psm 1 hocr
</code>```

gives a bounding box for everything and has some labelling in class tags e.g.

```<code><p class='ocr_par' dir='ltr' id='par_5_82' title="bbox 2194 4490 3842 4589">
    <span class='ocr_line' id='line_5_142' ...
</code>```

but I can't visualise this. Is there a standard tool to visualize hOCR files, or is the facility to create an output file with bounding boxes built into Tesseract?

The current head version details:

```<code>tesseract 3.04.00
 leptonica-1.71
  libjpeg 8d : libpng 1.6.16 : libtiff 4.0.3 : zlib 1.2.5
</code>```

Edit

I'm really looking to achieve this using the command line tool (as in examples above). @nguyenq has pointed me to the API reference, unfortunately I have no c++ experience. If the only solution is to use the API, please can you provide a quick python example?

答:
With Tesseract 4.0.0, a command like tesseract source/dir/myimage.tiff target/directory/basefilename hocr will create a basefilename.hocr file with block-, paragraph-, line-, and word-level bounding boxes for the OCR'ed text.  Even the command without the hocr config creates a text file with newlines between block-level text, but the hocr format is more explicit.

More config options here:  https://github.com/tesseract-ocr/tesseract/tree/master/tessdata/configs

Body:
I'm trying to get Tesseract to output a file with labelled bounding boxes that result from page segmentation (pre OCR). I know it must be capable of doing this 'out of the box' because of the results shown at the ICDAR competitions where contestants had to segment and various documents (academic paper here). Here's an example from that paper illustrating what I want to create:

I have built the latest version of tesseract using brew, brew install tesseract --HEAD, and have been trying to edit config files located in /usr/local/Cellar/tesseract/HEAD/share/tessdata/configs/ to output labelled boxes. The output received using hocr as the config, i.e.

tesseract infile.tiff outfile_stem -l eng -psm 1 hocr

gives a bounding box for everything and has some labelling in class tags e.g.

    <span class='ocr_line' id='line_5_142' ...

but I can't visualise this. Is there a standard tool to visualize hOCR files, or is the facility to create an output file with bounding boxes built into Tesseract?

The current head version details:

tesseract 3.04.00
 leptonica-1.71
  libjpeg 8d : libpng 1.6.16 : libtiff 4.0.3 : zlib 1.2.5

Edit

I'm really looking to achieve this using the command line tool (as in examples above). @nguyenq has pointed me to the API reference, unfortunately I have no c++ experience. If the only solution is to use the API, please can you provide a quick python example?


答:
Your code that waits for Enter to be pressed "steals" that character from the input stream before Scanner gets to see it. Hence, the first '\n' gets consumed by System.in.read() line.

When you call scanner.hasNextLine() for a Scanner based on the console, the code blocks to see if end-user enters a line or terminates the stream. The second '\n' is needed for the hasNextLine method to return.

You can fix this by removing the call to System.in.read(), and calling getNextLine() to consume the input before next call:

```<code>public void read() {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Press Enter to continue");
    try {
        System.in.read();
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (scanner.hasNextLine()) {
        scanner.nextLine(); // Remove '\n' from the buffer
        this.win();
    }
}
</code>```

Title: Java scanner works from second time

Body:
Your code that waits for Enter to be pressed "steals" that character from the input stream before Scanner gets to see it. Hence, the first '\n' gets consumed by System.in.read() line.

When you call scanner.hasNextLine() for a Scanner based on the console, the code blocks to see if end-user enters a line or terminates the stream. The second '\n' is needed for the hasNextLine method to return.

You can fix this by removing the call to System.in.read(), and calling getNextLine() to consume the input before next call:

public void read() {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Press Enter to continue");
    try {
        System.in.read();
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (scanner.hasNextLine()) {
        scanner.nextLine(); // Remove '\n' from the buffer
        this.win();
    }
}


问:
Format / Suppress Scientific Notation from Pandas Aggregation Results
How can one modify the format for the output from a groupby operation in pandas that produces scientific notation for very large numbers?

I know how to do string formatting in python but I'm at a loss when it comes to applying it here.

```<code>df1.groupby('dept')['data1'].sum()

dept
value1       1.192433e+08
value2       1.293066e+08
value3       1.077142e+08
</code>```

This suppresses the scientific notation if I convert to string but now I'm just wondering how to string format and add decimals.

```<code>sum_sales_dept.astype(str)
</code>```

答:
If you would like to use the values, say as part of csvfile csv.writer, the numbers can be formatted before creating a list:</p>

```<code>df['label'].apply(lambda x: '%.17f' % x).values.tolist()
</code>```

Body:
How can one modify the format for the output from a groupby operation in pandas that produces scientific notation for very large numbers?

I know how to do string formatting in python but I'm at a loss when it comes to applying it here.

df1.groupby('dept')['data1'].sum()

dept
value1       1.192433e+08
value2       1.293066e+08
value3       1.077142e+08

This suppresses the scientific notation if I convert to string but now I'm just wondering how to string format and add decimals.

sum_sales_dept.astype(str)

Body:
If you would like to use the values, say as part of csvfile csv.writer, the numbers can be formatted before creating a list:

df['label'].apply(lambda x: '%.17f' % x).values.tolist()