问:
Kivy scatter region is limited to window size
I'm basically running into issues with the only "grabbable" scatter regions being entirely defined by the size of the window I am viewing the program in, and not the size of the scatter.

Here's a working example of the bug:

```<code>from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.uix.scatter import Scatter

class AppFrame(GridLayout):
    def __init__(self,**kwargs):
        super(AppFrame,self).__init__(**kwargs)
        self.myscatter=Scatter(
            width=2000,
            height=200,
            do_rotation=False,
            do_scale=True,
            do_translation=True)
        self.add_widget(self.myscatter)
        self.layout=GridLayout(cols=30,width=2000,height=200)
        self.myscatter.add_widget(self.layout)

        for i in range(300):
            self.layout.add_widget(Button(text=str(i)))

class TestApp(App):
    def build(self):
        return AppFrame(cols=3)

if __name__ == '__main__':
    TestApp().run()
</code>```

On my screen, if I use the scatter to move to the right (increasing with the buttons), I can't grab anything past button ~10-11.  If I resize my screen, I can grab a bit farther.  If I make my screen small, the grabbable area shrinks and might not even be reachable. How on earth can I fix this?

I'm using the Kivy environment with the Android emulator, so I have a pretty big screen. Unfortunately if I moved this to a phone, the screen size would shrink significantly, making this bug effectively disable scrolling.

(The toplevel layout is for adding a menu. The actual menu isn't included in this example as it's not necessary to recreate the bug)

The main things I'm trying to figure out are:

Is this an issue with the code or with the android emulator?

If its an issue with the code, can it be fixed and how?

If it can't be fixed, how else can I get this functionality?

UPDATE:
 After the comment from George Bou, I've isolated the problem to be within the scatter's BBOX. On creation, the scatter bbox size is 2000x200.  However, after window creation it is 800x600 (the default size of the screen that pops up).

Annoyingly, I can't figure out how to fix this.  If I change the scatter's width/height at any point(i.e., in a button), it immediately gets reset back to 800x600 whenever a translation/zoom occurs. Anyone know how to make scatter stop automatically resizing its bbox to the window?

答: I ran into this myself. Add size_hint=(None,None) to stop it from using the windows dimensions.</p>

Body:
I'm basically running into issues with the only "grabbable" scatter regions being entirely defined by the size of the window I am viewing the program in, and not the size of the scatter.

Here's a working example of the bug:

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.uix.scatter import Scatter

class AppFrame(GridLayout):
    def __init__(self,**kwargs):
        super(AppFrame,self).__init__(**kwargs)
        self.myscatter=Scatter(
            width=2000,
            height=200,
            do_rotation=False,
            do_scale=True,
            do_translation=True)
        self.add_widget(self.myscatter)
        self.layout=GridLayout(cols=30,width=2000,height=200)
        self.myscatter.add_widget(self.layout)

        for i in range(300):
            self.layout.add_widget(Button(text=str(i)))

class TestApp(App):
    def build(self):
        return AppFrame(cols=3)

if __name__ == '__main__':
    TestApp().run()

On my screen, if I use the scatter to move to the right (increasing with the buttons), I can't grab anything past button ~10-11.  If I resize my screen, I can grab a bit farther.  If I make my screen small, the grabbable area shrinks and might not even be reachable. How on earth can I fix this?

I'm using the Kivy environment with the Android emulator, so I have a pretty big screen. Unfortunately if I moved this to a phone, the screen size would shrink significantly, making this bug effectively disable scrolling.

(The toplevel layout is for adding a menu. The actual menu isn't included in this example as it's not necessary to recreate the bug)

The main things I'm trying to figure out are:

Is this an issue with the code or with the android emulator?

If its an issue with the code, can it be fixed and how?

If it can't be fixed, how else can I get this functionality?

UPDATE:
 After the comment from George Bou, I've isolated the problem to be within the scatter's BBOX. On creation, the scatter bbox size is 2000x200.  However, after window creation it is 800x600 (the default size of the screen that pops up).

Annoyingly, I can't figure out how to fix this.  If I change the scatter's width/height at any point(i.e., in a button), it immediately gets reset back to 800x600 whenever a translation/zoom occurs. Anyone know how to make scatter stop automatically resizing its bbox to the window?


来源: stackexchange

问:
Unknown encoding (\x001, not ASCII) to float in Python
I have this string in Python '\x005\x003\x00.\x000\x005\x006\x00' that represents the number 53.056.

I am trying to convert that to a float (float()) but if I try to cast it to a float I get ValueError: could not convert string to float:.

I read that every character beginning with \x is an ASCII character but I also know that in ASCII 5 is \x05 and not \x005 and that \x00 is the number 0 and not a null value like in this case.

I also tried to encode that in UTF-8 but with no result.

What encoding is that and and how do I convert that string to a float?

答:
The string has some \x00 null characters that are causing the ValueError when you attempt to cast it to float. If you get rid of those, you should be able to call float() on it.

```<code>s = '\x005\x003\x00.\x000\x005\x006\x00'

float(''.join([char for char in s if char in '0123456789.']))
# or
float(s.replace('\x00', ''))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The string has some \x00 null characters that are causing the ValueError when you attempt to cast it to float. If you get rid of those, you should be able to call float() on it.

s = '\x005\x003\x00.\x000\x005\x006\x00'

float(''.join([char for char in s if char in '0123456789.']))
# or
float(s.replace('\x00', ''))


问:
How to embed image link in drupal?
I want to add image from remote server. I have image link such as http://www.qygjxz.com/data/out/114/5095827-image.jpg
But drupal is giving only upload image option. I don't want to store image. I want to display it without storing.</p>

答: Hi if you are running drupal 8, there is a module "Remote Image" to handle this https://www.drupal.org/project/remote_image

Title: How to embed image link in drupal?


答:
You can do with two query

first an insert/select with (fake) aggregation function and group by for populate all the column of a row

```<code>  insert into my_table (id, col1, col2,col3)
  select id, max(col1), max(col2), max(col3)
  from my_table
  group by id
  ;
</code>```

second  a delete for remove the row with some null coll

```<code>  delete from
  my_table
  where col1 is null
  or col2 is null
  or col3 is null
  ;
</code>```

Title: Reduction of rows in a table

Body:
How would I make this so that it just contains one row without any null values. I am unsure how to go about doing this.

+----+-------------+--------------+-----------------------+
| id |    Col1     |     Col2     |         Col3          |
+----+-------------+--------------+-----------------------+
|  1 | description | null         | null                  |
|  1 | null        | descriptions | null                  |
|  1 | null        | null         | different description |
+----+-------------+--------------+-----------------------+

Example of what I want to have

+----+-------------+--------------+-----------------------+
| id |    Col1     |     Col2     |         Col3          |
+----+-------------+--------------+-----------------------+
|  1 | description | descriptions | different description |
+----+-------------+--------------+-----------------------+

Body:
You can do with two query

first an insert/select with (fake) aggregation function and group by for populate all the column of a row

  insert into my_table (id, col1, col2,col3)
  select id, max(col1), max(col2), max(col3)
  from my_table
  group by id
  ;

second  a delete for remove the row with some null coll

  delete from
  my_table
  where col1 is null
  or col2 is null
  or col3 is null
  ;


问:
Should I use encodeURI or encodeURIComponent for encoding URLs?
Which of these two methods should be used for encoding URLs?</p>

答: As a general rule use encodeURIComponent.  Don't be scared of the long name thinking it's more specific in it's use, to me it's the more commonly used method.  Also don't be suckered into using encodeURI because you tested it and it appears to be encoding properly, it's probably not what you meant to use and even though your simple test using "Fred" in a first name field worked, you'll find later when you use more advanced text like adding an ampersand or a hashtag it will fail.  You can look at the other answers for the reasons why this is.


问:
Is it really safe to use Java for real-time purposes?
I recently read the paper "Making Android run on time", by Yin Yan et al. To fully understand the topic, I also read something about the Real-Time Specification for Java (RTSJ) and about lots of real-time virtual machines, garbage collectors and so on. Nevertheless, I still have a doubt. A RTSJ-compliant virtual machine uses priority inheritance for preventing priority inversion, but I know this algorithm does not prevent deadlocks. Since threads have no way to control the resource acquisition order, there is the possibility to circular wait, that actually can lead to a deadlock.

So, in the light of this, is it really safe to use Java as a programming language for real-time purposes, included desktop and mobile applications?

My question isn't about the use of either Java, Android or Linux as-is. My question is about the algorithm choosen by the RTSJ (priority inheritance), as it doesn't prevent deadlocks to occur.

答:
What do you want-  realtime, or desktop/mobile?  Realtime is for things like a pacemaker-  it means that if the computer can't promise a job will finish by time X, it won't even attempt to run it.  Its only suitable for systems where the execution time of all tasks is known.  Computers (including PCs, Macs, and Linux) are not realtime.  As Linux is not realtime, nothing on Android is.

As for realtime Java in general- no.  Nothing that has non-deterministic garbage collection can be used for realtime programming.


问:
pyspark partitioning data using partitionby
I understand that partitionBy function partitions my data. If I use rdd.partitionBy(100) it will partition my data by key into 100 parts. i.e. data associated with similar keys will be grouped together

Is my understanding correct?

Is it advisable to have number of partitions equal to number of
    available cores? Does that make processing more efficient?

what if my data is not in key,value format. Can i still use this function?

lets say my data is serial_number_of_student,student_name. In this
        case can i partition my data by student_name instead of the
        serial_number?

答: I recently used partitionby. What I did was restructure my data so that all those which I want to put in same partition have the same key, which in turn is a value from the data. my data was a list of dictionary, which I converted into tupples with key from dictionary.Initially the partitionby was not keeping same keys in same partition. But then I realized the keys were strings. I cast them to int. But the problem persisted. The numbers were very large. I then mapped these numbers to small numeric values and it worked. So my take away was that the keys need to be small integers. </p>


问:
Stuck with Custom Pivot Model on belongsToMany relationship on Laravel 5.4
I'm trying to figure out how to implement a many to many relationship with a custom intermediate model (pivot table). This is my model:

```<code>banners

 - id
 - title
 - description

banner_regions (Pivot)

 - id
 - region_id
 - banner_id
 - active

regions

 - id
 - name
 - slug
