问:
Dagger2 Compilation Issue in kotlin
I am trying to learn dependency injection using Dagger2. I have created few custom scopes and Qualifier. I have created an application component where I wanted to inject certain global dependencies and also I have created an Activity component which will return certain instances based upon activity context.

Now when I try to inject global instances in the Activity I am getting error as follows:

e:
  /home/arifur/source_code/me/myprojects/Learn/studio/Android/kotlin/FirebaseChat/app/build/tmp/kapt3/stubs/debug/com/example/arifur/firebasechatkotlin/dependecies/component/ActivityComponent.java:7:
  error: com.google.firebase.auth.FirebaseAuth cannot be provided
  without an @Provides- or @Produces-annotated method. e:

e:     public abstract void
  inject(@org.jetbrains.annotations.NotNull() e:

  ^ e:       com.google.firebase.auth.FirebaseAuth is injected at e:

  com.example.arifur.firebasechatkotlin.BaseActivity.firebaseAuth e:

  com.example.arifur.firebasechatkotlin.MainActivity is injected at e:

  com.example.arifur.firebasechatkotlin.dependecies.component.ActivityComponent.inject(p0)

w: warning: The following options were not recognized by any
  processor: '[kapt.kotlin.generated]' w:

e:
  /home/arifur/source_code/me/myprojects/Learn/studio/Android/kotlin/FirebaseChat/app/src/main/java/com/example/arifur/firebasechatkotlin/BaseActivity.kt:
  (29, 9): Unresolved reference: DaggerActivityComponent e:
  /home/arifur/source_code/me/myprojects/Learn/studio/Android/kotlin/FirebaseChat/app/src/main/java/com/example/arifur/firebasechatkotlin/FirebaseChatApp.kt:
  (20, 13): Unresolved reference: DaggerFirebaseComponent e:
  /home/arifur/source_code/me/myprojects/Learn/studio/Android/kotlin/FirebaseChat/app/src/main/java/com/example/arifur/firebasechatkotlin/MainActivity.kt:
  (1, 1): Some error(s) occurred while processing annotations. Please
  see the error messages above.

Qualifiers

ActivityContext.kt

```<code>@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class ActivityContext
</code>```

ApplicationContext.kt

```<code>@javax.inject.Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class ApplicationContext
</code>```

Scopes

ActivityScope.kt

```<code>@Scope
@Retention(AnnotationRetention.SOURCE)
annotation class ApplicationScope
</code>```

ApplicationScope.kt

```<code>@Scope
@Retention(AnnotationRetention.SOURCE)
annotation class ApplicationScope
</code>```

Components

ActivityComponent.kt Used in Injecting Activity class.

```<code>@ActivityScope
@Component(modules = arrayOf(ActivityModule::class), dependencies = arrayOf(FirebaseComponent::class))
interface ActivityComponent {
    fun inject(mainActivity: MainActivity)
}
</code>```

FirebaseComponent.kt Used in injecting Application class.

```<code>@ApplicationScope
@Component(modules = arrayOf(ApplicationModule::class, FirebaseAuthModule::class, NetworkModule::class))
interface FirebaseComponent {
    fun inject(app: FirebaseChatApp)
}
</code>```

Modules

ActivityModule.kt

```<code>@Module
class ActivityModule(val activity : Activity) {
    var mActivityRef : WeakReference<Activity> ;
    init {
        mActivityRef = WeakReference<Activity>(activity)
    }

    @Provides
    @ActivityScope
    @ActivityContext
    public fun getActivityContext() : Context? = mActivityRef.get()

    @Provides
    @ActivityScope
    @ActivityContext
    public fun getActivityInstance() : Activity? = mActivityRef.get();

    @Provides
    @ActivityScope
    public fun getGlideActivityInstance(@ActivityContext context : Context?) : Glide {
        Log.i("activityModule", "Returning activity glide")
        return Glide.get(context);
    }

}
</code>```

ApplicationModule.kt

```<code>@Module
class ApplicationModule(val app : FirebaseChatApp) {

    @ApplicationContext
    @ApplicationScope
    @Provides
    fun provideContext() : Context = app

    @ApplicationInstance
    @ApplicationScope
    @Provides
    fun provideApplication() : Application = app
}
</code>```

FirebaseAuthModule.kt

```<code>@Module
class FirebaseAuthModule {

    @Provides
    @ApplicationScope
    public fun getFirebaseAuth() : FirebaseAuth = FirebaseAuth.getInstance()
}
</code>```

NetworkModule.kt

```<code>@Module
class NetworkModule {

    @Provides
    @ApplicationScope
    public fun getGlideApplicationInstance(@ApplicationContext applicationContext: Context ) : Glide {
        return Glide.get(applicationContext);
    }
}
</code>```

FirebaseChatApp.kt An Application Class

```<code>class FirebaseChatApp : Application() {

        val firebaseComponent: FirebaseComponent by lazy {
            DaggerFirebaseComponent
                    .builder()
                    .applicationModule(ApplicationModule(this))
                    .build()
        }

    @Inject
    lateinit var firebaseAuth : FirebaseAuth

    @Inject
    lateinit var glide : Glide

    override fun onCreate() {
        super.onCreate()
        firebaseComponent.inject(this)
        Log.i("application", "APP->Firebase Auth = " + firebaseAuth)
        Log.i("application", "APP->Glide = " + glide)
    }

    public fun getApplicationComponent() : FirebaseComponent = firebaseComponent;
}
</code>```

BaseActivity.kt Super classes for all activities

```<code>public abstract class BaseActivity : AppCompatActivity(){
    @Inject
    @ActivityScope
    protected lateinit var glide : Glide

    @Inject
    @ApplicationScope
    protected lateinit var firebaseAuth : FirebaseAuth //ERROR HERE

    protected val activityComponent: ActivityComponent by lazy {
        DaggerActivityComponent
                .builder()
                .activityModule(ActivityModule(this))
                .firebaseComponent((this.application as FirebaseChatApp).getApplicationComponent())
                .build()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        injectComponent(activityComponent)
    }
     abstract fun injectComponent(activityComponent: ActivityComponent)
}
</code>```

MainActivity.kt Where Objects should get Injected.

```<code>class MainActivity : BaseActivity() {

    override fun injectComponent(activityComponent: ActivityComponent) {
        activityComponent.inject(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)
    }
}
</code>```

What should I do to resolve this error. And what is the correct way of using DI. Since I am new to it. I am getting little confused.

答:
The problem is that you are trying to use component dependencies, but you've skipped adding the provision methods that your subscoped component can inherit.</p>

```<code>@ApplicationScope
@Component(modules = arrayOf(ApplicationModule::class, FirebaseAuthModule::class, NetworkModule::class))
interface FirebaseComponent {
    fun firebaseAuth() : FirebaseAuth // <-- this is missing

    fun inject(app: FirebaseChatApp)
}
</code>```

Title: Dagger2 Compilation Issue in kotlin

Body:
I am trying to learn dependency injection using Dagger2. I have created few custom scopes and Qualifier. I have created an application component where I wanted to inject certain global dependencies and also I have created an Activity component which will return certain instances based upon activity context.

Now when I try to inject global instances in the Activity I am getting error as follows:

e:
  /home/arifur/source_code/me/myprojects/Learn/studio/Android/kotlin/FirebaseChat/app/build/tmp/kapt3/stubs/debug/com/example/arifur/firebasechatkotlin/dependecies/component/ActivityComponent.java:7:
  error: com.google.firebase.auth.FirebaseAuth cannot be provided
  without an @Provides- or @Produces-annotated method. e:

e:     public abstract void
  inject(@org.jetbrains.annotations.NotNull() e:

  ^ e:       com.google.firebase.auth.FirebaseAuth is injected at e:

  com.example.arifur.firebasechatkotlin.BaseActivity.firebaseAuth e:

  com.example.arifur.firebasechatkotlin.MainActivity is injected at e:

  com.example.arifur.firebasechatkotlin.dependecies.component.ActivityComponent.inject(p0)

w: warning: The following options were not recognized by any
  processor: '[kapt.kotlin.generated]' w:

e:
  /home/arifur/source_code/me/myprojects/Learn/studio/Android/kotlin/FirebaseChat/app/src/main/java/com/example/arifur/firebasechatkotlin/BaseActivity.kt:
  (29, 9): Unresolved reference: DaggerActivityComponent e:
  /home/arifur/source_code/me/myprojects/Learn/studio/Android/kotlin/FirebaseChat/app/src/main/java/com/example/arifur/firebasechatkotlin/FirebaseChatApp.kt:
  (20, 13): Unresolved reference: DaggerFirebaseComponent e:
  /home/arifur/source_code/me/myprojects/Learn/studio/Android/kotlin/FirebaseChat/app/src/main/java/com/example/arifur/firebasechatkotlin/MainActivity.kt:
  (1, 1): Some error(s) occurred while processing annotations. Please
  see the error messages above.

Qualifiers

ActivityContext.kt

@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class ActivityContext

ApplicationContext.kt

@javax.inject.Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class ApplicationContext

Scopes

ActivityScope.kt

@Scope
@Retention(AnnotationRetention.SOURCE)
annotation class ApplicationScope

ApplicationScope.kt

@Scope
@Retention(AnnotationRetention.SOURCE)
annotation class ApplicationScope

Components

ActivityComponent.kt Used in Injecting Activity class.

@ActivityScope
@Component(modules = arrayOf(ActivityModule::class), dependencies = arrayOf(FirebaseComponent::class))
interface ActivityComponent {
    fun inject(mainActivity: MainActivity)
}

FirebaseComponent.kt Used in injecting Application class.

@ApplicationScope
@Component(modules = arrayOf(ApplicationModule::class, FirebaseAuthModule::class, NetworkModule::class))
interface FirebaseComponent {
    fun inject(app: FirebaseChatApp)
}

Modules

ActivityModule.kt

@Module
class ActivityModule(val activity : Activity) {
    var mActivityRef : WeakReference<Activity> ;
    init {
        mActivityRef = WeakReference<Activity>(activity)
    }

    @Provides
    @ActivityScope
    @ActivityContext
    public fun getActivityContext() : Context? = mActivityRef.get()

    @Provides
    @ActivityScope
    @ActivityContext
    public fun getActivityInstance() : Activity? = mActivityRef.get();

    @Provides
    @ActivityScope
    public fun getGlideActivityInstance(@ActivityContext context : Context?) : Glide {
        Log.i("activityModule", "Returning activity glide")
        return Glide.get(context);
    }

}

ApplicationModule.kt

@Module
class ApplicationModule(val app : FirebaseChatApp) {

    @ApplicationContext
    @ApplicationScope
    @Provides
    fun provideContext() : Context = app

    @ApplicationInstance
    @ApplicationScope
    @Provides
    fun provideApplication() : Application = app
}

FirebaseAuthModule.kt

@Module
class FirebaseAuthModule {

    @Provides
    @ApplicationScope
    public fun getFirebaseAuth() : FirebaseAuth = FirebaseAuth.getInstance()
}

NetworkModule.kt

@Module
class NetworkModule {

    @Provides
    @ApplicationScope
    public fun getGlideApplicationInstance(@ApplicationContext applicationContext: Context ) : Glide {
        return Glide.get(applicationContext);
    }
}

FirebaseChatApp.kt An Application Class

class FirebaseChatApp : Application() {

        val firebaseComponent: FirebaseComponent by lazy {
            DaggerFirebaseComponent
                    .builder()
                    .applicationModule(ApplicationModule(this))
                    .build()
        }

    @Inject
    lateinit var firebaseAuth : FirebaseAuth

    @Inject
    lateinit var glide : Glide

    override fun onCreate() {
        super.onCreate()
        firebaseComponent.inject(this)
        Log.i("application", "APP->Firebase Auth = " + firebaseAuth)
        Log.i("application", "APP->Glide = " + glide)
    }

    public fun getApplicationComponent() : FirebaseComponent = firebaseComponent;
}

BaseActivity.kt Super classes for all activities

public abstract class BaseActivity : AppCompatActivity(){
    @Inject
    @ActivityScope
    protected lateinit var glide : Glide

    @Inject
    @ApplicationScope
    protected lateinit var firebaseAuth : FirebaseAuth //ERROR HERE

    protected val activityComponent: ActivityComponent by lazy {
        DaggerActivityComponent
                .builder()
                .activityModule(ActivityModule(this))
                .firebaseComponent((this.application as FirebaseChatApp).getApplicationComponent())
                .build()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        injectComponent(activityComponent)
    }
     abstract fun injectComponent(activityComponent: ActivityComponent)
}

MainActivity.kt Where Objects should get Injected.

class MainActivity : BaseActivity() {

    override fun injectComponent(activityComponent: ActivityComponent) {
        activityComponent.inject(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)
    }
}

What should I do to resolve this error. And what is the correct way of using DI. Since I am new to it. I am getting little confused.

Body:
The problem is that you are trying to use component dependencies, but you've skipped adding the provision methods that your subscoped component can inherit.

@ApplicationScope
@Component(modules = arrayOf(ApplicationModule::class, FirebaseAuthModule::class, NetworkModule::class))
interface FirebaseComponent {
    fun firebaseAuth() : FirebaseAuth // <-- this is missing

    fun inject(app: FirebaseChatApp)
}


来源: stackexchange

问:
Module not found: Error: Can't resolve
I upgraded the angular(2.1.2)and angular-cli version to latest, and I get the following error for each component I have:

```<code>ERROR in ./src/app/members/view-news/view-news.component.ts
Module not found: Error: Can't resolve 'view-news.component.css' in 'c:\xampp\htdocs\myapp\src\app\members\view-news'
 @ ./src/app/members/view-news/view-news.component.ts 74:21-55
 @ ./src/app/app.module.ts
 @ ./src/app/index.ts
 @ ./src/main.ts
 @ multi main
</code>```

Although the file view-news.component.css exists in the same folder of the view-news.component.ts and worked in previous version. What's wrong?

答: Make sure you change the comments tag from <dom-element> to 'test.html' if you have it surrounding with test.html it will fail.

ContentLicense: CC BY-SA 3.0

Title: Module not found: Error: Can't resolve

Body:
I upgraded the angular(2.1.2)and angular-cli version to latest, and I get the following error for each component I have:

ERROR in ./src/app/members/view-news/view-news.component.ts
Module not found: Error: Can't resolve 'view-news.component.css' in 'c:\xampp\htdocs\myapp\src\app\members\view-news'
 @ ./src/app/members/view-news/view-news.component.ts 74:21-55
 @ ./src/app/app.module.ts
 @ ./src/app/index.ts
 @ ./src/main.ts
 @ multi main

Although the file view-news.component.css exists in the same folder of the view-news.component.ts and worked in previous version. What's wrong?


问:
Does D-Bus guarantee message delivery?
I would like to know if D-Bus guarantees message delivery when used directly through the low level C API call dbus_connection_send_with_reply?

More specifically, does it guarantee that a single instance of a messages is delivered to the destination or if it fails that an error reply is returned?

I understand that the receiving application may not issue a reply to a method in which case D-Bus will return an error after a timeout. However, are all other potential failures covered by the D-Bus protocol?

答:
This is dependent on the underlying transport layer, but unless you got it working on something other than unix domain sockets or TCP (if you got to ask, you don't), it is safe to assume you will receive a reply.

Sources:

https://dbus.freedesktop.org/doc/dbus-tutorial.html#addresses

https://lists.freedesktop.org/archives/dbus/2007-June/008094.html

Title: Does D-Bus guarantee message delivery?


问:
creating over 20 unique legend colors using matplotlib
I am plotting 20 different lines on a single plot using matplotlib. I use a for loop for plotting and label every line with its key and then use the legend function

```<code>for key in dict.keys():
    plot(x,dict[key], label = key)
graph.legend()
</code>```

But using this way, the graph repeats a lot of colors in the legend. Is there any way to ensure a unique color is assigned to each line using matplotlib and over 20 lines?

thanks

答:
I had a plot with 12 lines, and I found it hard to distinguish lines with similar colours when I tried Yann's technique. My lines also appeared in pairs, so I used the same colour for the two lines in each pair, and used two different line widths. You could also vary the line style to get more combinations.

You could use set_prop_cycle(), but I just modified the line objects after calling plot().

Here is Yann's example with three different line widths:

```<code>import matplotlib.pyplot as plt
import numpy as np

NUM_COLORS = 20

cm = plt.get_cmap('gist_rainbow')
fig = plt.figure()
ax = fig.add_subplot(111)
for i in range(NUM_COLORS):
    lines = ax.plot(np.arange(10)*(i+1))
    lines[0].set_color(cm(i//3*3.0/NUM_COLORS))
    lines[0].set_linewidth(i%3 + 1)

fig.savefig('moreColors.png')
plt.show()
</code>```

Here's the same example with different line styles. Of course you could combine the two if you wanted.

```<code>import matplotlib.pyplot as plt
import numpy as np

NUM_COLORS = 20
LINE_STYLES = ['solid', 'dashed', 'dashdot', 'dotted']
NUM_STYLES = len(LINE_STYLES)

cm = plt.get_cmap('gist_rainbow')
fig = plt.figure()
ax = fig.add_subplot(111)
for i in range(NUM_COLORS):
    lines = ax.plot(np.arange(10)*(i+1))
    lines[0].set_color(cm(i//NUM_STYLES*float(NUM_STYLES)/NUM_COLORS))
    lines[0].set_linestyle(LINE_STYLES[i%NUM_STYLES])

fig.savefig('moreColors.png')
plt.show()
</code>```

Body:
I am plotting 20 different lines on a single plot using matplotlib. I use a for loop for plotting and label every line with its key and then use the legend function

for key in dict.keys():
    plot(x,dict[key], label = key)
graph.legend()

But using this way, the graph repeats a lot of colors in the legend. Is there any way to ensure a unique color is assigned to each line using matplotlib and over 20 lines?

thanks

Body:
I had a plot with 12 lines, and I found it hard to distinguish lines with similar colours when I tried Yann's technique. My lines also appeared in pairs, so I used the same colour for the two lines in each pair, and used two different line widths. You could also vary the line style to get more combinations.

You could use set_prop_cycle(), but I just modified the line objects after calling plot().

Here is Yann's example with three different line widths:

import matplotlib.pyplot as plt
import numpy as np

NUM_COLORS = 20

cm = plt.get_cmap('gist_rainbow')
fig = plt.figure()
ax = fig.add_subplot(111)
for i in range(NUM_COLORS):
    lines = ax.plot(np.arange(10)*(i+1))
    lines[0].set_color(cm(i//3*3.0/NUM_COLORS))
    lines[0].set_linewidth(i%3 + 1)

fig.savefig('moreColors.png')
plt.show()

Here's the same example with different line styles. Of course you could combine the two if you wanted.

import matplotlib.pyplot as plt
import numpy as np

NUM_COLORS = 20
LINE_STYLES = ['solid', 'dashed', 'dashdot', 'dotted']
NUM_STYLES = len(LINE_STYLES)

cm = plt.get_cmap('gist_rainbow')
fig = plt.figure()
ax = fig.add_subplot(111)
for i in range(NUM_COLORS):
    lines = ax.plot(np.arange(10)*(i+1))
    lines[0].set_color(cm(i//NUM_STYLES*float(NUM_STYLES)/NUM_COLORS))
    lines[0].set_linestyle(LINE_STYLES[i%NUM_STYLES])

fig.savefig('moreColors.png')
plt.show()


问:
datamaps.js - How to smoothly transition between bubble sizes?
I am using datamaps' bubbles to show data that changes slightly from year to year:

http://jsbin.com/goqeve/edit?html,output

(Click between the '1990' and '2000' buttons on the bottom)

When I replace the bubbles with map.bubbles([...]), the default animation is for new bubbles to grow from the center, which obscures the small changes in size. How can I get the bubbles to transition smoothly (i.e. grow or shrink) between sizes instead of replacing them?

答:
Suppose you have your bubble data in a list called Nodes.

When you transition from 1990 to 2000 (or vice-versa), you can update the radii of the data in Nodes and then redraw them by calling map.bubbles(Nodes). I tried it and it smoothly transitioned into the new radius and not redrawing them.


问:
How do get a timestamp on an ASP.NET MVC App
On web apps,  you commonly see something like "Last Logged In: 3 hours 42 minutes ago".   What is the best way to go about doing this.?  Use strings or Dates?  Also,  i'm bringing that timestamp back into a Kendo MVC Grid.  The column looks as such.

```<code>columns.Bound(c => c.LastStatusDateDiff).Title("Updated");
</code>```

My Linq code looks as such

```<code>select new ATSReDto
                {
                    CreatedDate = atsr.CreatedDt,
                    Desciption = atsr.Description,
                    LastStatusDateDiff = laststatus.CreatedDt - DateTime.Now
// get date difference between now "DateTime.Now" and
// date/time pulled from SQL Server to display in Grid
                };
</code>```

Any suggestions greatly appreciated

答:
I am not familiar with Kendo, but jQuery offers a plugin called TimeAgo for this:

```<code>jQuery(document).ready(function() {
    jQuery("time.timeago").timeago();
});
</code>```

Docs: http://timeago.yarp.com/ Plugin: https://plugins.jquery.com/timeago/

Edit

Apparently, you can markup your razor controller using Kendo like this:

```<code><abbr class="timeago" title="@Model.LastActivityDateString">@Model.LastActivityDateString</abbr>
</code>```

After setting it in your model:

```<code>LastActivityDateString=DateTime.UtcNow.ToString("o");
</code>```

Note: You are just returning the date of the event not getting the difference as your code shows.

And your would initialize with Javascript like this:

```<code> jQuery(document).ready(function() {
    jQuery(".timeago").timeago();
});
</code>```

Body:
On web apps,  you commonly see something like "Last Logged In: 3 hours 42 minutes ago".   What is the best way to go about doing this.?  Use strings or Dates?  Also,  i'm bringing that timestamp back into a Kendo MVC Grid.  The column looks as such.

columns.Bound(c => c.LastStatusDateDiff).Title("Updated");

My Linq code looks as such

select new ATSReDto
                {
                    CreatedDate = atsr.CreatedDt,
                    Desciption = atsr.Description,
                    LastStatusDateDiff = laststatus.CreatedDt - DateTime.Now
// get date difference between now "DateTime.Now" and
// date/time pulled from SQL Server to display in Grid
                };

Any suggestions greatly appreciated

Body:
I am not familiar with Kendo, but jQuery offers a plugin called TimeAgo for this:

jQuery(document).ready(function() {
    jQuery("time.timeago").timeago();
});

Docs: http://timeago.yarp.com/ Plugin: https://plugins.jquery.com/timeago/

Edit

Apparently, you can markup your razor controller using Kendo like this:

<abbr class="timeago" title="@Model.LastActivityDateString">@Model.LastActivityDateString</abbr>

After setting it in your model:

LastActivityDateString=DateTime.UtcNow.ToString("o");

Note: You are just returning the date of the event not getting the difference as your code shows.

And your would initialize with Javascript like this:

 jQuery(document).ready(function() {
    jQuery(".timeago").timeago();
});


问:
What the typical viewport size on a 1024x768 screen?
I am designing a web application, and I wish to know the largest size (x and y) that I can design for.

As of January 2008, about half of users are using 1024x278 screens, and probably less than 10% are using smaller screens. (Phone and palmtop users are an exception here.) So we are designing for minimum screen size of 1024x768.

However, that's the screen size, and when we are laying out our content we need to know the viewport size. There is evidence that most users have the browser maximized, but one still must subtract out space for OS decorations and browser chrome. People customize their chrome, so there is no single "right" answer; I am going for a reasonable bound that will accommodate the majority of users.

I see plenty of designers who say that they use a width of 960 pixels because it has many factors and can be divided up evenly -- but before deciding on this I want to know the maximum size that I can get away with, then I might choose to use somewhat less. I have seen max widths of 960, 974 or even 990 quoted... my own experiments seem to show a width of 1000 works OK.

Heights are even more difficult to come by: I find I can fit a vertical viewport height of 595 pixels works on the browsers that I've tried, with typical default OS and chrome settings. But I haven't tried very many, and I would rather see a more authoritative source. Surely someone else has done this research and done it better than me.

So my real question is this: What is the largest viewport size I can design for and expect it to fit without scrollbars for 80-90% of all users?

答:
I have Firefox open with a size (including chrome) of 1024x1000. I don't browse full-screen.

My chrome includes the menu bar, the navigation toolbar (with small icons), the bookmark toolbar, the tab bar, a right-side scroll bar and the status bar at the bottom.

My actual view port is exactly 1000x843.

OwnerDisplayName: mcherm

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: sjstrutt


问:
org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class [Ljava.lang.String;
I want to run the following command to create a user with MongoDB Java Driver,

```<code>    client = new MongoClient(mongoClientURI);
    MongoDatabase database = client.getDatabase("db_1");

    Document createUserCommand = new Document();
    createUserCommand.put("createUser", "abc");
    createUserCommand.put("pwd", "abc");
    createUserCommand.put("roles", new String[]{"userAdmin", "read", "readWrite", "dbAdmin", "dbOwner"});         database.runCommand(createUserCommand);
</code>```

But following exception occurred:

```<code>Exception in thread "main" org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class [Ljava.lang.String;.
    at org.bson.codecs.configuration.CodecCache.getOrThrow(CodecCache.java:46)
    at org.bson.codecs.configuration.ProvidersCodecRegistry.get(ProvidersCodecRegistry.java:63)
    at org.bson.codecs.configuration.ChildCodecRegistry.get(ChildCodecRegistry.java:51)
    at org.bson.codecs.DocumentCodec.writeValue(DocumentCodec.java:174)
    at org.bson.codecs.DocumentCodec.writeMap(DocumentCodec.java:189)
    at org.bson.codecs.DocumentCodec.encode(DocumentCodec.java:131)
    at org.bson.codecs.DocumentCodec.encode(DocumentCodec.java:45)
    at org.bson.codecs.BsonDocumentWrapperCodec.encode(BsonDocumentWrapperCodec.java:63)
</code>```

Looks the roles field which is an array leads to this problem, can some take a look at this problem? Thanks

答:
```<code>createUserCommand.put("roles", new String[]{"userAdmin", "read", "readWrite", "dbAdmin", "dbOwner"});
 database.runCommand(createUserCommand);
</code>```

should be

```<code>List<String> roles = new ArrayList<String>();
roles.add("userAdmin); ... createUserCommand.put("roles", roles); database.runCommand(createUserCommand);
</code>```

Looks like it support List, not Array, which is really ugl

Body:
I want to run the following command to create a user with MongoDB Java Driver,

    client = new MongoClient(mongoClientURI);
    MongoDatabase database = client.getDatabase("db_1");

    Document createUserCommand = new Document();
    createUserCommand.put("createUser", "abc");
    createUserCommand.put("pwd", "abc");
    createUserCommand.put("roles", new String[]{"userAdmin", "read", "readWrite", "dbAdmin", "dbOwner"});         database.runCommand(createUserCommand);

But following exception occurred:

Exception in thread "main" org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class [Ljava.lang.String;.
    at org.bson.codecs.configuration.CodecCache.getOrThrow(CodecCache.java:46)
    at org.bson.codecs.configuration.ProvidersCodecRegistry.get(ProvidersCodecRegistry.java:63)
    at org.bson.codecs.configuration.ChildCodecRegistry.get(ChildCodecRegistry.java:51)
    at org.bson.codecs.DocumentCodec.writeValue(DocumentCodec.java:174)
    at org.bson.codecs.DocumentCodec.writeMap(DocumentCodec.java:189)
    at org.bson.codecs.DocumentCodec.encode(DocumentCodec.java:131)
    at org.bson.codecs.DocumentCodec.encode(DocumentCodec.java:45)
    at org.bson.codecs.BsonDocumentWrapperCodec.encode(BsonDocumentWrapperCodec.java:63)

Looks the roles field which is an array leads to this problem, can some take a look at this problem? Thanks

Body:
createUserCommand.put("roles", new String[]{"userAdmin", "read", "readWrite", "dbAdmin", "dbOwner"});
 database.runCommand(createUserCommand);

should be

List<String> roles = new ArrayList<String>();
roles.add("userAdmin); ... createUserCommand.put("roles", roles); database.runCommand(createUserCommand);

Looks like it support List, not Array, which is really ugl


问:
Built an array with jquery events. How to trigger them?
I am capturing some events (using Jquery.Event) inside an iframe, in order to feed an array. Basically I am capturing events like:

```<code>var events=[]
$('#ifrm').contents().on('change click focus keypress select submit', function(evt){
  events.push($.Event(evt))
})
</code>```

Now, I am trying to trigger (replay) all events in event array like:

```<code>$.each(events, function(i,evt){
   $('#ifrm').contents().trigger(evt)
})
</code>```

Is it supposed to work or I am missing something?

答:
You have an error.. you forgot an s.

```<code>events.push($.Event(evt))
</code>```

Also, see this link for more  help.

Body:
I am capturing some events (using Jquery.Event) inside an iframe, in order to feed an array. Basically I am capturing events like:

var events=[]
$('#ifrm').contents().on('change click focus keypress select submit', function(evt){
  events.push($.Event(evt))
})

Now, I am trying to trigger (replay) all events in event array like:

$.each(events, function(i,evt){
   $('#ifrm').contents().trigger(evt)
})

Is it supposed to work or I am missing something?

Body:
You have an error.. you forgot an s.

events.push($.Event(evt))

Also, see this link for more  help.


问:
Javascript - comparision projects using object keys
I found the method to get all properties of object:

```<code>for (const key of Object.keys(obj)) {
    const val = obj[key];
    // use val
}
</code>```

But how can I compare 2 objects if these objects have a boolean field for each field to mark that object is different to the comparision?

```<code>export class MyObject {
   fieldOne: number;
   fieldOneChanged: boolean;
   fieldTwo: number;
   fieldTwoChanged: boolean;
   // and many more fields
}
</code>```

And I compare it the following:

```<code>if (myObj1.fieldOne != myObj2.fieldOne) {
    myObj2.fieldOneChanged = true;
}
</code>```

And now I wonder how can I user Object.keys() to reduction comparision and make it more generic.

答:
Use the key variable to compare the properties of the two objects.

```<code>for (const key of Object.keys(myObj1)) {
    if (myObj1[key] != myObj2[key]) {
        myObj2[key + "Changed"] = true;
    }
}
</code>```

Body:
I found the method to get all properties of object:

for (const key of Object.keys(obj)) {
    const val = obj[key];
    // use val
}

But how can I compare 2 objects if these objects have a boolean field for each field to mark that object is different to the comparision?

export class MyObject {
   fieldOne: number;
   fieldOneChanged: boolean;
   fieldTwo: number;
   fieldTwoChanged: boolean;
   // and many more fields
}

And I compare it the following:

if (myObj1.fieldOne != myObj2.fieldOne) {
    myObj2.fieldOneChanged = true;
}

And now I wonder how can I user Object.keys() to reduction comparision and make it more generic.

Body:
Use the key variable to compare the properties of the two objects.

for (const key of Object.keys(myObj1)) {
    if (myObj1[key] != myObj2[key]) {
        myObj2[key + "Changed"] = true;
    }
}


问:
Django doesn't render the requested view
people. I'm a beginner Django developer so sorry if it's a basic question.

I have a webpage that shows a list of movies and each movie has a details view, but for some reason, the details view is never rendered.

```<code>#views.py

def index(request):
    latest_movies = Movie.objects.order_by('-movie_id')[:5]

    template = loader.get_template('ytsmirror/index.html')
    context = {
        'latest_movies' : latest_movies,
    }

    return HttpResponse(template.render(context, request))

def detail(request, movie_id):

    movie = Movie.objects.get(movie_id=movie_id)
    template = loader.get_template('ytsmirror/details.html')

    context = {
        'movie' : movie,
        'plot': 'Lorem impsum',
    }

    return HttpResponse(template.render(context, request))
</code>```

And my urls.py

```<code>#urls.py

from django.conf.urls import url

from . import views

app_name = 'ytsmirror'
urlpatterns = [
  url(r'$', views.index, name='index'),
  url(r'^(?P<movie_id>\d{4})$', views.detail, name='detail'),
]
</code>```

When I try to reach /ytsmirror/4200/ for example, I don't get any error and Django apparently reaches the correct URL pattern but doesn't render the details view, it stays on the index view, without any change.

What am I doing wrong? Thanks.

答:
url(r'$', views.index, name='index') matches the end of the string, so basically it will match any url, that's why your code isn't working. You need to replace url(r'$', views.index, name='index') with url(r'^$', views.index, name='index') so that it will match only empty url

^ asserts position at start of the string

$ asserts position at the end of the string, or before the line terminator right at the end of the string (if any)

Body:
people. I'm a beginner Django developer so sorry if it's a basic question.

I have a webpage that shows a list of movies and each movie has a details view, but for some reason, the details view is never rendered.

#views.py

def index(request):
    latest_movies = Movie.objects.order_by('-movie_id')[:5]

    template = loader.get_template('ytsmirror/index.html')
    context = {
        'latest_movies' : latest_movies,
    }

    return HttpResponse(template.render(context, request))

def detail(request, movie_id):

    movie = Movie.objects.get(movie_id=movie_id)
    template = loader.get_template('ytsmirror/details.html')

    context = {
        'movie' : movie,
        'plot': 'Lorem impsum',
    }

    return HttpResponse(template.render(context, request))

And my urls.py

#urls.py

from django.conf.urls import url

from . import views

app_name = 'ytsmirror'
urlpatterns = [
  url(r'$', views.index, name='index'),
  url(r'^(?P<movie_id>\d{4})$', views.detail, name='detail'),
]

When I try to reach /ytsmirror/4200/ for example, I don't get any error and Django apparently reaches the correct URL pattern but doesn't render the details view, it stays on the index view, without any change.

What am I doing wrong? Thanks.


问:
Does the length of the text to be hashed affect the probability of a collision?
I want to make unique code with sha1 with unique salt (definitely unique because i use id from table). I need unique code with 7 character but i can't use id from my table because it's more than 7 character. So i think it's better to use sha1 and take first 7 character of hashed text as my unique code. Does the length of the text to be hashed affect the probability of a collision?

for example :

```<code>textA = "myId:12345678"
textB = "myId:12345678, myId2:87654321"
</code>```

Is it better to use long short text (e.g textA) or text (e.g textB)? Or does the text length have no effect?

答:
Hashing your unique IDs is a bad idea. Don't do it.

If your IDs consist of 7 hex digits, that gives you 268,435,456 unique values to play with. If you hash these values and truncate the results to 7 hex digits, then the probability of a collision rises very quickly (1% probability after 2,322 inputs, 50% after 19,290 inputs, 99% after 35,159 inputs).

If your aim is to disguise these ID values so that an adversary is unable to figure out what the actual sequential values are, then use format-preserving encryption instead.

Edit: If you need something secure, you could try implementing a Feistel network using an encryption function like AES as the round function. (AES is overkill, perhaps, but this could be implemented in a few lines of code in most languages based on existing primitives.) If you just want to obfuscate the IDs, you could use something simpler like this:

def obfuscate_id(id, key):
    # Transforms id using a 28-bit key
    a = 81883721   # (random prime congruent to 1 mod 4)
    c = 2791751    # (any odd number will do)
    m = 2**28      # (modulus for 7-digit hex values)
    return ((id ^ key) * a + c) % m
```

Body:
I want to make unique code with sha1 with unique salt (definitely unique because i use id from table). I need unique code with 7 character but i can't use id from my table because it's more than 7 character. So i think it's better to use sha1 and take first 7 character of hashed text as my unique code. Does the length of the text to be hashed affect the probability of a collision?

for example :

textA = "myId:12345678"
textB = "myId:12345678, myId2:87654321"

Is it better to use long short text (e.g textA) or text (e.g textB)? Or does the text length have no effect?


问:
Automatic code testing in c upon execution
each source file has a function:

```<code>unsigned char test(){
    //return true if tests succceed false otherwise
}
</code>```

Everytime the sourcefile gets recompiled I want the test function of that file to be run on execution of the executable and if the tests return false to halt. However, I want only code whose test code hasnt been run since build.

I was thinking that I could use the makefile system to help with this problem since makefiles will only recompile changed code which is exactly what i want. Therefore, I was thinking of adding something to the command line arguments.  I saw an example in which they used echo and date to add a time last modified. The code would write the time last modified to a save file on a successful execution of the test code with which it will compare to the next time.

Is there a better way? One that doesnt rely on make? At the least is there a way without relying on spefic unix commands? Lastly, even if that isnt possible, what would the command line to do the addition to the file look like.

答:
Yes, you could make a file.t target dependant on the file.c.

file.t would get generated based on the successful completion of the test.

It'll be easier if you call your test function "main" and wrap it in #ifdef's like this:

```<code>#ifdef TEST
int main() {
    if (test_something() == 1)
        return 0;
    else
        return 1;
}
#endif
</code>```

Of course, you can do other trickier things if you want.

An example Makefile (using GNU Make syntax)

```<code>all: foo.t

%.t: %.c
    gcc -DTEST $< -o $@.tmp
    if ./$@.tmp ; then echo "1" > $@; rm $@.tmp ; fi
</code>```

However!  You'll probably be better off adopting something like CUtest (http://cutest.sourceforge.net/).

Body:
each source file has a function:

unsigned char test(){
    //return true if tests succceed false otherwise
}

Everytime the sourcefile gets recompiled I want the test function of that file to be run on execution of the executable and if the tests return false to halt. However, I want only code whose test code hasnt been run since build.

I was thinking that I could use the makefile system to help with this problem since makefiles will only recompile changed code which is exactly what i want. Therefore, I was thinking of adding something to the command line arguments.  I saw an example in which they used echo and date to add a time last modified. The code would write the time last modified to a save file on a successful execution of the test code with which it will compare to the next time.

Is there a better way? One that doesnt rely on make? At the least is there a way without relying on spefic unix commands? Lastly, even if that isnt possible, what would the command line to do the addition to the file look like.

Body:
Yes, you could make a file.t target dependant on the file.c.

file.t would get generated based on the successful completion of the test.

It'll be easier if you call your test function "main" and wrap it in #ifdef's like this:

#ifdef TEST
int main() {
    if (test_something() == 1)
        return 0;
    else
        return 1;
}
#endif

Of course, you can do other trickier things if you want.

An example Makefile (using GNU Make syntax)

all: foo.t

%.t: %.c
    gcc -DTEST $< -o $@.tmp
    if ./$@.tmp ; then echo "1" > $@; rm $@.tmp ; fi

However!  You'll probably be better off adopting something like CUtest (http://cutest.sourceforge.net/).


问:
matplotlib custom legend with hatching
I can seem to figure out how to pass the handles and labels from matplotlib.patches.Patch to the legend.

```<code>import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

a_val = 0.6
colors = ['#EA5739','#FEFFBE','#4BB05C']

circ1 = mpatches.Patch( facecolor=colors[0],alpha=a_val,hatch=['\\\\'],label='Label1')
circ2= mpatches.Patch( facecolor=colors[1],alpha=a_val,hatch='o',label='Label2')
circ3 = mpatches.Patch(facecolor=colors[2],alpha=a_val,hatch='+',label='Label3')

fig,(ax) = plt.subplots()

ax.legend(handles = [circ1,circ2,circ3],loc=2)
plt.tight_layout()
</code>```

Why is the legend blank in the above example?

答:
Either I can't reproduce your issue, or you're missing a huge error. When I run your code above, I get an error about a list not being hashable, which seems to originate in the first Patch call's hatch=['\\\\'] kwarg. Removing the list syntax (and using a raw string with 4 backslashes for extra effect) seems to work for me on matplotlib 2.0.2:

```<code>import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

a_val = 0.6
colors = ['#EA5739','#FEFFBE','#4BB05C']

circ1 = mpatches.Patch( facecolor=colors[0],alpha=a_val,hatch=r'\\\\',label='Label1')
circ2= mpatches.Patch( facecolor=colors[1],alpha=a_val,hatch='o',label='Label2')
circ3 = mpatches.Patch(facecolor=colors[2],alpha=a_val,hatch='+',label='Label3')

fig,(ax) = plt.subplots()

ax.legend(handles = [circ1,circ2,circ3],loc=2)
plt.tight_layout()
</code>```

Is this what you're seeing?

Title: matplotlib custom legend with hatching

Body:
I can seem to figure out how to pass the handles and labels from matplotlib.patches.Patch to the legend.

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

a_val = 0.6
colors = ['#EA5739','#FEFFBE','#4BB05C']

circ1 = mpatches.Patch( facecolor=colors[0],alpha=a_val,hatch=['\\\\'],label='Label1')
circ2= mpatches.Patch( facecolor=colors[1],alpha=a_val,hatch='o',label='Label2')
circ3 = mpatches.Patch(facecolor=colors[2],alpha=a_val,hatch='+',label='Label3')

fig,(ax) = plt.subplots()

ax.legend(handles = [circ1,circ2,circ3],loc=2)
plt.tight_layout()

Why is the legend blank in the above example?

Body:
Either I can't reproduce your issue, or you're missing a huge error. When I run your code above, I get an error about a list not being hashable, which seems to originate in the first Patch call's hatch=['\\\\'] kwarg. Removing the list syntax (and using a raw string with 4 backslashes for extra effect) seems to work for me on matplotlib 2.0.2:

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

a_val = 0.6
colors = ['#EA5739','#FEFFBE','#4BB05C']

circ1 = mpatches.Patch( facecolor=colors[0],alpha=a_val,hatch=r'\\\\',label='Label1')
circ2= mpatches.Patch( facecolor=colors[1],alpha=a_val,hatch='o',label='Label2')
circ3 = mpatches.Patch(facecolor=colors[2],alpha=a_val,hatch='+',label='Label3')

fig,(ax) = plt.subplots()

ax.legend(handles = [circ1,circ2,circ3],loc=2)
plt.tight_layout()

Is this what you're seeing?


问:
Excel Equivalent of SQL query "SELECT A.one, B.two FROM A INNER JOIN B ON A.three = B.three"
How do you do SQL "select join on" in excel?
Say I want col one from table A, col two from table B and they both have col three.

I would do:

```<code>SELECT A.one, B.two
FROM A
INNER JOIN B ON
A.three = B.three
</code>```

But instead of tables I have a few tabs in a Excel sheet. How do I do the equivalent of above query in Excel?

答:
You can use VBA and ADO to query the worksheets directly with SQL. Just add the following code to a Sub in a VBA module. The code is mainly boilerplate except for the rs.Open line and the With Worksheets line which you should modify to suit your particular scenario.

' Set up connection
Dim cn As Object
Set cn = CreateObject("ADODB.Connection")

' Connection string for Excel 2007 onwards .xlsm files
With cn
   .Provider = "Microsoft.ACE.OLEDB.12.0"
   .ConnectionString = "Data Source=" & ThisWorkbook.FullName & ";" & _
        "Extended Properties=""Excel 12.0 Macro;IMEX=1"";"
    .Open
End With

' Connection string for Excel 97-2003 .xls files
' It should also work with Excel 2007 onwards worksheets
' as long as they have less than 65536 rows
'With cn
'    .Provider = "Microsoft.Jet.OLEDB.4.0"
'    .ConnectionString = "Data Source=" & ThisWorkbook.FullName & ";" & _
'        "Extended Properties=""Excel 8.0;IMEX=1"";"
'    .Open
'End With

' Create and run the query
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")

' Join the two worksheets - assumed that these are named "Sheet1"
' and "Sheet2", the columns are named "one", "two" and "three"
' and that the results should be output to "Sheet3"
rs.Open "SELECT [Sheet1$].[one], [Sheet2$].[two] " & _
    "FROM [Sheet1$] INNER JOIN [Sheet2$] " & _
    "ON [Sheet1$].[three] = [Sheet2$].[three];", cn

' Output the field names and the results
Dim fld As Object
Dim i As Integer

' Change the worksheet to whichever one you want to output to
With Worksheets("Sheet3")
    .UsedRange.ClearContents

    For Each fld In rs.Fields
        i = i + 1
        .Cells(1, i).Value = fld.Name
    Next fld

    .Cells(2, 1).CopyFromRecordset rs
End With

' Tidy up
rs.Close
cn.Close
```

<p>The code could be changed to use early binding instead by adding a reference to "Microsoft ActiveX Data Objects 2.8 Library" (go to Tools > References in the VBA editor to do this). You would change the following lines which declare and initialize various ADO objects:</p>

<pre class="lang-vb prettyprint-override"><code>Dim cn As ADODB.Connection
Set cn = New ADODB.Connection

Dim rs As ADODB.Recordset

Dim fld As ADODB.Field
</code>```

Body:
How do you do SQL "select join on" in excel?
Say I want col one from table A, col two from table B and they both have col three.

I would do:

SELECT A.one, B.two
FROM A
INNER JOIN B ON
A.three = B.three

But instead of tables I have a few tabs in a Excel sheet. How do I do the equivalent of above query in Excel?

Body:
You can use VBA and ADO to query the worksheets directly with SQL. Just add the following code to a Sub in a VBA module. The code is mainly boilerplate except for the rs.Open line and the With Worksheets line which you should modify to suit your particular scenario.

' Set up connection
Dim cn As Object
Set cn = CreateObject("ADODB.Connection")

' Connection string for Excel 2007 onwards .xlsm files
With cn
   .Provider = "Microsoft.ACE.OLEDB.12.0"
   .ConnectionString = "Data Source=" & ThisWorkbook.FullName & ";" & _
        "Extended Properties=""Excel 12.0 Macro;IMEX=1"";"
    .Open
End With

' Connection string for Excel 97-2003 .xls files
' It should also work with Excel 2007 onwards worksheets
' as long as they have less than 65536 rows
'With cn
'    .Provider = "Microsoft.Jet.OLEDB.4.0"
'    .ConnectionString = "Data Source=" & ThisWorkbook.FullName & ";" & _
'        "Extended Properties=""Excel 8.0;IMEX=1"";"
'    .Open
'End With

' Create and run the query
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")

' Join the two worksheets - assumed that these are named "Sheet1"
' and "Sheet2", the columns are named "one", "two" and "three"
' and that the results should be output to "Sheet3"
rs.Open "SELECT [Sheet1$].[one], [Sheet2$].[two] " & _
    "FROM [Sheet1$] INNER JOIN [Sheet2$] " & _
    "ON [Sheet1$].[three] = [Sheet2$].[three];", cn

' Output the field names and the results
Dim fld As Object
Dim i As Integer

' Change the worksheet to whichever one you want to output to
With Worksheets("Sheet3")
    .UsedRange.ClearContents

    For Each fld In rs.Fields
        i = i + 1
        .Cells(1, i).Value = fld.Name
    Next fld

    .Cells(2, 1).CopyFromRecordset rs
End With

' Tidy up
rs.Close
cn.Close

The code could be changed to use early binding instead by adding a reference to "Microsoft ActiveX Data Objects 2.8 Library" (go to Tools > References in the VBA editor to do this). You would change the following lines which declare and initialize various ADO objects:

Dim cn As ADODB.Connection
Set cn = New ADODB.Connection

Dim rs As ADODB.Recordset

Dim fld As ADODB.Field


问:
Adding and updating Assets
I have a registry with an asset. I need to add a new asset, and then update the registry. The assets are an apportionment, where you send a value from one to the other one. If the receiving asset doesn't exist it's created with the new value assigned, and then the value it's taken from the sending one. When I have all the assets modified though the transaction .js and I want to update the registry, I do:

```<code>                if(exists==false){
                    return getAssetRegistry('org.basetis.bonusetis.apportionment')
                    .then(function (apportionmentRegistry) {
                        return apportionmentRegistry.addAll([apportionment1]);
                    })
                    .then(function () {
                        return getAssetRegistry('org.basetis.bonusetis.apportionment');
                    })
                    .then(function (apportionmentRegistry) {
                        return apportionmentRegistry.updateAll(apportionments);
                    })
</code>```

which if I debug, goes through the addAll that adds the new created asset, but then, when it tries to update it with updateAll it gives me an error saying that the new added asset does not exist. If I delete the updateAll function, the new asset does get added.
Why is it not able to update the asset if it has added it before in the code? Is there anything wrong in the code?

答: In Hyperledger Fabric (which Hyperledger Composer is currently using), you are not able to read your own writes from within a transaction, meaning that you cannot add something to a registry and then read it, in the same transaction. </p>

Title: Adding and updating Assets

Body:
I have a registry with an asset. I need to add a new asset, and then update the registry. The assets are an apportionment, where you send a value from one to the other one. If the receiving asset doesn't exist it's created with the new value assigned, and then the value it's taken from the sending one. When I have all the assets modified though the transaction .js and I want to update the registry, I do:

                if(exists==false){
                    return getAssetRegistry('org.basetis.bonusetis.apportionment')
                    .then(function (apportionmentRegistry) {
                        return apportionmentRegistry.addAll([apportionment1]);
                    })
                    .then(function () {
                        return getAssetRegistry('org.basetis.bonusetis.apportionment');
                    })
                    .then(function (apportionmentRegistry) {
                        return apportionmentRegistry.updateAll(apportionments);
                    })

which if I debug, goes through the addAll that adds the new created asset, but then, when it tries to update it with updateAll it gives me an error saying that the new added asset does not exist. If I delete the updateAll function, the new asset does get added.
Why is it not able to update the asset if it has added it before in the code? Is there anything wrong in the code?


问:
How do I get Filter Criteria in Excel 2016 using VBA?
I am working on an Excel 2016 VBA Macro that applies a filter to the headings column. Afterwards, the user applies the filter criteria. I would like to be able to in VBA retrieve the filter criteria that the user applied and save it to a string array. Is there a way to access the filter criteria?</p>

答:
I checked this question and pretty much copied the first part of the code, the only thing is you don't get the field that it is applied to which can be problematic.</p>

```<code>Dim sht As Worksheet
Set sht = ActiveSheet
With sht.AutoFilter
    With .Filters
        ReDim filtarr(1 To .Count, 1 To 3)
        For f = 1 To .Count
            With .Item(f)
                If .On Then
                    filtarr(f, 1) = .Criteria1
                    Debug.Print .Criteria1
                    If .Operator Then
                        filtarr(f, 2) = .Operator
                        filtarr(f, 3) = .Criteria2
                        Debug.Print .Operator & ", " & .Criteria2
                    End If
                End If
            End With
        Next f
    End With
End With
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I checked this question and pretty much copied the first part of the code, the only thing is you don't get the field that it is applied to which can be problematic.

Dim sht As Worksheet
Set sht = ActiveSheet
With sht.AutoFilter
    With .Filters
        ReDim filtarr(1 To .Count, 1 To 3)
        For f = 1 To .Count
            With .Item(f)
                If .On Then
                    filtarr(f, 1) = .Criteria1
                    Debug.Print .Criteria1
                    If .Operator Then
                        filtarr(f, 2) = .Operator
                        filtarr(f, 3) = .Criteria2
                        Debug.Print .Operator & ", " & .Criteria2
                    End If
                End If
            End With
        Next f
    End With
End With


问:
How does SQL Server determine if stored procedures are valid for "readonly" application intent?
The sys.dm_exec_describe_first_result_set_for_object function takes an object (e.g. stored procedure) and determines the properties of the first result set.

Is there a similar function that can show me if a procedure is "readonly", which could indicate that it can be used properly with ApplicationIntent=readonly in the connection string?

答:
Interesting question.  SQL Server does not mark objects as read-only, that is set at a user rights level.  The ApplicationIntent=readonly seems to be dealing with a situation where you are running Availability Groups and have a read-only replica for reporting usually.  It would then route to that server.

Read Only Application Intent


问:
How to construct a numpy array with its each element be the minimum value of all possible values?
I want to construct a 1d numpy array a, and I know each a[i] has several possible values. Of course, the numbers of the possible values of any two elements of a can be different. For each a[i], I want to set it be the minimum value of all the possible values.

For example, I have two array:

```<code>idx = np.array([0, 1, 0, 2, 3, 3, 3])
val = np.array([0.1, 0.5, 0.2, 0.6, 0.2, 0.1, 0.3])
</code>```

The array I want to construct is following:

```<code>a = np.array([0.1, 0.5, 0.6, 0.1])
</code>```

So does there exist any function in numpy can finish this work?

答:
You can also use binned_statistic:

```<code>from scipy.stats import binned_statistic

idx_list=np.append(np.unique(idx),np.max(idx)+1)
stats=binned_statistic(idx,val,statistic='min', bins=idx_list)
a=stats.statistic
</code>```

I think, in older scipy versions, statistic='min' was not implemented, but you can use statistic=np.min instead. Intervals are half open in binned_statistic, so this implementation is safe.

Body:
I want to construct a 1d numpy array a, and I know each a[i] has several possible values. Of course, the numbers of the possible values of any two elements of a can be different. For each a[i], I want to set it be the minimum value of all the possible values.

For example, I have two array:

idx = np.array([0, 1, 0, 2, 3, 3, 3])
val = np.array([0.1, 0.5, 0.2, 0.6, 0.2, 0.1, 0.3])

The array I want to construct is following:

a = np.array([0.1, 0.5, 0.6, 0.1])

So does there exist any function in numpy can finish this work?

Body:
You can also use binned_statistic:

from scipy.stats import binned_statistic

idx_list=np.append(np.unique(idx),np.max(idx)+1)
stats=binned_statistic(idx,val,statistic='min', bins=idx_list)
a=stats.statistic

I think, in older scipy versions, statistic='min' was not implemented, but you can use statistic=np.min instead. Intervals are half open in binned_statistic, so this implementation is safe.


问:
How to manipulate history in React Router v4?
I am using:

React, Redux, React-Router, Meteor

Following situation:

I have a modal with two tabs, based on the chosen tab a different list of selections will be shown in the content area, picking a selection will then give a list of subselection (all within the modal).

Desired behavior:

I want the user to be able to use the browser's back button to "undo" clicking on one of the tabs or picking a selection.

What I tried so far with no success:

use withRouter HOC to wrap my component, so that I would get access to history. I would then use history.push(currentUrl,{selectedTab:selection})
-> Problem: the state from push wasn't stored on this histories location object, but only in the state of the history object associated with my rootcomponent (way further up the tree)

(More promising so far) Simply import the history I created with createHistory in another module and put that into component state on construction.
I would then access the push method by using this.state.history.push(currentUrl,{selectedTab:selection}), which works fine and I can find the pushed state under this.state.history.location.state.selectedTab. However, using the browser's back button does not cause a rerender and therefore the selection will stay the same.

Any ideas?

Cheers

答:
I refined the second approach and it is working now. It does still feel hacky to import the history into my module (as a local variable), and thus bypassing react tree, redux store and react router altogether.
However, it is working and not causing any bugs so far. So here we go ...

I instantiate my history object in:
 store.js module:

```<code>import createHistory from 'history/createBrowserHistory';
...
const history = createHistory();
...
export { history , store }
</code>```

that as you can see exports history. I then feed said history to my Router (ConnectedRouter in my case, as I am using react-router-redux) in:
routes.js module

```<code>import { store , history } from '/imports/client/store';

const MyStoreRouter = () => {
    return (
        <Provider store={store}>
            <ConnectedRouter history={ history }>
                <div>
                    <Switch>
                        <Route exact path="/" component={Landing}/>
                        <Route path="/" component={MainApp}/>
                    </Switch>
                </div>
            </ConnectedRouter>
        </Provider>
    );
};
</code>```

Now for the wacky part. I import the history into a display component and use it to set up a listener (to state changes in history.location) and change the state accordingly:

DisplayComponent.js module:

```<code>import { history } from '/imports/client/store';
....
export default class EventCreationModal extends Component {
    constructor() {
        super();
        this.handleSelect = this.handleSelect.bind(this);
        this.state = {
            selectedCategory: (history.location.state && history.location.state.category) ? history.location.state.category : 'sports',
        };
        history.listen((location,action) => {
            this.setState({
                selectedCategory: (history.location.state && history.location.state.category) ? history.location.state.category : 'sports',
            })
        });
    }

    handleSelect(key) {
        history.push("/Home",{'category':key})
    }

render () {
    return (
        <Tabs activeKey={this.state.selectedCategory} onSelect={this.handleSelect} id="SportOrSocialSelector">
            <Tab eventKey={'sports} .../>
            <Tab eventKey={'social} .../>
        </Tabs>
    )
}
</code>```

Body:
I refined the second approach and it is working now. It does still feel hacky to import the history into my module (as a local variable), and thus bypassing react tree, redux store and react router altogether.
However, it is working and not causing any bugs so far. So here we go ...

I instantiate my history object in:
 store.js module:

import createHistory from 'history/createBrowserHistory';
...
const history = createHistory();
...
export { history , store }

that as you can see exports history. I then feed said history to my Router (ConnectedRouter in my case, as I am using react-router-redux) in:
routes.js module

import { store , history } from '/imports/client/store';

const MyStoreRouter = () => {
    return (
        <Provider store={store}>
            <ConnectedRouter history={ history }>
                <div>
                    <Switch>
                        <Route exact path="/" component={Landing}/>
                        <Route path="/" component={MainApp}/>
                    </Switch>
                </div>
            </ConnectedRouter>
        </Provider>
    );
};

Now for the wacky part. I import the history into a display component and use it to set up a listener (to state changes in history.location) and change the state accordingly:

DisplayComponent.js module:

import { history } from '/imports/client/store';
....
export default class EventCreationModal extends Component {
    constructor() {
        super();
        this.handleSelect = this.handleSelect.bind(this);
        this.state = {
            selectedCategory: (history.location.state && history.location.state.category) ? history.location.state.category : 'sports',
        };
        history.listen((location,action) => {
            this.setState({
                selectedCategory: (history.location.state && history.location.state.category) ? history.location.state.category : 'sports',
            })
        });
    }

    handleSelect(key) {
        history.push("/Home",{'category':key})
    }

render () {
    return (
        <Tabs activeKey={this.state.selectedCategory} onSelect={this.handleSelect} id="SportOrSocialSelector">
            <Tab eventKey={'sports} .../>
            <Tab eventKey={'social} .../>
        </Tabs>
    )
}


问:
C++ syntax of 2D vector
Can someone explain below c++ syntax with example ?

```<code>vector <vector <int> > s(n,vector <int> ());
</code>```

especially this part inside the constructor:

```<code>vector <int> ()
</code>```

答:
This specific constructor of vector takes two arguments:

The number of elements.

The value to assign to each element.

For example, this creates a vector containing 3 times the value 5.

```<code>std::vector<int> vec(3, 5);
</code>```

vector<int>() is a default-constructed instance of vector<int>. So you are creating a vector containing n vectors, each empty.

Title: C++ syntax of 2D vector

Body:
Can someone explain below c++ syntax with example ?

vector <vector <int> > s(n,vector <int> ());

especially this part inside the constructor:

vector <int> ()

Body:
This specific constructor of vector takes two arguments:

The number of elements.

The value to assign to each element.

For example, this creates a vector containing 3 times the value 5.

std::vector<int> vec(3, 5);

vector<int>() is a default-constructed instance of vector<int>. So you are creating a vector containing n vectors, each empty.


问:
event is not null but _invocationList is null?
I thought that if I have this code:

```<code>    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (PropertyChanged != null) PropertyChanged(this, e);
    }
</code>```

and the PropertyChanged event wasn't hooked, ProeprtyChanged would be null, but I'm getting a PropertyChanged that is not null and whose _invocationList member is null and whose _invocationCount member is 0. This (I think) is causing an ArgumentOutOfRangeException when I invoke PropertyChanged(this, e). Any idea where could the problem be?

This is my stack trace from the OnClick event:

at System.Collections.ArrayList.get_Item(Int32 index)
     at System.Windows.Forms.BindingsCollection.get_Item(Int32 index)
     at System.Windows.Forms.BindingManagerBase.PushData(Boolean& success)
     at System.Windows.Forms.PropertyManager.OnCurrentChanged(EventArgs ea)
     at System.Windows.Forms.BindToObject.PropValueChanged(Object sender, EventArgs e)
     at System.EventHandler.Invoke(Object sender, EventArgs e)
     at System.ComponentModel.PropertyDescriptor.OnValueChanged(Object component, EventArgs e)
     at System.ComponentModel.ReflectPropertyDescriptor.OnValueChanged(Object component, EventArgs e)
     at System.ComponentModel.ReflectPropertyDescriptor.OnINotifyPropertyChanged(Object component, PropertyChangedEventArgs e)
     at Player.DataBaseManager.OnPropertyChanged(PropertyChangedEventArgs e) in C:\Users\Juan Luis\My Dropbox\Documents\CodeWebScraper sin Player\WebScraperAndPlayer\Player\DataBaseManager2.cs:line 100
     at Player.DataBaseManager.set_TableNames(List`1 value) in C:\Users\Juan Luis\My Dropbox\Documents\CodeWebScraper sin Player\WebScraperAndPlayer\Player\DataBaseManager2.cs:line 30
     at Player.DataBaseManager.UpdateTableNames() in C:\Users\Juan Luis\My Dropbox\Documents\CodeWebScraper sin Player\WebScraperAndPlayer\Player\DataBaseManager2.cs:line 95
     at Player.DataBaseManager.ExecuteNonQuery(String sqlQuery) in C:\Users\Juan Luis\My Dropbox\Documents\CodeWebScraper sin Player\WebScraperAndPlayer\Player\DataBaseManager2.cs:line 336
     at WebScraperAndPlayer.DataBaseEditor.deleteTableButton_Click(Object sender, EventArgs e) in C:\Users\Juan Luis\My Dropbox\Documents\CodeWebScraper sin Player\WebScraperAndPlayer\BuilderForm2\Data\DataBaseEditor.cs:line 90
     at System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
     at System.Windows.Forms.ToolStripButton.OnClick(EventArgs e)

答:
System.EventHandler.Invoke(Object sender, EventArgs e)

That was the PropertyChanged(this, e) call.  It isn't the cause of the exception, your stack trace went well beyond this.  Unfortunately into code you didn't write, it's part of the Winforms binding plumbing.  Something is screwed up with the binding.

Body:
I thought that if I have this code:

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (PropertyChanged != null) PropertyChanged(this, e);
    }

and the PropertyChanged event wasn't hooked, ProeprtyChanged would be null, but I'm getting a PropertyChanged that is not null and whose _invocationList member is null and whose _invocationCount member is 0. This (I think) is causing an ArgumentOutOfRangeException when I invoke PropertyChanged(this, e). Any idea where could the problem be?

This is my stack trace from the OnClick event:

at System.Collections.ArrayList.get_Item(Int32 index)
     at System.Windows.Forms.BindingsCollection.get_Item(Int32 index)
     at System.Windows.Forms.BindingManagerBase.PushData(Boolean& success)
     at System.Windows.Forms.PropertyManager.OnCurrentChanged(EventArgs ea)
     at System.Windows.Forms.BindToObject.PropValueChanged(Object sender, EventArgs e)
     at System.EventHandler.Invoke(Object sender, EventArgs e)
     at System.ComponentModel.PropertyDescriptor.OnValueChanged(Object component, EventArgs e)
     at System.ComponentModel.ReflectPropertyDescriptor.OnValueChanged(Object component, EventArgs e)
     at System.ComponentModel.ReflectPropertyDescriptor.OnINotifyPropertyChanged(Object component, PropertyChangedEventArgs e)
     at Player.DataBaseManager.OnPropertyChanged(PropertyChangedEventArgs e) in C:\Users\Juan Luis\My Dropbox\Documents\CodeWebScraper sin Player\WebScraperAndPlayer\Player\DataBaseManager2.cs:line 100
     at Player.DataBaseManager.set_TableNames(List`1 value) in C:\Users\Juan Luis\My Dropbox\Documents\CodeWebScraper sin Player\WebScraperAndPlayer\Player\DataBaseManager2.cs:line 30
     at Player.DataBaseManager.UpdateTableNames() in C:\Users\Juan Luis\My Dropbox\Documents\CodeWebScraper sin Player\WebScraperAndPlayer\Player\DataBaseManager2.cs:line 95
     at Player.DataBaseManager.ExecuteNonQuery(String sqlQuery) in C:\Users\Juan Luis\My Dropbox\Documents\CodeWebScraper sin Player\WebScraperAndPlayer\Player\DataBaseManager2.cs:line 336
     at WebScraperAndPlayer.DataBaseEditor.deleteTableButton_Click(Object sender, EventArgs e) in C:\Users\Juan Luis\My Dropbox\Documents\CodeWebScraper sin Player\WebScraperAndPlayer\BuilderForm2\Data\DataBaseEditor.cs:line 90
     at System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
     at System.Windows.Forms.ToolStripButton.OnClick(EventArgs e)


问:
How to run another batch script with different privilege?
I want to run a batch script as Administrator which, in turn, starts another batch script (start "title" /b /wait), but with current user's privilege.
Is this possible? What's the best way to do it?
Or how can I get the current logged in user name?</p>

答:
The command you want is runas - this command runs batchfile with the domain and username of the currently logged in user (you could also hardcode the domain and username if you wanted a specific user):

```<code>runas /noprofile /user:%USERDOMAIN%\%USERNAME% C:\batchfile.bat
</code>```

The runas command requires an external program as the last argument so it doesn't handle built in commands like dir or copy.  But you can run a built in command like copy with:

```<code>runas /noprofile /user:%USERDOMAIN%\%USERNAME% "cmd /c copy C:\source.txt C:\dest.txt"
</code>```

You can also run things as Administrator like this:

```<code>runas /noprofile /user:Administrator "cmd /c copy C:\file.txt C:\Windows\System"
</code>```

Here is some more info:

https://www.windows-commandline.com/windows-runas-command-prompt/

Body:
The command you want is runas - this command runs batchfile with the domain and username of the currently logged in user (you could also hardcode the domain and username if you wanted a specific user):

runas /noprofile /user:%USERDOMAIN%\%USERNAME% C:\batchfile.bat

The runas command requires an external program as the last argument so it doesn't handle built in commands like dir or copy.  But you can run a built in command like copy with:

runas /noprofile /user:%USERDOMAIN%\%USERNAME% "cmd /c copy C:\source.txt C:\dest.txt"

You can also run things as Administrator like this:

runas /noprofile /user:Administrator "cmd /c copy C:\file.txt C:\Windows\System"

Here is some more info:

https://www.windows-commandline.com/windows-runas-command-prompt/


问:
Android: ListPreference as font size picker or accessing individual views of ListView items
What is the best way to create a ListPreference to be used as a "font size picker" like this?

Is there any way I can access individual views of items of the ListView in that preference and set them font size? Or do I have to create custom ListPreference with custom adapter?

Thanks in advance.

答:
Best way (without breaking any of the original ListPreference implementation):</p>

```<code>@Override
protected void onPrepareDialogBuilder(Builder builder) {

    ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(getContext(), R.layout.preference_font_size_checked_tv, getEntries()) {
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            float fontSizePx;
            CheckedTextView view = (CheckedTextView) convertView;
            if(view == null){
                view = (CheckedTextView) View.inflate(getContext(), R.layout.preference_font_size_checked_tv, null);
            }
            switch (position){
                case 0:
                    fontSizePx = getContext().getResources().getDimension(R.dimen.font_size_small_medium);
                    break;
                case 2:
                    fontSizePx = getContext().getResources().getDimension(R.dimen.font_size_large_medium);
                    break;
                case 1:default:
                    fontSizePx = getContext().getResources().getDimension(R.dimen.font_size_medium_medium);
            }
            view.setText(getEntries()[position]);
            view.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSizePx);
            return view;
        }
    };
    builder.setAdapter(adapter, this);
    super.onPrepareDialogBuilder(builder);
}

@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
    preference.setSummary(getEntry());
    return true;
}
</code>```

Body:
Best way (without breaking any of the original ListPreference implementation):

@Override
protected void onPrepareDialogBuilder(Builder builder) {

    ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(getContext(), R.layout.preference_font_size_checked_tv, getEntries()) {
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            float fontSizePx;
            CheckedTextView view = (CheckedTextView) convertView;
            if(view == null){
                view = (CheckedTextView) View.inflate(getContext(), R.layout.preference_font_size_checked_tv, null);
            }
            switch (position){
                case 0:
                    fontSizePx = getContext().getResources().getDimension(R.dimen.font_size_small_medium);
                    break;
                case 2:
                    fontSizePx = getContext().getResources().getDimension(R.dimen.font_size_large_medium);
                    break;
                case 1:default:
                    fontSizePx = getContext().getResources().getDimension(R.dimen.font_size_medium_medium);
            }
            view.setText(getEntries()[position]);
            view.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSizePx);
            return view;
        }
    };
    builder.setAdapter(adapter, this);
    super.onPrepareDialogBuilder(builder);
}

@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
    preference.setSummary(getEntry());
    return true;
}


问:
what is the difference between Control.OnClick and Control.InvokeOnClick
i'm just wondering what the difference is between Control.OnClick and Control.InvokeOnClick methods.

the second thing i wonder ise, when it is asp.net they talk about 3 componenets: Click event, OnClick method, and button1_click eventhandler. but when it is desktop appcliatons they talk about only 2 componenets, Click event and its eventhandler. why is the onclik(invokeonclick) not mentioned at all?

答:
OnClick allows you to add a handler for when the Click event occurs on the control.
InvokeOnClick will "Raise the Click event for the specified control".

So if you have assigned a handler to OnClick and then call InvokeOnClick on that control then your handler will be called.

Web is different. This answer may help you for invoking click on a 'web' button.


问:
How to stop Auth user from visiting own page with non auth user privileges in laravel?
My laravel application is a social media site. Here's the route for visiting another laravel user's profile

```<code>Route::get('/dashboard/{id}', [
'uses' => 'UserController@getProfile',
'as' => 'profile.index',
'middleware' => 'auth'
]);
</code>```

It works just fine. However, I've discovered a bug that when I input the Auth user's ID into the route, I get taken to the same page where I can then add myself as a friend, I do not want this to happen. I would rather get taken back to the home screen if I'm visiting my own profile.

Here's the controller:

```<code> public function getProfile($id)
{

    if(Auth::user() === $id)
        redirect('dashboard');

    $user = User::where('id', $id)->first();

    $posts = Post::where("dash_id", "=", $user->id)->latest()->paginate(3);
    $photos = Photo::paginate(6);
    return view('profile.index',compact('user','posts', 'photos'));

}
</code>```

I've tried to get it to redirect to 'dashboard' instead of 'profile.index' if it's the Auth user's page instead of pulling up just like a regular non-auth profile, but can't seem to get it to work. Any ideas on how to fix this small bug?

答:
You try to compare the current user object to the request id, try this code:</p>

```<code>public function getProfile($id)
{
    if(Auth::id() === $id) {
        redirect('dashboard');
    }

    $user = User::where('id', $id)->first();

    $posts = Post::where("dash_id", "=", $user->id)->latest()->paginate(3);
    $photos = Photo::paginate(6)

    return view('profile.index',compact('user','posts', 'photos'));
}
</code>```

Body:
My laravel application is a social media site. Here's the route for visiting another laravel user's profile

Route::get('/dashboard/{id}', [
'uses' => 'UserController@getProfile',
'as' => 'profile.index',
'middleware' => 'auth'
]);

It works just fine. However, I've discovered a bug that when I input the Auth user's ID into the route, I get taken to the same page where I can then add myself as a friend, I do not want this to happen. I would rather get taken back to the home screen if I'm visiting my own profile.

Here's the controller:

 public function getProfile($id)
{

    if(Auth::user() === $id)
        redirect('dashboard');

    $user = User::where('id', $id)->first();

    $posts = Post::where("dash_id", "=", $user->id)->latest()->paginate(3);
    $photos = Photo::paginate(6);
    return view('profile.index',compact('user','posts', 'photos'));

}

I've tried to get it to redirect to 'dashboard' instead of 'profile.index' if it's the Auth user's page instead of pulling up just like a regular non-auth profile, but can't seem to get it to work. Any ideas on how to fix this small bug?

Body:
You try to compare the current user object to the request id, try this code:

public function getProfile($id)
{
    if(Auth::id() === $id) {
        redirect('dashboard');
    }

    $user = User::where('id', $id)->first();

    $posts = Post::where("dash_id", "=", $user->id)->latest()->paginate(3);
    $photos = Photo::paginate(6)

    return view('profile.index',compact('user','posts', 'photos'));
}


问:
Java 8 Stream read file for every 100 lines
Let's say I have a huge file and I would like to read 100 every lines and do one operation. (I want to combine 100 lines and send a rest request)

In Java 7, I would do something like below.

```<code>try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {

    String line;
    int count = 0;
    List<String> list = new ArrayList<>();
    while ((line = br.readLine()) != null) {
        list.add(line);
        count++;
        if (count % 100 == 0) {
            //do the operation on list
            list = new ArrayList();
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}
</code>```

Is there something we can leverage Java 8 Stream here?
I know we can do something like this but it operates on each line instead of 100 lines. So I think foreach is not the option here.

```<code>try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
    stream.forEach(System.out::println);
} catch (IOException e) {
    e.printStackTrace();
}
</code>```

答:
If you don't like the approach above you can simply using the second approach, but you can't create partial streams in parallel since you must read the lines sequentially. for example:

```<code>split(Paths.get("file"), 100).forEach(this::sendRequest);

void sendRequest(List<String> each) {
  // then you must send the rest request in parallel here
}
</code>```

```<code>Stream<List<String>> split(Path path, int limit) throws IOException {
    // skip the remaining lines if its size < limit
    return split(Files.lines(path), limit, true);
}

<T> Stream<List<T>> split(Stream<T> source,
                          int limit, boolean skipRemainingElements) {

    //variables just for printing purpose
    Spliterator<T> it = source.spliterator();
    long size = it.estimateSize();
    int c = it.characteristics();// characteristics

    return stream(new AbstractSpliterator<List<T>>(size, c) {
        private int thresholds = skipRemainingElements ? limit : 1;

        @Override
        @SuppressWarnings("StatementWithEmptyBody")
        public boolean tryAdvance(Consumer<? super List<T>> action) {
            List<T> each = new ArrayList<>(limit);

            while (each.size() < limit && it.tryAdvance(each::add)) ;

            if (each.size() < thresholds) return false;

            action.accept(each);
            return true;
        }

    }, false).onClose(source::close);
}
</code>```

Body:
Let's say I have a huge file and I would like to read 100 every lines and do one operation. (I want to combine 100 lines and send a rest request)

In Java 7, I would do something like below.

try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {

    String line;
    int count = 0;
    List<String> list = new ArrayList<>();
    while ((line = br.readLine()) != null) {
        list.add(line);
        count++;
        if (count % 100 == 0) {
            //do the operation on list
            list = new ArrayList();
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}

Is there something we can leverage Java 8 Stream here?
I know we can do something like this but it operates on each line instead of 100 lines. So I think foreach is not the option here.

try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
    stream.forEach(System.out::println);
} catch (IOException e) {
    e.printStackTrace();
}

Body:
If you don't like the approach above you can simply using the second approach, but you can't create partial streams in parallel since you must read the lines sequentially. for example:

split(Paths.get("file"), 100).forEach(this::sendRequest);

void sendRequest(List<String> each) {
  // then you must send the rest request in parallel here
}

Stream<List<String>> split(Path path, int limit) throws IOException {
    // skip the remaining lines if its size < limit
    return split(Files.lines(path), limit, true);
}

<T> Stream<List<T>> split(Stream<T> source,
                          int limit, boolean skipRemainingElements) {

    //variables just for printing purpose
    Spliterator<T> it = source.spliterator();
    long size = it.estimateSize();
    int c = it.characteristics();// characteristics

    return stream(new AbstractSpliterator<List<T>>(size, c) {
        private int thresholds = skipRemainingElements ? limit : 1;

        @Override
        @SuppressWarnings("StatementWithEmptyBody")
        public boolean tryAdvance(Consumer<? super List<T>> action) {
            List<T> each = new ArrayList<>(limit);

            while (each.size() < limit && it.tryAdvance(each::add)) ;

            if (each.size() < thresholds) return false;

            action.accept(each);
            return true;
        }

    }, false).onClose(source::close);
}


问:
Spring i18n and l10n error-NoSuchMessageException: No message found under code 'lable' for locale 'hi,en-in;q=0.5'
I am trying to implement i18n and l10n using Spring.I am getting error:

```<code>NoSuchMessageException: No message found under code 'lable' for locale 'hi,en-in;q=0.5'
</code>```

Here is the code snippet:
index.jsp file:

```<code><%-- String lang=request.getHeader("accept-language"); This line will give browser language --%>
<%@page import="org.springframework.context.support.ResourceBundleMessageSource"%>
<%@page import="org.springframework.context.support.ClassPathXmlApplicationContext"%>
<%@page import="org.springframework.context.ApplicationContext"%>
<%@page import="java.util.Locale"%>
<%

String lang=request.getHeader("accept-language");
Locale locale =new Locale(lang);
ApplicationContext ap =new ClassPathXmlApplicationContext("resources/spring.xml");
String value=ap.getMessage("lable",null,locale);
%>

<form action="./hello">
<%=value%>:<input type="text" name="name"/>
            <input type="submit" value="submit">
</form>
</code>```

2 properties files and 1 spring.xml file:

Data_hi.properties: for hindi language

lable=नाम्

Data_te.properties: for Telugu language

lable=సిదర్త్

spring.xml file:

```<code><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name ="basename" value="Data"/>
    </bean>

</beans>
</code>```

When I am trying to run the application via Tomcat Server,I am getting the below error:

HTTP Status 500 -

type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

```<code>org.apache.jasper.JasperException: An exception occurred processing JSP page /index.jsp at line 11

8: String lang=request.getHeader("accept-language");
9: Locale locale =new Locale(lang);
10: ApplicationContext ap =new ClassPathXmlApplicationContext("resources/spring.xml");
11: String value=ap.getMessage("lable",null,locale);
12: %>
13:
14:
</code>```

Stacktrace:

```<code>org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
</code>```

root cause

```<code>org.springframework.context.NoSuchMessageException: No message found under code 'lable' for locale 'hi,en-in;q=0.5'.
    org.springframework.context.support.AbstractMessageSource.getMessage(AbstractMessageSource.java:159)
    org.springframework.context.support.AbstractApplicationContext.getMessage(AbstractApplicationContext.java:1259)
    org.apache.jsp.index_jsp._jspService(index_jsp.java:76)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
</code>```

note The full stack trace of the root cause is available in the Apache Tomcat/7.0.23 logs.

Apache Tomcat/7.0.23

Please suggest someone where I need to correct the code.I tried on google also but didn't find?

PS:All the required jars and libraries are imported correctly.

Thanks in advance!!!

答:
Agreed with  M. Deinum's comments about  memory issues, however to resolve your described issue below approaches should work :

either set your browser's language to hindi or telgu as these are the prop files you added in resources and running the code to get it.

or Add one more property file Data_en.properties because your browser's language would be english during execution of jsp code and there was no prop file related to english message and throwing error "NoSuchMessageException: No message found under code 'lable' for locale 'hi,en-in;q=0.5'" which correct quite obviously ;)

Body:
I am trying to implement i18n and l10n using Spring.I am getting error:

NoSuchMessageException: No message found under code 'lable' for locale 'hi,en-in;q=0.5'

Here is the code snippet:
index.jsp file:

<%-- String lang=request.getHeader("accept-language"); This line will give browser language --%>
<%@page import="org.springframework.context.support.ResourceBundleMessageSource"%>
<%@page import="org.springframework.context.support.ClassPathXmlApplicationContext"%>
<%@page import="org.springframework.context.ApplicationContext"%>
<%@page import="java.util.Locale"%>
<%

String lang=request.getHeader("accept-language");
Locale locale =new Locale(lang);
ApplicationContext ap =new ClassPathXmlApplicationContext("resources/spring.xml");
String value=ap.getMessage("lable",null,locale);
%>

<form action="./hello">
<%=value%>:<input type="text" name="name"/>
            <input type="submit" value="submit">
</form>

2 properties files and 1 spring.xml file:

Data_hi.properties: for hindi language

lable=नाम्

Data_te.properties: for Telugu language

lable=సిదర్త్

spring.xml file:

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name ="basename" value="Data"/>
    </bean>

</beans>

When I am trying to run the application via Tomcat Server,I am getting the below error:

HTTP Status 500 -

type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

org.apache.jasper.JasperException: An exception occurred processing JSP page /index.jsp at line 11

8: String lang=request.getHeader("accept-language");
9: Locale locale =new Locale(lang);
10: ApplicationContext ap =new ClassPathXmlApplicationContext("resources/spring.xml");
11: String value=ap.getMessage("lable",null,locale);
12: %>
13:
14:

Stacktrace:

org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

root cause

org.springframework.context.NoSuchMessageException: No message found under code 'lable' for locale 'hi,en-in;q=0.5'.
    org.springframework.context.support.AbstractMessageSource.getMessage(AbstractMessageSource.java:159)
    org.springframework.context.support.AbstractApplicationContext.getMessage(AbstractApplicationContext.java:1259)
    org.apache.jsp.index_jsp._jspService(index_jsp.java:76)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

note The full stack trace of the root cause is available in the Apache Tomcat/7.0.23 logs.

Apache Tomcat/7.0.23

Please suggest someone where I need to correct the code.I tried on google also but didn't find?

PS:All the required jars and libraries are imported correctly.

Thanks in advance!!!