</code>```

Eloquent Models code:

```<code>class Banner extends Model
{
    /**
    * Get all of the regions for the banner.
    */
    public function regions()
    {
        return $this->belongsToMany('App\Region', 'banner_regions')
            ->withPivot('active')
            ->using(BannerRegion::class);
    }
}

class BannerRegion extends Model
{

}

class Region extends Model
{
    /**
    * Get all of the banners for the region.
    */
    public function banners()
    {
        return $this->belongsToMany('App\Banner', 'banner_regions')
            ->withPivot('active')
            ->using(BannerRegion::class);
    }
}
</code>```

Banner Controller code:

```<code>class BannerController extends Controller
{
    protected $model;

    public function __construct(Banner $model)
    {
        $this->model = $model;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $region = $request->region; // region model instance
        // ??
    }
}
</code>```

So, my question here is how to retrieve the banners for a particular region?

答:
SOLUTION

I've changed my code and now it works as expected.

I changed BannerRegion pivot model to be Pivot instead of Model:

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Relations\Pivot;

class BannerRegion extends Pivot
{
    // It is just for casting int values into boolean values.
    // Useful for JSON responses.
    protected $casts = [
        'active' => 'boolean',
        'for_customers' => 'boolean',
    ];
}
</code>```

Banner Model. Nothing to add here, but I've made some changes in order to improve the JSON response, like $appends.

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Banner extends Model
{
    protected $hidden = ['id', 'regions'];

    // Add data from the pivot model
    protected $appends = ['for_customers'];

    public function getForCustomersAttribute()
    {
        // Get the attribute 'for_customers' from the pivot model
        return $this->regions
            ->keyBy('pivot.banner_id')
            ->get($this->id)
            ->pivot
            ->for_customers;
    }

    /**
    * Get all of the regions for the banner.
    *
    */
    public function regions()
    {
        return $this->belongsToMany('App\Region', 'banner_regions')
            ->withPivot('for_customers', 'active')
            ->using('App\BannerRegion');
    }

    /**
    * Scope a query to only include active banners for a specific region.
    *
    * @param \Illuminate\Database\Eloquent\Builder $query
    * @param App\Region $region
    * @return \Illuminate\Database\Eloquent\Builder
    */
    public function scopeFindbyRegionAndActive($query, Region $region)
    {
        return $query->whereHas('regions', function($query) use ($region) {
            return $query->whereRegionId($region->id)->whereActive(true);
        });
    }
}
</code>```

In my Banner controller, I just added:

```<code>    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Region $region)
    {
        return $this->model->findbyRegionAndActive($region)->get();
    }
</code>```

Region param is resolved by Dependency Injection (laravel.com/docs/5.4/routing#route-model-binding).

Finally, my route:

```<code>Route::group(['prefix' => '/regions/{region}'], function()
{
   // Banners
   Route::resource('banners', 'BannerController', ['only' => 'index']);
});
</code>```

The endpoint:

/regions/my-region/banners

The JSON response:

```<code>[
  {
    "title": "a title...",
    "description": "a descritpion...",
    "link": "http://localhost",
    "for_customers": true
  }
]
</code>```

Body:
I'm trying to figure out how to implement a many to many relationship with a custom intermediate model (pivot table). This is my model:

banners

 - id
 - title
 - description

banner_regions (Pivot)

 - id
 - region_id
 - banner_id
 - active

regions

 - id
 - name
 - slug

Eloquent Models code:

class Banner extends Model
{
    /**
    * Get all of the regions for the banner.
    */
    public function regions()
    {
        return $this->belongsToMany('App\Region', 'banner_regions')
            ->withPivot('active')
            ->using(BannerRegion::class);
    }
}

class BannerRegion extends Model
{

}

class Region extends Model
{
    /**
    * Get all of the banners for the region.
    */
    public function banners()
    {
        return $this->belongsToMany('App\Banner', 'banner_regions')
            ->withPivot('active')
            ->using(BannerRegion::class);
    }
}

Banner Controller code:

class BannerController extends Controller
{
    protected $model;

    public function __construct(Banner $model)
    {
        $this->model = $model;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $region = $request->region; // region model instance
        // ??
    }
}

So, my question here is how to retrieve the banners for a particular region?

Body:
SOLUTION

I've changed my code and now it works as expected.

I changed BannerRegion pivot model to be Pivot instead of Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Relations\Pivot;

class BannerRegion extends Pivot
{
    // It is just for casting int values into boolean values.
    // Useful for JSON responses.
    protected $casts = [
        'active' => 'boolean',
        'for_customers' => 'boolean',
    ];
}

Banner Model. Nothing to add here, but I've made some changes in order to improve the JSON response, like $appends.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Banner extends Model
{
    protected $hidden = ['id', 'regions'];

    // Add data from the pivot model
    protected $appends = ['for_customers'];

    public function getForCustomersAttribute()
    {
        // Get the attribute 'for_customers' from the pivot model
        return $this->regions
            ->keyBy('pivot.banner_id')
            ->get($this->id)
            ->pivot
            ->for_customers;
    }

    /**
    * Get all of the regions for the banner.
    *
    */
    public function regions()
    {
        return $this->belongsToMany('App\Region', 'banner_regions')
            ->withPivot('for_customers', 'active')
            ->using('App\BannerRegion');
    }

    /**
    * Scope a query to only include active banners for a specific region.
    *
    * @param \Illuminate\Database\Eloquent\Builder $query
    * @param App\Region $region
    * @return \Illuminate\Database\Eloquent\Builder
    */
    public function scopeFindbyRegionAndActive($query, Region $region)
    {
        return $query->whereHas('regions', function($query) use ($region) {
            return $query->whereRegionId($region->id)->whereActive(true);
        });
    }
}

In my Banner controller, I just added:

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Region $region)
    {
        return $this->model->findbyRegionAndActive($region)->get();
    }

Region param is resolved by Dependency Injection (laravel.com/docs/5.4/routing#route-model-binding).

Finally, my route:

Route::group(['prefix' => '/regions/{region}'], function()
{
   // Banners
   Route::resource('banners', 'BannerController', ['only' => 'index']);
});

The endpoint:

/regions/my-region/banners

The JSON response:

[
  {
    "title": "a title...",
    "description": "a descritpion...",
    "link": "http://localhost",
    "for_customers": true
  }
]


问:
Seaborn plot per column in a pandas dataframe?
I have a little dataframe that looks somewhat like this:

```<code>csv = [{"Oranges" : 12, "Apples" : 4, "Kiwis" : "Yes"}, {"Oranges" : 1, "Apples" : 8, "Kiwis" : "No"}, {"Oranges" : 1, "Apples" : 14, "Kiwis" : "Yes"}, {"Oranges" : 11, "Apples" : 3, "Kiwis" : "No"}, ]
df = pd.DataFrame(csv)
</code>```

Only, it has many more cols. I want to plot a seaborn violin plot per column. If I create the plot per column manually, it would look somewhat like this:

```<code>sns.violinplot(y="Oranges", x="Kiwis", data=df, split=True, inner="quart")
sns.violinplot(y="Apples", x="Kiwis", data=df, split=True, inner="quart")
</code>```

However, and given about 100 cols, I'd like to loop through the dataframe col by col.

I tried building a tiny function like follows:

```<code>def violin(col):
    sns.violinplot(y=col, x="Kiwis", data=df, split=True, inner="quart")
</code>```

My idea is to use apply() to use it for each column...but it doesent work this far.. Any ideas?

答:
You can use difference for column Kiwis and then use apply with selecting columns by subset []:

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

def violin(col):
    sns.violinplot(y=col, x="Kiwis", data=df, split=True, inner="quart")
    plt.figure()

cols = df.columns.difference(['Kiwis'])
df[cols].apply(violin)
</code>```

Body:
I have a little dataframe that looks somewhat like this:

csv = [{"Oranges" : 12, "Apples" : 4, "Kiwis" : "Yes"}, {"Oranges" : 1, "Apples" : 8, "Kiwis" : "No"}, {"Oranges" : 1, "Apples" : 14, "Kiwis" : "Yes"}, {"Oranges" : 11, "Apples" : 3, "Kiwis" : "No"}, ]
df = pd.DataFrame(csv)

Only, it has many more cols. I want to plot a seaborn violin plot per column. If I create the plot per column manually, it would look somewhat like this:

sns.violinplot(y="Oranges", x="Kiwis", data=df, split=True, inner="quart")
sns.violinplot(y="Apples", x="Kiwis", data=df, split=True, inner="quart")

However, and given about 100 cols, I'd like to loop through the dataframe col by col.

I tried building a tiny function like follows:

def violin(col):
    sns.violinplot(y=col, x="Kiwis", data=df, split=True, inner="quart")

My idea is to use apply() to use it for each column...but it doesent work this far.. Any ideas?

Body:
You can use difference for column Kiwis and then use apply with selecting columns by subset []:

import matplotlib.pyplot as plt

def violin(col):
    sns.violinplot(y=col, x="Kiwis", data=df, split=True, inner="quart")
    plt.figure()

cols = df.columns.difference(['Kiwis'])
df[cols].apply(violin)


问:
forkjoin returns no results
I'm using forkJoin to combine the results of two firebase requests

Both requests complete and log within the console, but the map function for the forkJoin itself does not fire and hence no results are returned to the application

```<code>public initGroup(groupname, username){
  console.log(groupname, username)//This logs
  return Observable.forkJoin([
      this.getGroup(groupname, username),
      this.groupMembers(username, groupname),
    ])
    .map((data)=>{
      console.log(data)//This does not log
      this.group = data;
      return this.group
    })
}
</code>```

And for the individual functions:

```<code>public getGroup(groupname, username){
  return (this._af.database.object('/groups/'+groupname) as FirebaseObjectObservable<any>)
      .map((group)=>{
       console.log(group)//This logs
       return group
  })

}
 public groupMembers(username, groupname){
  return  this.afService.getUserItems(groupname)
  .map((users:UserInfo[])=>{
    console.log(users)//This logs
    return users
  })
}
</code>```

I subscribe within the component:

```<code>let conn = this.groupService.initGroup(groupname, username)
                  .subscribe((data)=>{
                  console.log(data)//Does not log
                  ......
                })
</code>```

答:
It turns out forkJoin just doesn't work with firebase observables,

When I updated to

```<code>public initGroup(groupname, username){
  return Observable.combineLatest([
      this.getGroup(groupname, username),
      this.groupMembers(username, groupname)

  ])
    .map((data)=>{
      console.log(data)//This now logs
      this.group = data;
      return this.group
    })

}
</code>```

combineLatest made it work as expected

Title: forkjoin returns no results

Body:
I'm using forkJoin to combine the results of two firebase requests

Both requests complete and log within the console, but the map function for the forkJoin itself does not fire and hence no results are returned to the application

public initGroup(groupname, username){
  console.log(groupname, username)//This logs
  return Observable.forkJoin([
      this.getGroup(groupname, username),
      this.groupMembers(username, groupname),
    ])
    .map((data)=>{
      console.log(data)//This does not log
      this.group = data;
      return this.group
    })
}

And for the individual functions:

public getGroup(groupname, username){
  return (this._af.database.object('/groups/'+groupname) as FirebaseObjectObservable<any>)
      .map((group)=>{
       console.log(group)//This logs
       return group
  })

}
 public groupMembers(username, groupname){
  return  this.afService.getUserItems(groupname)
  .map((users:UserInfo[])=>{
    console.log(users)//This logs
    return users
  })
}

I subscribe within the component:

let conn = this.groupService.initGroup(groupname, username)
                  .subscribe((data)=>{
                  console.log(data)//Does not log
                  ......
                })

Body:
It turns out forkJoin just doesn't work with firebase observables,

When I updated to

public initGroup(groupname, username){
  return Observable.combineLatest([
      this.getGroup(groupname, username),
      this.groupMembers(username, groupname)

  ])
    .map((data)=>{
      console.log(data)//This now logs
      this.group = data;
      return this.group
    })

}

combineLatest made it work as expected


问:
Why do I have ClassNotFoundException on my app?

Background

Not so long ago, Google has changed the Google Play Console, so that crashes are automatically being reported as soon as they occur, having it as part of what they call "Android Vital".

From this day, I got many crash reports that I've decided to fix for my app.

The problem

Among some bugs I've fixed (and one that I haven't, here), there is another quite common crash, with this crash log or similar:

```<code>java.lang.RuntimeException:
  at android.app.LoadedApk.makeApplication(LoadedApk.java:572)
  at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4768)
  at android.app.ActivityThread.access$1500(ActivityThread.java:176)
  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1498)
  at android.os.Handler.dispatchMessage(Handler.java:111)
  at android.os.Looper.loop(Looper.java:194)
  at android.app.ActivityThread.main(ActivityThread.java:5576)
  at java.lang.reflect.Method.invoke(Native Method:0)
  at java.lang.reflect.Method.invoke(Method.java:372)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:956)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:751)
Caused by: java.lang.ClassNotFoundException:
  at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
  at android.app.Instrumentation.newApplication(Instrumentation.java:984)
  at android.app.LoadedApk.makeApplication(LoadedApk.java:567)
</code>```

This crash seem to be affecting various Android versions and devices, yet there aren't much clues about how to fix it:

What I've tried

The only thing I've found to solve such a crash, is by using multi-dex, as written here.

Seeing that even though my app is very small and barely using third party libraries (hence doesn't even get near the 64K methods count), and that multi-dex is not even needed on Android 5.x and above, I was still curious if this would help, but in just one day of trying it, it actually caused the crash to occur more frequently:

So I quickly stopped using it, and came back to without using it.

The questions

Why does it occur?

Is there any way to avoid this? Will avoiding extending Application class help?

How common is it for other apps?

Why would multi-dexing actually cause more issues with it?

From users point of view, do users who have this issue - always have it? Does specific devices or Android versions have this issue? Does a restart of the app or re-installing of it help? What exactly is the experience the users get from this?

答:
I managed to decrease occurrences of it by adding these lines to my Proguard file:

```<code>-keep class android.app.Application
-keep class <<MyPackage>>.MyApplication
</code>```

that may be shortened to:

```<code>-keep class * extends android.app.Application
</code>```

According to android source code I suppose it fixed the first issue.

I also updated all my libs to the last versions (Google Play Services 11.0.2, support lib 25.4.0) that should have fixed the second one.

UPDATE: it doesn't fix the issue completely. I got far less occurrences but there are still some.

Body:
Background

Not so long ago, Google has changed the Google Play Console, so that crashes are automatically being reported as soon as they occur, having it as part of what they call "Android Vital".

From this day, I got many crash reports that I've decided to fix for my app.

The problem

Among some bugs I've fixed (and one that I haven't, here), there is another quite common crash, with this crash log or similar:

java.lang.RuntimeException:
  at android.app.LoadedApk.makeApplication(LoadedApk.java:572)
  at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4768)
  at android.app.ActivityThread.access$1500(ActivityThread.java:176)
  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1498)
  at android.os.Handler.dispatchMessage(Handler.java:111)
  at android.os.Looper.loop(Looper.java:194)
  at android.app.ActivityThread.main(ActivityThread.java:5576)
  at java.lang.reflect.Method.invoke(Native Method:0)
  at java.lang.reflect.Method.invoke(Method.java:372)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:956)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:751)
Caused by: java.lang.ClassNotFoundException:
  at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
  at android.app.Instrumentation.newApplication(Instrumentation.java:984)
  at android.app.LoadedApk.makeApplication(LoadedApk.java:567)

This crash seem to be affecting various Android versions and devices, yet there aren't much clues about how to fix it:

What I've tried

The only thing I've found to solve such a crash, is by using multi-dex, as written here.

Seeing that even though my app is very small and barely using third party libraries (hence doesn't even get near the 64K methods count), and that multi-dex is not even needed on Android 5.x and above, I was still curious if this would help, but in just one day of trying it, it actually caused the crash to occur more frequently:

So I quickly stopped using it, and came back to without using it.

The questions

Why does it occur?

Is there any way to avoid this? Will avoiding extending Application class help?

How common is it for other apps?

Why would multi-dexing actually cause more issues with it?

From users point of view, do users who have this issue - always have it? Does specific devices or Android versions have this issue? Does a restart of the app or re-installing of it help? What exactly is the experience the users get from this?

Body:
I managed to decrease occurrences of it by adding these lines to my Proguard file:

-keep class android.app.Application
-keep class <<MyPackage>>.MyApplication

that may be shortened to:

-keep class * extends android.app.Application

According to android source code I suppose it fixed the first issue.

I also updated all my libs to the last versions (Google Play Services 11.0.2, support lib 25.4.0) that should have fixed the second one.

UPDATE: it doesn't fix the issue completely. I got far less occurrences but there are still some.


问:
Cant find file to import
I have a file system as follows:

```<code>/
- website/
-   - server.py
- common.py
</code>```

When in /, i try to run:   python website/server.py but it shows an error when attempting to from common import my_func saying:

```<code>ImportError: No module named common
</code>```

Is there a way to denote a file as a module?  The issue I am running into is that while working in PyCharm it understands the python files correctly and functions as designed, but when running them in the command prompt in a VM it doesnt understand.  I was running the python from / as you can see, thinking it would use that as the scope, but it seems like that isnt working.

I was not given any more information from the debugger or logs. What am I doing wrong?

Edit  I tried doing the following as per Joao's request.   python ./website/server.py and returned the following line still, which is the same error received above.

```<code>Traceback (most recent call last):
  File "./website/server.py", line 3, in <module>
    from common import my_func
Import Error: No module named common
</code>```

答:
You're trying to import from the parent folder.

Add the following code before from common import my_func will do the trick.

```<code>import sys

#appending parent directory into the path
sys.path.append('..')
</code>```

Title: Cant find file to import

Body:
I have a file system as follows:

/
- website/
-   - server.py
- common.py

When in /, i try to run:   python website/server.py but it shows an error when attempting to from common import my_func saying:

ImportError: No module named common

Is there a way to denote a file as a module?  The issue I am running into is that while working in PyCharm it understands the python files correctly and functions as designed, but when running them in the command prompt in a VM it doesnt understand.  I was running the python from / as you can see, thinking it would use that as the scope, but it seems like that isnt working.

I was not given any more information from the debugger or logs. What am I doing wrong?

Edit  I tried doing the following as per Joao's request.   python ./website/server.py and returned the following line still, which is the same error received above.

Traceback (most recent call last):
  File "./website/server.py", line 3, in <module>
    from common import my_func
Import Error: No module named common

Body:
You're trying to import from the parent folder.

Add the following code before from common import my_func will do the trick.

import sys

#appending parent directory into the path
sys.path.append('..')


问:
SQL sum error in ORACLE
I am trying to make a simple dummy database, but I encountered a problem while trying to query this:

```<code>SELECT
    k.id_customer,
    k.name_customer,
    k.lastname_customer,
    r.date_bill,
    sum(p.price_product*us.quantity) AS TOTAL_PRICE
FROM
    product p,
    bill r,
    item us,
    customer k
WHERE
    k.id_customer=1
    AND k.id_customer=r.customer_ID_customer
    AND us.bill_ID_bill=r.ID_bill
    AND p.ID_product=us.product_ID_product
GROUP BY k.id_customer
</code>```

ORACLE states out the following error:

ORA-00979: not a GROUP BY expression

I have tried doing the same query only with the sum and it worked, but I'd like to add the name of the customer and the date on the bill.

答:
All the expressions that are not aggregate functions must be part of the GROUP BY. Try with:

```<code>SELECT
    k.id_customer,
    k.name_customer,
    k.lastname_customer,
    r.date_bill,
    sum(p.price_product*us.quantity) AS TOTAL_PRICE
FROM
    product p,
    bill r,
    item us,
    customer k
WHERE
    k.id_customer=1
    AND k.id_customer=r.customer_ID_customer
    AND us.bill_ID_bill=r.ID_bill
    AND p.ID_product=us.product_ID_product
GROUP BY k.id_customer,
    k.name_customer,
    k.lastname_customer,
    r.date_bill
</code>```

Also, consider not to use that old syntax for your JOINS, it's more likely to inadvertently introduce CROSS JOINs. It would be something like:

```<code>...
FROM table1
  INNER JOIN table2
    ON (table1.column1 = table2.column2)
</code>```

Title: SQL sum error in ORACLE

Body:
I am trying to make a simple dummy database, but I encountered a problem while trying to query this:

SELECT
    k.id_customer,
    k.name_customer,
    k.lastname_customer,
    r.date_bill,
    sum(p.price_product*us.quantity) AS TOTAL_PRICE
FROM
    product p,
    bill r,
    item us,
    customer k
WHERE
    k.id_customer=1
    AND k.id_customer=r.customer_ID_customer
    AND us.bill_ID_bill=r.ID_bill
    AND p.ID_product=us.product_ID_product
GROUP BY k.id_customer

ORACLE states out the following error:

ORA-00979: not a GROUP BY expression

I have tried doing the same query only with the sum and it worked, but I'd like to add the name of the customer and the date on the bill.

Body:
All the expressions that are not aggregate functions must be part of the GROUP BY. Try with:

SELECT
    k.id_customer,
    k.name_customer,
    k.lastname_customer,
    r.date_bill,
    sum(p.price_product*us.quantity) AS TOTAL_PRICE
FROM
    product p,
    bill r,
    item us,
    customer k
WHERE
    k.id_customer=1
    AND k.id_customer=r.customer_ID_customer
    AND us.bill_ID_bill=r.ID_bill
    AND p.ID_product=us.product_ID_product
GROUP BY k.id_customer,
    k.name_customer,
    k.lastname_customer,
    r.date_bill

Also, consider not to use that old syntax for your JOINS, it's more likely to inadvertently introduce CROSS JOINs. It would be something like:

...
FROM table1
  INNER JOIN table2
    ON (table1.column1 = table2.column2)


问:
Java implementation of Floyd's algorithm doesn't work for undirected graphs
I got the following implementation for Floyd's algorithm, which is used to find shortest paths in a weighted graph. The result is a matrix of the shortest paths between all vertices:

```<code>class FloydWarshall {

static int graph [][] = {   {0, 5, 3},
                            {5, 0, 0},
                            {3, 0, 0}
                        };

public static void main(String args[]) {

    int N=graph.length;
    int y, x, j;

    for (y = 0; y < N; y++)
        for (x = 0; x < N; x++)
            if (graph[x][y] > 0)
                for (j = 0; j < N; j++)
                    if (graph[y][j] > 0)
                        if ((graph[x][j] == 0) || (graph[x][y] + graph[y][j] < graph[x][j]))
                            graph[x][j] = graph[x][y]+graph[y][j];
    for (y = 0; y < N; y++) {
        for (x = 0; x < N; x++)
            System.out.print(graph[y][x] < 0 ? "  "+graph[y][x] : " "+graph[y][x]);
        System.out.println();
    }
}
</code>```

}

The weird thing is even though it is working, it doesn't calculate the right distance from a vertice to itself (which should be 0) for undirected graphs. For example the following graph:

```<code>{0, 5, 3}
{5, 0, 0}
{3, 0, 0}
</code>```

gets the output:

```<code>6 5 3
5 10 8
3 8 6
</code>```

instead of:

```<code>0 5 3
5 0 8
3 8 0
</code>```

I assume there is just a stupid mistake in the code but I'm unable to find it so I am thankful for any help.

答:
The problem is the following: You are using the value 0 in two opposite ways in your implementation:

To signal that there exists no edge between x and y, you set graph[x][y] to 0, as witnessed by the checks if (graph[x][y] > 0), if (graph[y][j] > 0)

To signal distance 0 between two nodes.

So your resulting diagonal entries actually tell you: What is the shortest non-trivial cycle involving my vertex?

I would recommend that you either use a very large number (Integer.MAX_VALUE, watch out for overflows!) to denote non-edges or better: store the adjacency information in a completely separate matrix.

Body:
I got the following implementation for Floyd's algorithm, which is used to find shortest paths in a weighted graph. The result is a matrix of the shortest paths between all vertices:

class FloydWarshall {

static int graph [][] = {   {0, 5, 3},
                            {5, 0, 0},
                            {3, 0, 0}
                        };

public static void main(String args[]) {

    int N=graph.length;
    int y, x, j;

    for (y = 0; y < N; y++)
        for (x = 0; x < N; x++)
            if (graph[x][y] > 0)
                for (j = 0; j < N; j++)
                    if (graph[y][j] > 0)
                        if ((graph[x][j] == 0) || (graph[x][y] + graph[y][j] < graph[x][j]))
                            graph[x][j] = graph[x][y]+graph[y][j];
    for (y = 0; y < N; y++) {
        for (x = 0; x < N; x++)
            System.out.print(graph[y][x] < 0 ? "  "+graph[y][x] : " "+graph[y][x]);
        System.out.println();
    }
}

}

The weird thing is even though it is working, it doesn't calculate the right distance from a vertice to itself (which should be 0) for undirected graphs. For example the following graph:

{0, 5, 3}
{5, 0, 0}
{3, 0, 0}

gets the output:

6 5 3
5 10 8
3 8 6

instead of:

0 5 3
5 0 8
3 8 0

I assume there is just a stupid mistake in the code but I'm unable to find it so I am thankful for any help.


答:
From my understanding you need to include all expressions from the SELECT clause that are not a group function, so the following should work.</p>

```<code>    SELECT k.id_customer,k.name_customer,k.lastname_customer,r.date_bill,sum(p.price_product*us.quantity) AS TOTAL_PRICE
    FROM product p,bill r,item us,customer k
    WHERE k.id_customer=1 AND k.id_customer=r.customer_ID_customer AND us.bill_ID_bill=r.ID_bill AND p.ID_product=us.product_ID_product
    GROUP BY k.id_customer,
k.name_customer,
k.lastname_customer,
r.date_bill
</code>```

Title: SQL sum error in ORACLE

Body:
From my understanding you need to include all expressions from the SELECT clause that are not a group function, so the following should work.

    SELECT k.id_customer,k.name_customer,k.lastname_customer,r.date_bill,sum(p.price_product*us.quantity) AS TOTAL_PRICE
    FROM product p,bill r,item us,customer k
    WHERE k.id_customer=1 AND k.id_customer=r.customer_ID_customer AND us.bill_ID_bill=r.ID_bill AND p.ID_product=us.product_ID_product
    GROUP BY k.id_customer,
k.name_customer,
k.lastname_customer,
r.date_bill


问:
Get the array index of duplicates
In a JavaScript array how can I get the index of duplicate strings?

Example:

```<code>MyArray = ["abc","def","abc"]; //----> return 0,2("abc");
</code>```

Another example:

```<code>My Array = ["abc","def","abc","xyz","def","abc"]
//----> return 0,2,5("abc") and 1,4("def");
</code>```

I have no idea how to do this.
Thanks in advance for your help!

答:
This covers finding the indices efficiently:</p>

```<code>var inputArray = [1, 2, 3, 4, 5, 6, 6, 7, 8, 9];
var encounteredIndices = {};

for(var i = 0; i < inputArray.length; i++)
  if (encounteredIndices[inputArray[i]])
    console.log(i); // Or add to some array if you wish
  else
    encounteredIndices[inputArray[i]] = 1;
</code>```

Title: Get the array index of duplicates

Body:
In a JavaScript array how can I get the index of duplicate strings?

Example:

MyArray = ["abc","def","abc"]; //----> return 0,2("abc");

Another example:

My Array = ["abc","def","abc","xyz","def","abc"]
//----> return 0,2,5("abc") and 1,4("def");

I have no idea how to do this.
Thanks in advance for your help!

Body:
This covers finding the indices efficiently:

var inputArray = [1, 2, 3, 4, 5, 6, 6, 7, 8, 9];
var encounteredIndices = {};

for(var i = 0; i < inputArray.length; i++)
  if (encounteredIndices[inputArray[i]])
    console.log(i); // Or add to some array if you wish
  else
    encounteredIndices[inputArray[i]] = 1;

ContentLicense: CC BY-SA 4.0


问:
Spring Business Object Modeling
We're building a service that can handle posts which are proxied from a web app or a dialer application. Users can confirm or cancel appointments via email, SMS, phone calls, or app.

The complicating factor is that with app and email you get a discrete "Confirm" or "Cancel" action, whereas with phone calls you get a digit pressed and with SMS you get a keyword, like "CONFIRM" or "C". (Further complicating is that to different accounts, keywords or digits will resolve to different actions.)

Here's my question. We receive a post and serialize it into a UserInteraction POJO that contains all relevant info and which is persisted to the database. Unfortunately, this POJO doesn't contain the abstraction of the discrete action the user is taking as far as the business logic is concerned.

Should I add to the POJO something like:

```<code>@Transient
private ResponseType responseType;
</code>```

or should this additional attribute pass through all the methods in its lifecycle as a separate argument?

Method signatures would be like this if I was to keep the ResponseType separate:

```<code>public GenericResponse handleConfirmation(UserInteraction userInteraction, AppointmentInfo apptInfo, ResponseType responseType)
</code>```

答: If refactoring cost is concerned then using a transient property in POJO seems fair enough. But without knowing other surrounding factors and API dependencies its not easy to differentiate the effects of the two solutions. </p>

Title: Spring Business Object Modeling

Body:
We're building a service that can handle posts which are proxied from a web app or a dialer application. Users can confirm or cancel appointments via email, SMS, phone calls, or app.

The complicating factor is that with app and email you get a discrete "Confirm" or "Cancel" action, whereas with phone calls you get a digit pressed and with SMS you get a keyword, like "CONFIRM" or "C". (Further complicating is that to different accounts, keywords or digits will resolve to different actions.)

Here's my question. We receive a post and serialize it into a UserInteraction POJO that contains all relevant info and which is persisted to the database. Unfortunately, this POJO doesn't contain the abstraction of the discrete action the user is taking as far as the business logic is concerned.

Should I add to the POJO something like:

@Transient
private ResponseType responseType;

or should this additional attribute pass through all the methods in its lifecycle as a separate argument?

Method signatures would be like this if I was to keep the ResponseType separate:

public GenericResponse handleConfirmation(UserInteraction userInteraction, AppointmentInfo apptInfo, ResponseType responseType)


问:
How to display "Registered Successfull" Message in android
Any one can tell me how to display this Message in Android.
Registered Successfully
Click To view Image</p>

答:
The class used to display temporary messages in android is called Toast.

The method to display a toast is as follows :-

```<code>Toast.makeText(context,"Your message to display",Toast.LENGTH_LONG).show();
</code>```

Read up more on Toast here here. And to add images and customise the toast ( as shown in your image ) , you can refer to this answer.

Body:
The class used to display temporary messages in android is called Toast.

The method to display a toast is as follows :-

Toast.makeText(context,"Your message to display",Toast.LENGTH_LONG).show();

Read up more on Toast here here. And to add images and customise the toast ( as shown in your image ) , you can refer to this answer.


问:
Half responsive css layout (depends on rest of width and height)

Hello I need an advice from you. I have 3 divs - one with absolute size X and Y, and I want 2 others to be depends of rest of window width and height.
I want achieve sticked elements too (margins, or padding 0?)

I'm doing this now ith jquery and setwidth, setheight, but this doesn't give good effects.

```<code>$("#console").height(window.innerHeight - gameCanvas.height - 19);
$("#menu").height(gameCanvas.height);
$("#menu").width(window.innerWidth - gameCanvas.width - 6);
</code>```

Sorry but I'm new in CSS and cant search good answer for my question

#menu is right up element

#console is down element

#gameCanvas is up left element

Please help me, how can I achieve it?
Can I achieve it only with css?

答:
This can very likely be done with CSS alone. See if this works for you:

```<code>#gameCanvas{
  width:1024px;
  height:512px;
  float:left;
}
#menu{
  height:512px;
}
#console{
  clear:both;
  height:calc(100vh - 512px);
}
</code>```

I used calc and vh to set the height of #console. That part might have to be done with javascript to ensure an excellent browser support. The above code should work in 90% of the browsers.

Body:
Hello I need an advice from you. I have 3 divs - one with absolute size X and Y, and I want 2 others to be depends of rest of window width and height.
I want achieve sticked elements too (margins, or padding 0?)

I'm doing this now ith jquery and setwidth, setheight, but this doesn't give good effects.

$("#console").height(window.innerHeight - gameCanvas.height - 19);
$("#menu").height(gameCanvas.height);
$("#menu").width(window.innerWidth - gameCanvas.width - 6);

Sorry but I'm new in CSS and cant search good answer for my question

#menu is right up element

#console is down element

#gameCanvas is up left element

Please help me, how can I achieve it?
Can I achieve it only with css?

Body:
This can very likely be done with CSS alone. See if this works for you:

#gameCanvas{
  width:1024px;
  height:512px;
  float:left;
}
#menu{
  height:512px;
}
#console{
  clear:both;
  height:calc(100vh - 512px);
}

I used calc and vh to set the height of #console. That part might have to be done with javascript to ensure an excellent browser support. The above code should work in 90% of the browsers.


问:
Windows Forms Application Performance
My app has many controls on its surface, and more are added dynamically at runtime.

Although i am using tabs to limit the number of controls shown, and double-buffering too, it still flickers and stutters when it has to redraw (resize, maximize, etc).

What are your tips and tricks to improve WinForms app performance?

答:
Are you making good use of SuspendLayout() and ResumeLayout()?

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.suspendlayout(VS.80).aspx

OwnerDisplayName: Shuft

ContentLicense: CC BY-SA 2.5

Title: Windows Forms Application Performance

OwnerDisplayName: Jim Harte


问:
How do I project lines dynamically on to 3D terrain?
I'm working on a game in XNA for Xbox 360.  The game has 3D terrain with a collection of static objects that are connected by a graph of links.  I want to draw the links connecting the objects as lines projected on to the terrain.  I also want to be able to change the colors etc. of links as players move their selection around, though I don't need the links to move.  However, I'm running into issues making this work correctly and efficiently.

Some ideas I've had are:

1) Render quads to a separate render target, and use the texture as an overlay on top of the terrain. I currently have this working, generating the texture only for the area currently visible to the camera to minimize aliasing.  However, I'm still getting aliasing issues -- the lines look jaggy, and the game chugs frequently when moving the camera EDIT: it chugs all the time, I just don't have a frame rate counter on Xbox so I only notice it when things move.

2) Bake the lines into a texture ahead of time.  This could increase performance, but makes the aliasing issue worse.  Also, it doesn't let me dynamically change the properties of the lines without much munging.

3) Make geometry that matches the shape of the terrain by tessellating the line-quads over the terrain.  This option seems like it could help, but I'm unsure if I should spend time trying it out if there's an easier way.

Is there some magical way to do this that I haven't thought of? Is one of these paths the best when done correctly?

答: Does XNA have a shadowing library? If so, yo could just pretend the lines are shadows.</p>

OwnerDisplayName: Neil Williams

LastEditorDisplayName: Neil Williams

OwnerDisplayName: Shalmanese


问:
How to move focus when error in bound field?
I have VB.Net Application with some fields bound to a datatable.

Here is my code :

```<code>Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Me.DxErrorProvider1 = New DevExpress.XtraEditors.DXErrorProvider.DXErrorProvider(Me.components)
    Dim DT As DataTable = GetDT()
    Me.TextEdit1.DataBindings.Add("EditValue", DT, "C1", True, DataSourceUpdateMode.OnValidation, "")
End Sub

Function GetDT() As DataTable
    Dim DT As New DataTable

    Dim i As Integer = 0
    DT.Columns.Add(New DataColumn("C1", i.GetType))

    Dim R As DataRow = DT.NewRow
    R.Item(0) = 15
    DT.Rows.Add(R)

    Return DT
End Function
</code>```

When the user types a wrong value on the field. The focus can not move anymore.

The full code contains actually multiple fields and I would like to allow the user to be able to move the next field even if there is wrong value. A red icon shows, so he may want to correct it later.

Is there anyway to achieve that please ?

Thanks.

答:
I was thinking arround and i figured this get-through, i hope it helps some how.

```<code>        AddHandler TextEdit1.LostFocus, Sub()
                                            If TextEdit1.ErrorText <> "Focus released" And TextEdit1.ErrorText <> ""  Then
                                                TextEdit1.DataBindings(0).DataSourceUpdateMode = DataSourceUpdateMode.Never
                                                DxErrorProvider1.SetError(TextEdit1, "Focus released")
                                            Else
                                                DxErrorProvider1.SetError(TextEdit1, "")
                                                TextEdit1.DataBindings(0).DataSourceUpdateMode = DataSourceUpdateMode.OnPropertyChanged
                                            End If
                                        End Sub
</code>```

Also you can add TextEdit1.BackColor = Color.red or TextEdit1.BackColor = Color.Empty in either of both IF segments

Body:
I have VB.Net Application with some fields bound to a datatable.

Here is my code :

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Me.DxErrorProvider1 = New DevExpress.XtraEditors.DXErrorProvider.DXErrorProvider(Me.components)
    Dim DT As DataTable = GetDT()
    Me.TextEdit1.DataBindings.Add("EditValue", DT, "C1", True, DataSourceUpdateMode.OnValidation, "")
End Sub

Function GetDT() As DataTable
    Dim DT As New DataTable

    Dim i As Integer = 0
    DT.Columns.Add(New DataColumn("C1", i.GetType))

    Dim R As DataRow = DT.NewRow
    R.Item(0) = 15
    DT.Rows.Add(R)

    Return DT
End Function

When the user types a wrong value on the field. The focus can not move anymore.

The full code contains actually multiple fields and I would like to allow the user to be able to move the next field even if there is wrong value. A red icon shows, so he may want to correct it later.

Is there anyway to achieve that please ?

Thanks.

Body:
I was thinking arround and i figured this get-through, i hope it helps some how.

        AddHandler TextEdit1.LostFocus, Sub()
                                            If TextEdit1.ErrorText <> "Focus released" And TextEdit1.ErrorText <> ""  Then
                                                TextEdit1.DataBindings(0).DataSourceUpdateMode = DataSourceUpdateMode.Never
                                                DxErrorProvider1.SetError(TextEdit1, "Focus released")
                                            Else
                                                DxErrorProvider1.SetError(TextEdit1, "")
                                                TextEdit1.DataBindings(0).DataSourceUpdateMode = DataSourceUpdateMode.OnPropertyChanged
                                            End If
                                        End Sub

Also you can add TextEdit1.BackColor = Color.red or TextEdit1.BackColor = Color.Empty in either of both IF segments


问:
What is the minimum time slot for an Azure function wrt calculating costs
What is the minimum time slot for an Azure function wrt calculating costs

The online calculator has a de minimus of 1 second, so is any run at least one?

答:
The minimum time slot is 100ms, so the calculation is performed on the sub-second consumption amount (execution duration).

Unfortunately, the pricing calculator is currently limited to whole seconds, but I have passed this feedback on to the team that owns it so this limitation can be addressed.


问:
AutoMocker Question
I'm trying to test my controllers, but each of them have a dependency on a service which has a dependency on a repository.  I have the following code...

```<code>Mock.Get(controller.Get<ServiceInterface>())
            .Setup(s => s.GetData())
            .Returns(FakeData.Create<Entity>(25));
</code>```

I keep getting an error related to the ServiceInterface concrete class not having a default instance for its repository (injected).  I'm trying to avoid creating a FakeService, but its looking like that's what I'm going to have to do.  Can anyone offer some suggestions?

答:
My response to this question shows how you can program your services to fulfill an interface, use that interface as a dependency, and then mock the service to help you in unit testing.

Edit

Not having had any experience with the MoqAutoMocker, my advice is somewhat limited. But I would begin by attempting to use Moq directly, and see if that's causing you any trouble.

```<code>var serviceMock = new Mock<IService>();
serviceMock.Setup(r => r.GetData())
    .Returns(FakeData.Create<Entity>(25));
var controller = new MyController(serviceMock.Object);
</code>```

Once you've ensured that this works, you can introduce the auto-mocking aspect of it:

```<code>var autoMocker = new MoqAutoMocker<MyController>();
Mock.Get(autoMocker.Get<IService>()).Setup(r => r.GetData())
    .Returns(FakeData.Create<Entity>(25));
MyController controller = autoMocker.ClassUnderTest;
</code>```

Title: AutoMocker Question

Body:
I'm trying to test my controllers, but each of them have a dependency on a service which has a dependency on a repository.  I have the following code...

Mock.Get(controller.Get<ServiceInterface>())
            .Setup(s => s.GetData())
            .Returns(FakeData.Create<Entity>(25));

I keep getting an error related to the ServiceInterface concrete class not having a default instance for its repository (injected).  I'm trying to avoid creating a FakeService, but its looking like that's what I'm going to have to do.  Can anyone offer some suggestions?

Body:
My response to this question shows how you can program your services to fulfill an interface, use that interface as a dependency, and then mock the service to help you in unit testing.

Edit

Not having had any experience with the MoqAutoMocker, my advice is somewhat limited. But I would begin by attempting to use Moq directly, and see if that's causing you any trouble.

var serviceMock = new Mock<IService>();
serviceMock.Setup(r => r.GetData())
    .Returns(FakeData.Create<Entity>(25));
var controller = new MyController(serviceMock.Object);

Once you've ensured that this works, you can introduce the auto-mocking aspect of it:

var autoMocker = new MoqAutoMocker<MyController>();
Mock.Get(autoMocker.Get<IService>()).Setup(r => r.GetData())
    .Returns(FakeData.Create<Entity>(25));
MyController controller = autoMocker.ClassUnderTest;


问:
Thousands of strange crashes in new Google Play Console version
The ANRs & crashes section of the Google Play Console has been recently updated to display more ANRs & crashes (automatically collected from users that have opted in).

I found a lot of strange new crashes, on various Android versions and devices:

1) The most common (thousands of occurrences a week), a ClassNotFoundException without any class name:

```<code>java.lang.RuntimeException:
    at android.app.LoadedApk.makeApplication(LoadedApk.java:509)
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4657)
    at android.app.ActivityThread.access$1400(ActivityThread.java:159)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1376)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:176)
    at android.app.ActivityThread.main(ActivityThread.java:5419)
    at java.lang.reflect.Method.invokeNative(Method.java:0)
    at java.lang.reflect.Method.invoke(Method.java:525)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
    at dalvik.system.NativeStart.main(NativeStart.java:0)
Caused by: java.lang.ClassNotFoundException:
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:64)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
    at android.app.Instrumentation.newApplication(Instrumentation.java:992)
    at android.app.LoadedApk.makeApplication(LoadedApk.java:504)
</code>```

2) The most common (hundreds), a RuntimeException that seems related to admob (com.google.android.gms.ads.internal.*):

```<code>java.lang.RuntimeException:
  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377)
  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2429)
  at android.app.ActivityThread.access$800(ActivityThread.java:151)
  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1342)
  at android.os.Handler.dispatchMessage(Handler.java:110)
  at android.os.Looper.loop(Looper.java:193)
  at android.app.ActivityThread.main(ActivityThread.java:5333)
  at java.lang.reflect.Method.invokeNative(Method.java:0)
  at java.lang.reflect.Method.invoke(Method.java:515)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
  at dalvik.system.NativeStart.main(NativeStart.java:0)
Caused by: java.lang.IllegalStateException:
  at com.google.android.gms.ads.internal.zzj.a(zzj.java:322)
  at com.google.android.gms.ads.internal.client.ak.onTransact(ak.java:98)
  at android.os.Binder.transact(Binder.java:361)
  at com.google.android.gms.internal.zzet$zza$zza.zza(zzet.java:0)
  at <OR>.zza(zzet.java:0)
  at <OR>.zza(zzet.java:0)
 ...
  at <OR>.zza(zzet.java:0)
  ...
</code>```

Notes:

the stack trace is very long and contains a lot of methods with , line number is always 0

the app uses Proguard

lib folder architecture

3) a bunch of other exceptions with same kind of traces (a lot of methods with  and line number 0)

My questions are:

Do you experience similar reports?

Are these reports really relevant? I mean, I should receive more direct user feedbacks. Is it possible, they are "silent" crashes?

Are there any know issues / fixes?

Body:
The ANRs & crashes section of the Google Play Console has been recently updated to display more ANRs & crashes (automatically collected from users that have opted in).

I found a lot of strange new crashes, on various Android versions and devices:

1) The most common (thousands of occurrences a week), a ClassNotFoundException without any class name:

java.lang.RuntimeException:
    at android.app.LoadedApk.makeApplication(LoadedApk.java:509)
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4657)
    at android.app.ActivityThread.access$1400(ActivityThread.java:159)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1376)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:176)
    at android.app.ActivityThread.main(ActivityThread.java:5419)
    at java.lang.reflect.Method.invokeNative(Method.java:0)
    at java.lang.reflect.Method.invoke(Method.java:525)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
    at dalvik.system.NativeStart.main(NativeStart.java:0)
Caused by: java.lang.ClassNotFoundException:
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:64)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
    at android.app.Instrumentation.newApplication(Instrumentation.java:992)
    at android.app.LoadedApk.makeApplication(LoadedApk.java:504)

2) The most common (hundreds), a RuntimeException that seems related to admob (com.google.android.gms.ads.internal.*):

java.lang.RuntimeException:
  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377)
  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2429)
  at android.app.ActivityThread.access$800(ActivityThread.java:151)
  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1342)
  at android.os.Handler.dispatchMessage(Handler.java:110)
  at android.os.Looper.loop(Looper.java:193)
  at android.app.ActivityThread.main(ActivityThread.java:5333)
  at java.lang.reflect.Method.invokeNative(Method.java:0)
  at java.lang.reflect.Method.invoke(Method.java:515)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
  at dalvik.system.NativeStart.main(NativeStart.java:0)
Caused by: java.lang.IllegalStateException:
  at com.google.android.gms.ads.internal.zzj.a(zzj.java:322)
  at com.google.android.gms.ads.internal.client.ak.onTransact(ak.java:98)
  at android.os.Binder.transact(Binder.java:361)
  at com.google.android.gms.internal.zzet$zza$zza.zza(zzet.java:0)
  at <OR>.zza(zzet.java:0)
  at <OR>.zza(zzet.java:0)
 ...
  at <OR>.zza(zzet.java:0)
  ...

Notes:

the stack trace is very long and contains a lot of methods with , line number is always 0

the app uses Proguard

lib folder architecture

3) a bunch of other exceptions with same kind of traces (a lot of methods with  and line number 0)

My questions are:

Do you experience similar reports?

Are these reports really relevant? I mean, I should receive more direct user feedbacks. Is it possible, they are "silent" crashes?

Are there any know issues / fixes?

Body:
I managed to decrease occurrences of it by adding these lines to my Proguard file:

-keep class android.app.Application
-keep class <<MyPackage>>.MyApplication

that may be shortened to:

-keep class * extends android.app.Application

According to android source code I suppose it fixed the first issue.

I also updated all my libs to the last versions (Google Play Services 11.0.2, support lib 25.4.0) that should have fixed the second one.

UPDATE: it doesn't fix the issue completely. I got far less occurrences but there are still some.


问:
Swift: Getting 'Snapshotting a view that has not been rendered..' error when trying to open a URL in safari from my app
One of the specifications of my app is that on tapping a tableView cell, the user will be redirected to the website associated with the cell. Here is the code:

```<code>override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if let url = NSURL(string: appdelegate.studentInfo[indexPath.row].url) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        UIApplication.sharedApplication().openURL(url)
    }
    else {
        let alert = UIAlertController(title: "Invalid URL", message: "Cannot open URL because it is invalid.", preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil))
        self.presentViewController(alert, animated: true, completion: nil)
    }
}
</code>```

On my first tap, the URL opens like it is supposed to. However, returning to the app from Safari and touching another cell results in the following error, although the app still works like it is supposed to:

Snapshotting a view that has not been rendered results in an empty
  snapshot. Ensure your view has been rendered at least once before
  snapshotting or snapshot after screen updates.

Is there any way to avoid this error? Or is this a bug?

I have experimented with dispatch_async blocks but it did not solve the problem.

答:
I was getting a similar debug warning when trying to present a QLPreviewController modally. I've read on other posts that it's an Xcode bug.

For me the error displayed when I ran my app on the simulator but not on an actual device. Must be an Xcode/Simulator issue. Hope that helps.

Body:
One of the specifications of my app is that on tapping a tableView cell, the user will be redirected to the website associated with the cell. Here is the code:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if let url = NSURL(string: appdelegate.studentInfo[indexPath.row].url) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        UIApplication.sharedApplication().openURL(url)
    }
    else {
        let alert = UIAlertController(title: "Invalid URL", message: "Cannot open URL because it is invalid.", preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil))
        self.presentViewController(alert, animated: true, completion: nil)
    }
}

On my first tap, the URL opens like it is supposed to. However, returning to the app from Safari and touching another cell results in the following error, although the app still works like it is supposed to:

Snapshotting a view that has not been rendered results in an empty
  snapshot. Ensure your view has been rendered at least once before
  snapshotting or snapshot after screen updates.

Is there any way to avoid this error? Or is this a bug?

I have experimented with dispatch_async blocks but it did not solve the problem.


答:
In PyCharm PYTHONPATH is set automatically. Assuming you're running server.py from the directory containing common.py, you could define PYTHONPATH to that directory an run.

```<code>$ python website/server.py
Traceback (most recent call last):
  File "website/server.py", line 1, in <module>
    from common import my_func
ImportError: No module named common

$ PYTHONPATH=`pwd` python website/server.py
$
</code>```

The key here is to make sure the packages you need are in the paths that Python will search when running your code.

Title: Cant find file to import

Body:
I have a file system as follows:

/
- website/
-   - server.py
- common.py

When in /, i try to run:   python website/server.py but it shows an error when attempting to from common import my_func saying:

ImportError: No module named common

Is there a way to denote a file as a module?  The issue I am running into is that while working in PyCharm it understands the python files correctly and functions as designed, but when running them in the command prompt in a VM it doesnt understand.  I was running the python from / as you can see, thinking it would use that as the scope, but it seems like that isnt working.

I was not given any more information from the debugger or logs. What am I doing wrong?

Edit  I tried doing the following as per Joao's request.   python ./website/server.py and returned the following line still, which is the same error received above.

Traceback (most recent call last):
  File "./website/server.py", line 3, in <module>
    from common import my_func
Import Error: No module named common

Body:
In PyCharm PYTHONPATH is set automatically. Assuming you're running server.py from the directory containing common.py, you could define PYTHONPATH to that directory an run.

$ python website/server.py
Traceback (most recent call last):
  File "website/server.py", line 1, in <module>
    from common import my_func
ImportError: No module named common

$ PYTHONPATH=`pwd` python website/server.py
$

The key here is to make sure the packages you need are in the paths that Python will search when running your code.


问:
posting uploaded file name
I want to output the filename. I also want to check the length of the filename. I have tried the following which didn't work.</p>

```<code>echo $_POST[$_FILES['file']['name']];

echo (strlen($_POST[$_FILES['file']['name']]);
</code>```

答:
don't use $_POST for getting  the files, simply use $_FILES to get the uploaded files as

```<code>echo $_FILES['file']['name'];

echo $_FILES['file']['tmp_name'];
</code>```

To get the file size use

```<code>echo $_FILES['file']['size']
</code>```

Title: posting uploaded file name

Body:
I want to output the filename. I also want to check the length of the filename. I have tried the following which didn't work.

echo $_POST[$_FILES['file']['name']];

echo (strlen($_POST[$_FILES['file']['name']]);

Body:
don't use $_POST for getting  the files, simply use $_FILES to get the uploaded files as

echo $_FILES['file']['name'];

echo $_FILES['file']['tmp_name'];

To get the file size use

echo $_FILES['file']['size']


问:
How to correctly store connection strings in environment variables for retrieval by production ASP.Net Core MVC applications
I am working on an ASP.NET Core MVC application and I am having an issue with my connection strings.

I have an ASPNETCORE_ENVIRONMENT variable set to Production on my production server and my production server is a Windows Server 2012R2 running IIS. I also have the DotNetCore.1.0.4_1.1.1-WindowsHosting.exe installed on the production server.

During development, I am using UserSecrets to hold my connection string. This is working properly.

For production, I want my connection strings in environment variables on my production server and this is where I am having an issue. I suspect that it may be in the way I am structuring the environment variable.

When I try to access the database in production I get an error indicating basically that it can't cannot parse the connection string.

```<code>An exception occurred in the database while iterating the results of a query.

System.ArgumentException: Keyword not supported: '"server'.
at System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary`2
parsetable, String connectionString, Boolean buildChain, Dictionary`2 synonyms)
at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Dictionary`2 synonyms)
at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString)
</code>```

If I put the connection string in appSettings.json, the production server works just fine.

So, here is an example of my appSettings.json file showing the connection string that works in production;

```<code>{
  "ConnectionStrings": {
     "TestDb": "Server=TestServer;Database=TestDb;Persist Security Info=True;User ID=TestUser;Password=testpassword;MultipleActiveResultSets=true"
  },

    ...
    ...
    ...
  }
}
</code>```

If I deploy this appSettings.json file to production, it works OK.

In my ASP.Net Core application, in the Startup.cs file, I have the following;

```<code>public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

    if (env.IsDevelopment())
    {
        // For more details on using the user secret store see https://go.microsoft.com/fwlink/?LinkID=532709
        builder.AddUserSecrets<Startup>();
    }

    builder.AddEnvironmentVariables();
    Configuration = builder.Build();

}
</code>```

My understanding is that the last builder.add... listed has priority, so in my case, if a connection string exists in the environment, it should take priority over anything in appsettings.

So in production, if I use the following appSettings.config file;

```<code>{
  "ConnectionStrings": {
     "TestDb": "Placeholder for connection string. Overridden by User Secrets in Development and Environment Variables in Production. "
  },

    ...
    ...
    ...
  }
}
</code>```

It should not matter what I have as a value for ConnectionStrings:TestDb in that appsettings.json file if I have an environment variable for the connection string.

Listed below is the environment variable I am using;

```<code>Variable                    Value
ConnectionStrings:TestDb    "Server=TestServer;Database=TestDb;Persist Security Info=True;User ID=TestUser;Password=testpassword;MultipleActiveResultSets=true"
</code>```

However, when I use this setup, I get an error when I try to access the database indicating that it can't parse the connection string.

I have to assume that the problem is the way I have the connection string specified in the environment variable, but after quite a while searching online, I have not been able to find an example of exactly what the environment variable value should look like. For example, do I need to put leading and trailing single quotes around the entire string? Does individual sections of the connection string need single or double quotes?

Any help, such as an example of a proper connection string defined in an environment variable, would be greatly appreciated.

答:
There is a typo/wrong value set in your connection variables.

Which can be seen in this output you pasted:

```<code>Variable                    Value
ConnectionStrings:TestDb    "Server=TestServer;Database=TestDb;Persist Security Info=True;User ID=TestUser;Password=testpassword;MultipleActiveResultSets=true"
</code>```

This likely happend while setting the variable via

```<code>$env:ConnectionStrings:MyDb = """Server=..."""
</code>```

the correct way is to set it without the quotation marks.

```<code>$env:ConnectionStrings:MyDb = "Server=..."
</code>```

Old answer (for other users who may search for similar issues)

The convention for connection strings is SQLCONNSTR_, MYSQLCONNSTR_, SQLAZURECONNSTR_ and CUSTOMCONNSTR_ which are used by Azure Web Apps, but should also work for self-hosting, VMs or any other cloud provider.

So if you have an environment variable called CUSTOMCONNSTR_TestDb it will be the same as defining it in appsettings.json in

```<code>{
    "connectionStrings": {
        "TestDb": "..."
    }
}
</code>```

It will also override the value inside it, if AddEnvironmentVariables() is called after .UseJsonFile(...). Last registration wins.

```<code>var builder = new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
    // This one needs to be last
    .AddEnvironmentVariables();
</code>```

You can also use other variables to override configuration values. iirc. ASPNETCORE_ is the default prefix (but you can change it in the AddEnvironmentVariables("MY_")).

So a ASPNETCORE_MySettings overrides Configuration["MySettings"] (or Configuration.Get("MySettings")) and ASPNETCORE_My__Settings (use double underscore for level hierarchy on Linux, read where : is used to obtain the config - Linux disallows colon in variable names) overrides Configuration["My:Settings"] so same as

```<code>{
    "my": {
        "settings": "..."
    }
}
</code>```

Unless they changed that recently.

FWIW: Environment variables/configuration key names are case-insensitive as far as I remember.

Body:
I am working on an ASP.NET Core MVC application and I am having an issue with my connection strings.

I have an ASPNETCORE_ENVIRONMENT variable set to Production on my production server and my production server is a Windows Server 2012R2 running IIS. I also have the DotNetCore.1.0.4_1.1.1-WindowsHosting.exe installed on the production server.

During development, I am using UserSecrets to hold my connection string. This is working properly.

For production, I want my connection strings in environment variables on my production server and this is where I am having an issue. I suspect that it may be in the way I am structuring the environment variable.

When I try to access the database in production I get an error indicating basically that it can't cannot parse the connection string.

An exception occurred in the database while iterating the results of a query.

System.ArgumentException: Keyword not supported: '"server'.
at System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary`2
parsetable, String connectionString, Boolean buildChain, Dictionary`2 synonyms)
at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Dictionary`2 synonyms)
at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString)

If I put the connection string in appSettings.json, the production server works just fine.

So, here is an example of my appSettings.json file showing the connection string that works in production;

{
  "ConnectionStrings": {
     "TestDb": "Server=TestServer;Database=TestDb;Persist Security Info=True;User ID=TestUser;Password=testpassword;MultipleActiveResultSets=true"
  },

    ...
    ...
    ...
  }
}

If I deploy this appSettings.json file to production, it works OK.

In my ASP.Net Core application, in the Startup.cs file, I have the following;

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

    if (env.IsDevelopment())
    {
        // For more details on using the user secret store see https://go.microsoft.com/fwlink/?LinkID=532709
        builder.AddUserSecrets<Startup>();
    }

    builder.AddEnvironmentVariables();
    Configuration = builder.Build();

}

My understanding is that the last builder.add... listed has priority, so in my case, if a connection string exists in the environment, it should take priority over anything in appsettings.

So in production, if I use the following appSettings.config file;

{
  "ConnectionStrings": {
     "TestDb": "Placeholder for connection string. Overridden by User Secrets in Development and Environment Variables in Production. "
  },

    ...
    ...
    ...
  }
}

It should not matter what I have as a value for ConnectionStrings:TestDb in that appsettings.json file if I have an environment variable for the connection string.

Listed below is the environment variable I am using;

Variable                    Value
ConnectionStrings:TestDb    "Server=TestServer;Database=TestDb;Persist Security Info=True;User ID=TestUser;Password=testpassword;MultipleActiveResultSets=true"

However, when I use this setup, I get an error when I try to access the database indicating that it can't parse the connection string.

I have to assume that the problem is the way I have the connection string specified in the environment variable, but after quite a while searching online, I have not been able to find an example of exactly what the environment variable value should look like. For example, do I need to put leading and trailing single quotes around the entire string? Does individual sections of the connection string need single or double quotes?

Any help, such as an example of a proper connection string defined in an environment variable, would be greatly appreciated.

Body:
There is a typo/wrong value set in your connection variables.

Which can be seen in this output you pasted:

Variable                    Value
ConnectionStrings:TestDb    "Server=TestServer;Database=TestDb;Persist Security Info=True;User ID=TestUser;Password=testpassword;MultipleActiveResultSets=true"

This likely happend while setting the variable via

$env:ConnectionStrings:MyDb = """Server=..."""

the correct way is to set it without the quotation marks.

$env:ConnectionStrings:MyDb = "Server=..."

Old answer (for other users who may search for similar issues)

The convention for connection strings is SQLCONNSTR_, MYSQLCONNSTR_, SQLAZURECONNSTR_ and CUSTOMCONNSTR_ which are used by Azure Web Apps, but should also work for self-hosting, VMs or any other cloud provider.

So if you have an environment variable called CUSTOMCONNSTR_TestDb it will be the same as defining it in appsettings.json in

{
    "connectionStrings": {
        "TestDb": "..."
    }
}

It will also override the value inside it, if AddEnvironmentVariables() is called after .UseJsonFile(...). Last registration wins.

var builder = new ConfigurationBuilder()
    .SetBasePath(env.ContentRootPath)
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
    // This one needs to be last
    .AddEnvironmentVariables();

You can also use other variables to override configuration values. iirc. ASPNETCORE_ is the default prefix (but you can change it in the AddEnvironmentVariables("MY_")).

So a ASPNETCORE_MySettings overrides Configuration["MySettings"] (or Configuration.Get("MySettings")) and ASPNETCORE_My__Settings (use double underscore for level hierarchy on Linux, read where : is used to obtain the config - Linux disallows colon in variable names) overrides Configuration["My:Settings"] so same as

{
    "my": {
        "settings": "..."
    }
}

Unless they changed that recently.

FWIW: Environment variables/configuration key names are case-insensitive as far as I remember.


问:
Redirect to dynamically added URL in MVC 5
My requirement is to redirect user to new url from old url . My entity is as follows:

```<code>public class HttpRedirect
{
    [Key]
    public int Id { get; set; }

    [Required(ErrorMessage = "Old url is required.")]
    [MaxLength(1000)]
    //[Url]
    [Display(Name = "Old Url")]
    public string OldUrl { get; set; }

    [Required(ErrorMessage = "New url is required.")]
    [MaxLength(1000)]
    //[Url]
    [Display (Name = "New Url")]
    public string NewUrl { get; set; }

}
</code>```

Url is commented so that I can work in localhost.

So when Old url is requested I want the request is transferred to new url
To achieve this in global.asax file in Application_BeginRequest event I have following code

```<code>protected void Application_BeginRequest(object sender, EventArgs e)
{
  //You don't want to redirect on posts, or images/css/js
  bool isGet = HttpContext.Current.Request.RequestType.ToLowerInvariant().Contains("get");
  if (isGet && HttpContext.Current.Request.Url.AbsolutePath.Contains(".") == false)
  {
    string lowercaseURL = (Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.Url.AbsolutePath);
    string newUrl = new HttpRedirectRepository().RedirectUrl(lowercaseURL);
    if(newUrl != null)
       {
         lowercaseURL = newUrl;
       }
     lowercaseURL = lowercaseURL.ToLower().Trim() + HttpContext.Current.Request.Url.Query;
     Response.Clear();
     Response.Status = "301 Moved Permanently";
     Response.AddHeader("Location", lowercaseURL);
     Response.End();
   }
}
</code>```

I have implemented the above code to accomplish 2 task.
 1. Change url to lower case
 2. If new url is available for requested url redirect to that url.

With my above implementation I have strong feeling that its working but causing infinite loop by redirecting to a lowercaseURL

So how can I prevent multiple redirection. For e.g.
I request http://localhost:80/mypage and I have set its new url to http://localhost:80/home then when mypage is requested it should redirect to home making url in lowercase and redirect should occur only one time.

note

I need to redirect within my own domain only.

User will enter full url address for both old and new url.

UPDATE

With some hint from @RobertHarvey I have modified my code as follows which is working for me

```<code>protected void Application_BeginRequest(object sender, EventArgs e)
{
  //You don't want to redirect on posts, or images/css/js
  bool isGet = HttpContext.Current.Request.RequestType.ToLowerInvariant().Contains("get");
  if (isGet && HttpContext.Current.Request.Url.AbsolutePath.Contains(".") == false)
  {
    bool redirect = false;
    string requestUrl = (Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.Url.AbsolutePath);
    //You don't want to change casing on query strings
    string newUrl = new HttpRedirectRepository().RedirectUrl(requestUrl);
    if (newUrl != null)
    {
      requestUrl = newUrl;
      redirect = true;
     }
     if (Regex.IsMatch(requestUrl, @"[A-Z]"))
     {
       requestUrl = requestUrl.ToLower().Trim() + HttpContext.Current.Request.Url.Query;
       redirect = true;
      }
      if (redirect)
      {
        Response.Clear();
        Response.Status = "301 Moved Permanently";
        Response.AddHeader("Location", requestUrl);
        Response.End();
       }
    }
}
</code>```

Though still I believe updated implementation has some limitation. I would appreciate any further code enhancement and case coverage.

答:
Your two "notes" are contradictory. If you only want to allow redirection within your domain, then recording a full URL, including a domain, is entirely unnecessary, and only serves to complicate things. Make the old/new URLs just absolute paths. This also solves your problem with working in development vs. production, since you don't need to worry about the data having the right domain for the right environment.

Note: your infinite redirect is a bug in your code here. You should be redirecting to newUrl, not lowercaseUrl. In the case where newUrl is null, there is no redirect, so you should simply not redirect at all in that case.

Body:
My requirement is to redirect user to new url from old url . My entity is as follows:

public class HttpRedirect
{
    [Key]
    public int Id { get; set; }

    [Required(ErrorMessage = "Old url is required.")]
    [MaxLength(1000)]
    //[Url]
    [Display(Name = "Old Url")]
    public string OldUrl { get; set; }

    [Required(ErrorMessage = "New url is required.")]
    [MaxLength(1000)]
    //[Url]
    [Display (Name = "New Url")]
    public string NewUrl { get; set; }

}

Url is commented so that I can work in localhost.

So when Old url is requested I want the request is transferred to new url
To achieve this in global.asax file in Application_BeginRequest event I have following code

protected void Application_BeginRequest(object sender, EventArgs e)
{
  //You don't want to redirect on posts, or images/css/js
  bool isGet = HttpContext.Current.Request.RequestType.ToLowerInvariant().Contains("get");
  if (isGet && HttpContext.Current.Request.Url.AbsolutePath.Contains(".") == false)
  {
    string lowercaseURL = (Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.Url.AbsolutePath);
    string newUrl = new HttpRedirectRepository().RedirectUrl(lowercaseURL);
    if(newUrl != null)
       {
         lowercaseURL = newUrl;
       }
     lowercaseURL = lowercaseURL.ToLower().Trim() + HttpContext.Current.Request.Url.Query;
     Response.Clear();
     Response.Status = "301 Moved Permanently";
     Response.AddHeader("Location", lowercaseURL);
     Response.End();
   }
}

I have implemented the above code to accomplish 2 task.
 1. Change url to lower case
 2. If new url is available for requested url redirect to that url.

With my above implementation I have strong feeling that its working but causing infinite loop by redirecting to a lowercaseURL

So how can I prevent multiple redirection. For e.g.
I request http://localhost:80/mypage and I have set its new url to http://localhost:80/home then when mypage is requested it should redirect to home making url in lowercase and redirect should occur only one time.

note

I need to redirect within my own domain only.

User will enter full url address for both old and new url.

UPDATE

With some hint from @RobertHarvey I have modified my code as follows which is working for me

protected void Application_BeginRequest(object sender, EventArgs e)
{
  //You don't want to redirect on posts, or images/css/js
  bool isGet = HttpContext.Current.Request.RequestType.ToLowerInvariant().Contains("get");
  if (isGet && HttpContext.Current.Request.Url.AbsolutePath.Contains(".") == false)
  {
    bool redirect = false;
    string requestUrl = (Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.Url.AbsolutePath);
    //You don't want to change casing on query strings
    string newUrl = new HttpRedirectRepository().RedirectUrl(requestUrl);
    if (newUrl != null)
    {
      requestUrl = newUrl;
      redirect = true;
     }
     if (Regex.IsMatch(requestUrl, @"[A-Z]"))
     {
       requestUrl = requestUrl.ToLower().Trim() + HttpContext.Current.Request.Url.Query;
       redirect = true;
      }
      if (redirect)
      {
        Response.Clear();
        Response.Status = "301 Moved Permanently";
        Response.AddHeader("Location", requestUrl);
        Response.End();
       }
    }
}

Though still I believe updated implementation has some limitation. I would appreciate any further code enhancement and case coverage.


问:
<%# Bind([ReqPo!ItemId])%> doesnt work
In Dynamics ax Enterprise Portal I have created a templatefield in AxGridView. Seems everything ok, but when i try to enter some value to this textbox (manually or through lookup), it doesnt bind to ReqPo!ItemId field. Checked that with info(strfmt("%1", ReqPo.ItemId))); in validateWrite method on ReqPo dataset - it prints nothing; What i'm missing?

```<code><asp:TemplateField ConvertEmptyStringToNull="False" HeaderText="<%$ AxLabel:@SYS12836 %>" Visible="true">
        <EditItemTemplate>
            <asp:TextBox runat="server" ID="TextBoxFilterItemId" CssClass="AxInputField"
                Columns="<%$ AxDataSet:ReqTransPo.ReqTrans.ReqPo!ItemId.DisplayLength %>"
                Enabled="<%$ AxDataSet:ReqTransPo.ReqTrans.ReqPo!ItemId.AllowEdit %>"
                MaxLength="<%$ AxDataSet:ReqTransPo.ReqTrans.ReqPo!ItemId.StringSize %>"
                Text='<%# Bind("[ReqPo!ItemId]") %>'>
            </asp:TextBox>
            <dynamics:AxLookup
                ID="AxLookup3" runat="server" OnLookup="Item_lookup" TargetControlId="TextBoxFilterItemId"
                CssClass="AxLookupButtonBF" HoverCssClass="AxLookupButtonHoverBF" ShowFilter="True">
            </dynamics:AxLookup>
        </EditItemTemplate>
        <ItemTemplate>
            <asp:Label ID="ItemIdLabel" runat="server" Text='<%# Bind("[ReqPo!ItemId]") %>'></asp:Label>
        </ItemTemplate>
    </asp:TemplateField>
</code>```

答:
I assume you are using the ItemId field from the table ReqPo. If you locate that field in the Data Dictionary you will discover that the field does not allow editing.

As AxGridView only supports editing, which leads me to the conclusion that you are trying the break the data integrity rules of the application.

if this is the case, it is obviously not possible.

Title: <%# Bind([ReqPo!ItemId])%> doesnt work

Body:
In Dynamics ax Enterprise Portal I have created a templatefield in AxGridView. Seems everything ok, but when i try to enter some value to this textbox (manually or through lookup), it doesnt bind to ReqPo!ItemId field. Checked that with info(strfmt("%1", ReqPo.ItemId))); in validateWrite method on ReqPo dataset - it prints nothing; What i'm missing?

<asp:TemplateField ConvertEmptyStringToNull="False" HeaderText="<%$ AxLabel:@SYS12836 %>" Visible="true">
        <EditItemTemplate>
            <asp:TextBox runat="server" ID="TextBoxFilterItemId" CssClass="AxInputField"
                Columns="<%$ AxDataSet:ReqTransPo.ReqTrans.ReqPo!ItemId.DisplayLength %>"
                Enabled="<%$ AxDataSet:ReqTransPo.ReqTrans.ReqPo!ItemId.AllowEdit %>"
                MaxLength="<%$ AxDataSet:ReqTransPo.ReqTrans.ReqPo!ItemId.StringSize %>"
                Text='<%# Bind("[ReqPo!ItemId]") %>'>
            </asp:TextBox>
            <dynamics:AxLookup
                ID="AxLookup3" runat="server" OnLookup="Item_lookup" TargetControlId="TextBoxFilterItemId"
                CssClass="AxLookupButtonBF" HoverCssClass="AxLookupButtonHoverBF" ShowFilter="True">
            </dynamics:AxLookup>
        </EditItemTemplate>
        <ItemTemplate>
            <asp:Label ID="ItemIdLabel" runat="server" Text='<%# Bind("[ReqPo!ItemId]") %>'></asp:Label>
        </ItemTemplate>
    </asp:TemplateField>