问:
Update a listview from modify on selected items
Excuse me if I didn't formulate good the question, but don't know how to name it better...

I have a project with some ListView, binded to ObservableCollection.
When I make a right click on my ListView, to change name, or other parameter, the ListView doesn't automatically refresh until I go out, then open again.

Here is my behind code for context :

```<code>public class Contexte : INotifyPropertyChanged
    {
        private Affaire affaireSelectionnee;
        public Affaire AffaireSelectionnee
        {
            get { return affaireSelectionnee; }
            set
            {
                if (value == affaireSelectionnee) return;
                affaireSelectionnee = value;
                NotifyPropertyChanged("AffaireSelectionnee");
            }
        }

        private ObservableCollection<Affaire> listeDesAffairesSelectionnees;
        public ObservableCollection<Affaire> ListeDesAffairesSelectionnees
        {
            get { return listeDesAffairesSelectionnees; }
            set { NotifyPropertyChanged(ref listeDesAffairesSelectionnees, value); }
        }
        private ObservableCollection<Phase> listeDesPhasesSelectionnees;
        public ObservableCollection<Phase> ListeDesPhasesSelectionnees
        {
            get { return listeDesPhasesSelectionnees; }
            set { NotifyPropertyChanged(ref listeDesPhasesSelectionnees, value); }
        }
        private ObservableCollection<Assemblage> listeDesAssemblagesSelectionnees;
        public ObservableCollection<Assemblage> ListeDesAssemblagesSelectionnees
        {
            get { return listeDesAssemblagesSelectionnees; }
            set { NotifyPropertyChanged(ref listeDesAssemblagesSelectionnees, value); }
        }
        private ObservableCollection<Repere> listeDesReperesSelectionnees;
        public ObservableCollection<Repere> ListeDesReperesSelectionnees
        {
            get { return listeDesReperesSelectionnees; }
            set { NotifyPropertyChanged(ref listeDesReperesSelectionnees, value); }
        }

        private ObservableCollection<Affaire> listeDesAffaires;
        public ObservableCollection<Affaire> ListeDesAffaires
        {
            get { return listeDesAffaires; }
            set { NotifyPropertyChanged(ref listeDesAffaires, value); }
        }
        private ObservableCollection<Phase> listeDesPhases;
        public ObservableCollection<Phase> ListeDesPhases
        {
            get { return listeDesPhases; }
            set { NotifyPropertyChanged(ref listeDesPhases, value); }
        }
        private ObservableCollection<Assemblage> listeDesAssemblages;
        public ObservableCollection<Assemblage> ListeDesAssemblages
        {
            get { return listeDesAssemblages; }
            set { NotifyPropertyChanged(ref listeDesAssemblages, value); }
        }
        private ObservableCollection<Repere> listeDesReperes;
        public ObservableCollection<Repere> ListeDesReperes
        {
            get { return listeDesReperes; }
            set { NotifyPropertyChanged(ref listeDesReperes, value); }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged(string nomPropriete)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(nomPropriete));
        }

        private bool NotifyPropertyChanged<T>(ref T variable, T valeur, [CallerMemberName] string nomPropriete = null)
        {
            if (object.Equals(variable, valeur)) return false;

            variable = valeur;
            NotifyPropertyChanged(nomPropriete);
            return true;
        }

    }
</code>```

I load the context once when loading the programm :

```<code>DBConnect DataBase = new DBConnect();
string requete = "SELECT * FROM affaire ORDER BY ID";
List<Affaire> liste = DataBase.Select_affaire(requete, true);
contexte = new Contexte { ListeDesAffaires = new ObservableCollection<Affaire>(liste), ListeDesPhases = new ObservableCollection<Phase>(), ListeDesAssemblages = new ObservableCollection<Assemblage>(), ListeDesReperes = new ObservableCollection<Repere>(), AffaireSelectionnee = new Affaire(), ListeDesAffairesSelectionnees = new ObservableCollection<Affaire>(liste), ListeDesPhasesSelectionnees = new ObservableCollection<Phase>(), ListeDesAssemblagesSelectionnees = new ObservableCollection<Assemblage>(), ListeDesReperesSelectionnees = new ObservableCollection<Repere>() };
DataContext = contexte;
</code>```

Then my function that may update property :

```<code>foreach (Phase ph in contexte.ListeDesPhasesSelectionnees)
{
  Phase ph_find = contexte.ListeDesPhases.First(s=>s==ph);
  ph_find.Priorite = new_priorite;
}
</code>```

ph_find.Priorite is well updated, as is my Observable Collection "contexte.ListeDesPhases", but no refresh is made on the ListView.

Edit : Well I could solve the problem adding a ListView1.Items.Refresh()...
I am not sure this is the most correct way(is not bidding supposed to refresh the listview automaticaly?), but for now it works

Edit2 :

My XAML code (ListView of the phase) :

```<code><ListView x:Name="ListView2" ItemsSource="{Binding ListeDesPhases}" Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="4" MouseDoubleClick="ListView_MouseDoubleClick" GridViewColumnHeader.Click="GridViewColumnHeaderClickedHandler" SelectionChanged="ListView_SelectionChanged" >

            <ListView.View>

                <GridView AllowsColumnReorder="true" x:Name="GridView2">
                    <GridViewColumn DisplayMemberBinding="{Binding ID}" Header="ID" Width="50"/>
                    <GridViewColumn DisplayMemberBinding= "{Binding NomPhase}" Header="{x:Static p:Resources.Nom}" Width="200"/>
                    <GridViewColumn DisplayMemberBinding="{Binding IdAffaire}" Header="{x:Static p:Resources.IdAffaire}" Width="100"/>
                    <GridViewColumn DisplayMemberBinding="{Binding CommPhase}" Header="{x:Static p:Resources.Commentaire}" Width="100"/>
                    <GridViewColumn DisplayMemberBinding="{Binding Priorite}" Header="{x:Static p:Resources.Priorite}" Width="100"/>
                </GridView>
            </ListView.View>
        </ListView>
</code>```

My Phase class :

```<code>public class Phase
    {
        public string NomPhase { get; set; }
        public long IdAffaire { get; set; }
        public string CommPhase { get; set; }
        public int Priorite { get; set; }
        public long ID { get; set; }
        public List<Assemblage> ListAssemblages { get; set; }
        public Phase()
        {
            this.NomPhase = "";
            this.IdAffaire = 0;
            this.CommPhase = "";
            this.Priorite = 0;
            this.ID = 0;
            this.ListAssemblages = new List<Assemblage>();
        }
        ...
    }
</code>```

Edit3 :

Tried to modify as indicated by Netstep, but still the same :

```<code>public ObservableCollection<Phase> ListeDesPhases
        {
            get { return listeDesPhases; }
            set { NotifyPropertyChanged(ref listeDesPhases, value);
                NotifyPropertyChanged("Priorite");
            }
        }
</code>```

Edit 4 :

Well, I now understand that nothing was happening, I read that course http://www.wpf-tutorial.com/data-binding/responding-to-changes/ to understand it...
So example given by NetStep was the good one (just didn't understand what is the RaisePropertyChanged(() => Priorite); part? Is this due to the use of mvvmlight.net library?

```<code>public class Phase : INotifyPropertyChanged
    {
        private string nomPhase;
        public string NomPhase
        {
            get { return this.nomPhase; }
            set
            {
                if (this.nomPhase != value)
                {
                    this.nomPhase = value;
                    this.NotifyPropertyChanged("NomPhase");
                }
            }
        }
        private int priorite;
        public int Priorite
        {
            get { return this.priorite; }
            set
            {
                if (this.priorite != value)
                {
                    this.priorite = value;
                    this.NotifyPropertyChanged("Priorite");
                }
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged(string propName)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
    ...//all of my other functions
    }
</code>```

So this is what I did and it works good now.

Then I have the following question : I have 4 different objects displayed in 4 ListView(Contract, Subcontract, Phase and Detail).
Contract is the "Mother Class", it countains parameters, but also contains a list of Subcontracts. Subcontracts contains several parameters, and a list of Phases, and each Phase contains some parameters, with a list of Details.
Each of them is displayed in a different ListView(4 ListView).
May I define 4 different ObservableCollection, or is there a way to define only one ObservableCollection for all the "tree", then bind on parameters of my ObservableCollection>?

答:
To have the field properly updated in UI, please ensure that Phase class also implement INotifyPropertyChanged someway and call

```<code>NotifyPropertyChanged("Priorite")
</code>```

in set accessor. Just using the ObservableCollection is not enough, it handles notifying only Add/Remove operations. And you right - ListView1.Items.Refresh() is a workaround in this case.
Hope this will help, otherwise please share Phase class code and your xaml code to get more clear comment/answer.

Here is the example, based on MVVM light library:

```<code>using GalaSoft.MvvmLight;

namespace WpfApp1
{
    public class Phase : ViewModelBase
    {
        private int _priorite;

        public int Priorite
        {
            get { return _priorite; }
            set
            {
                _priorite = value;
                RaisePropertyChanged(() => Priorite);
            }
        }
    }
}
</code>```

All the rest of code can remain unchanged. You also can inherit you Context class from ViewModelBase

Body:
Excuse me if I didn't formulate good the question, but don't know how to name it better...

I have a project with some ListView, binded to ObservableCollection.
When I make a right click on my ListView, to change name, or other parameter, the ListView doesn't automatically refresh until I go out, then open again.

Here is my behind code for context :

public class Contexte : INotifyPropertyChanged
    {
        private Affaire affaireSelectionnee;
        public Affaire AffaireSelectionnee
        {
            get { return affaireSelectionnee; }
            set
            {
                if (value == affaireSelectionnee) return;
                affaireSelectionnee = value;
                NotifyPropertyChanged("AffaireSelectionnee");
            }
        }

        private ObservableCollection<Affaire> listeDesAffairesSelectionnees;
        public ObservableCollection<Affaire> ListeDesAffairesSelectionnees
        {
            get { return listeDesAffairesSelectionnees; }
            set { NotifyPropertyChanged(ref listeDesAffairesSelectionnees, value); }
        }
        private ObservableCollection<Phase> listeDesPhasesSelectionnees;
        public ObservableCollection<Phase> ListeDesPhasesSelectionnees
        {
            get { return listeDesPhasesSelectionnees; }
            set { NotifyPropertyChanged(ref listeDesPhasesSelectionnees, value); }
        }
        private ObservableCollection<Assemblage> listeDesAssemblagesSelectionnees;
        public ObservableCollection<Assemblage> ListeDesAssemblagesSelectionnees
        {
            get { return listeDesAssemblagesSelectionnees; }
            set { NotifyPropertyChanged(ref listeDesAssemblagesSelectionnees, value); }
        }
        private ObservableCollection<Repere> listeDesReperesSelectionnees;
        public ObservableCollection<Repere> ListeDesReperesSelectionnees
        {
            get { return listeDesReperesSelectionnees; }
            set { NotifyPropertyChanged(ref listeDesReperesSelectionnees, value); }
        }

        private ObservableCollection<Affaire> listeDesAffaires;
        public ObservableCollection<Affaire> ListeDesAffaires
        {
            get { return listeDesAffaires; }
            set { NotifyPropertyChanged(ref listeDesAffaires, value); }
        }
        private ObservableCollection<Phase> listeDesPhases;
        public ObservableCollection<Phase> ListeDesPhases
        {
            get { return listeDesPhases; }
            set { NotifyPropertyChanged(ref listeDesPhases, value); }
        }
        private ObservableCollection<Assemblage> listeDesAssemblages;
        public ObservableCollection<Assemblage> ListeDesAssemblages
        {
            get { return listeDesAssemblages; }
            set { NotifyPropertyChanged(ref listeDesAssemblages, value); }
        }
        private ObservableCollection<Repere> listeDesReperes;
        public ObservableCollection<Repere> ListeDesReperes
        {
            get { return listeDesReperes; }
            set { NotifyPropertyChanged(ref listeDesReperes, value); }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged(string nomPropriete)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(nomPropriete));
        }

        private bool NotifyPropertyChanged<T>(ref T variable, T valeur, [CallerMemberName] string nomPropriete = null)
        {
            if (object.Equals(variable, valeur)) return false;

            variable = valeur;
            NotifyPropertyChanged(nomPropriete);
            return true;
        }

    }

I load the context once when loading the programm :

DBConnect DataBase = new DBConnect();
string requete = "SELECT * FROM affaire ORDER BY ID";
List<Affaire> liste = DataBase.Select_affaire(requete, true);
contexte = new Contexte { ListeDesAffaires = new ObservableCollection<Affaire>(liste), ListeDesPhases = new ObservableCollection<Phase>(), ListeDesAssemblages = new ObservableCollection<Assemblage>(), ListeDesReperes = new ObservableCollection<Repere>(), AffaireSelectionnee = new Affaire(), ListeDesAffairesSelectionnees = new ObservableCollection<Affaire>(liste), ListeDesPhasesSelectionnees = new ObservableCollection<Phase>(), ListeDesAssemblagesSelectionnees = new ObservableCollection<Assemblage>(), ListeDesReperesSelectionnees = new ObservableCollection<Repere>() };
DataContext = contexte;

Then my function that may update property :

foreach (Phase ph in contexte.ListeDesPhasesSelectionnees)
{
  Phase ph_find = contexte.ListeDesPhases.First(s=>s==ph);
  ph_find.Priorite = new_priorite;
}

ph_find.Priorite is well updated, as is my Observable Collection "contexte.ListeDesPhases", but no refresh is made on the ListView.

Edit : Well I could solve the problem adding a ListView1.Items.Refresh()...
I am not sure this is the most correct way(is not bidding supposed to refresh the listview automaticaly?), but for now it works

Edit2 :

My XAML code (ListView of the phase) :

<ListView x:Name="ListView2" ItemsSource="{Binding ListeDesPhases}" Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="4" MouseDoubleClick="ListView_MouseDoubleClick" GridViewColumnHeader.Click="GridViewColumnHeaderClickedHandler" SelectionChanged="ListView_SelectionChanged" >

            <ListView.View>

                <GridView AllowsColumnReorder="true" x:Name="GridView2">
                    <GridViewColumn DisplayMemberBinding="{Binding ID}" Header="ID" Width="50"/>
                    <GridViewColumn DisplayMemberBinding= "{Binding NomPhase}" Header="{x:Static p:Resources.Nom}" Width="200"/>
                    <GridViewColumn DisplayMemberBinding="{Binding IdAffaire}" Header="{x:Static p:Resources.IdAffaire}" Width="100"/>
                    <GridViewColumn DisplayMemberBinding="{Binding CommPhase}" Header="{x:Static p:Resources.Commentaire}" Width="100"/>
                    <GridViewColumn DisplayMemberBinding="{Binding Priorite}" Header="{x:Static p:Resources.Priorite}" Width="100"/>
                </GridView>
            </ListView.View>
        </ListView>

My Phase class :

public class Phase
    {
        public string NomPhase { get; set; }
        public long IdAffaire { get; set; }
        public string CommPhase { get; set; }
        public int Priorite { get; set; }
        public long ID { get; set; }
        public List<Assemblage> ListAssemblages { get; set; }
        public Phase()
        {
            this.NomPhase = "";
            this.IdAffaire = 0;
            this.CommPhase = "";
            this.Priorite = 0;
            this.ID = 0;
            this.ListAssemblages = new List<Assemblage>();
        }
        ...
    }

Edit3 :

Tried to modify as indicated by Netstep, but still the same :

public ObservableCollection<Phase> ListeDesPhases
        {
            get { return listeDesPhases; }
            set { NotifyPropertyChanged(ref listeDesPhases, value);
                NotifyPropertyChanged("Priorite");
            }
        }

Edit 4 :

Well, I now understand that nothing was happening, I read that course http://www.wpf-tutorial.com/data-binding/responding-to-changes/ to understand it...
So example given by NetStep was the good one (just didn't understand what is the RaisePropertyChanged(() => Priorite); part? Is this due to the use of mvvmlight.net library?

public class Phase : INotifyPropertyChanged
    {
        private string nomPhase;
        public string NomPhase
        {
            get { return this.nomPhase; }
            set
            {
                if (this.nomPhase != value)
                {
                    this.nomPhase = value;
                    this.NotifyPropertyChanged("NomPhase");
                }
            }
        }
        private int priorite;
        public int Priorite
        {
            get { return this.priorite; }
            set
            {
                if (this.priorite != value)
                {
                    this.priorite = value;
                    this.NotifyPropertyChanged("Priorite");
                }
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged(string propName)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
    ...//all of my other functions
    }

So this is what I did and it works good now.

Then I have the following question : I have 4 different objects displayed in 4 ListView(Contract, Subcontract, Phase and Detail).
Contract is the "Mother Class", it countains parameters, but also contains a list of Subcontracts. Subcontracts contains several parameters, and a list of Phases, and each Phase contains some parameters, with a list of Details.
Each of them is displayed in a different ListView(4 ListView).
May I define 4 different ObservableCollection, or is there a way to define only one ObservableCollection for all the "tree", then bind on parameters of my ObservableCollection>?

Body:
To have the field properly updated in UI, please ensure that Phase class also implement INotifyPropertyChanged someway and call

NotifyPropertyChanged("Priorite")

in set accessor. Just using the ObservableCollection is not enough, it handles notifying only Add/Remove operations. And you right - ListView1.Items.Refresh() is a workaround in this case.
Hope this will help, otherwise please share Phase class code and your xaml code to get more clear comment/answer.

Here is the example, based on MVVM light library:

using GalaSoft.MvvmLight;

namespace WpfApp1
{
    public class Phase : ViewModelBase
    {
        private int _priorite;

        public int Priorite
        {
            get { return _priorite; }
            set
            {
                _priorite = value;
                RaisePropertyChanged(() => Priorite);
            }
        }
    }
}

All the rest of code can remain unchanged. You also can inherit you Context class from ViewModelBase


来源: stackexchange

问:
The effective way for Hibernate Stateless Session batch inserting with associated instance
I am trying to use Hibernate stateless session to do batch insertion

```<code>class Book {
    String title;
    String author;
    Double price;
    Publisher publisher;

    static constraints = {
        publisher nullable: true
    }

    static mapping = {
        id generator: 'assigned'
    }
}

class Publisher {

    String name

    static hasMany = [book: Book] // add one line here

    static constraints = {

    }

    static mapping = {
        id generator: 'assigned'
    }
}
</code>```

The batch inserting test code:

```<code>class BatchController {
    SessionFactory sessionFactory;

    def testBatchInsert() {
        StatelessSession session = sessionFactory.openStatelessSession()
        Transaction tx = session.beginTransaction();
        int count = 100;
        for (int i = 0; i < count; i++) {
            def publisher = ["publisher": (i % 1000)] // make publisher id
            //The above code have to load publisher from db, or "save the transient instance before flushing" exception will throw.
            Book book = new Book()
            bindData(book, publisher) // use data binding here to set publisher id for the instance
            book.setId(i)
            book.setTitle("title $i")
            book.setAuthor("author $i")
            book.setPrice(123.456)
            session.insert(book)
        }
        tx.commit()
        render "finished!"
    }
}
</code>```

Any way to skip loading publisher from db and improve the processing performance? (All publishers exist in the table already).

答:
You can try to use bindData as below

```<code>    StatelessSession session = sessionFactory.openStatelessSession()
    for (int i = 0; i < count; i++) {
        def publisher = ["publisher": (i % 1000)] // make publisher id
        //The above code have to load publisher from db, or "save the transient instance before flushing" exception will throw.
        Book book = new Book()
        bindData(book, publisher) // use data binding here to set publisher id for the instance
        book.setId(start + i)
        book.setTitle("title $i")
        book.setAuthor("author $i")
        book.setPrice(123.456)
        session.insert(book)
    }
</code>```

// Add a relation between publisher and book in domain publisher

```<code>class Publisher {

    String name

    static hasMany = [book: Book] // add one line here

    static constraints = {

    }

    static mapping = {
        id generator: 'assigned'
    }
}
</code>```

Ref: http://docs.grails.org/latest/ref/Controllers/bindData.html

Hope it can help.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to use Hibernate stateless session to do batch insertion

class Book {
    String title;
    String author;
    Double price;
    Publisher publisher;

    static constraints = {
        publisher nullable: true
    }

    static mapping = {
        id generator: 'assigned'
    }
}

class Publisher {

    String name

    static hasMany = [book: Book] // add one line here

    static constraints = {

    }

    static mapping = {
        id generator: 'assigned'
    }
}

The batch inserting test code:

class BatchController {
    SessionFactory sessionFactory;

    def testBatchInsert() {
        StatelessSession session = sessionFactory.openStatelessSession()
        Transaction tx = session.beginTransaction();
        int count = 100;
        for (int i = 0; i < count; i++) {
            def publisher = ["publisher": (i % 1000)] // make publisher id
            //The above code have to load publisher from db, or "save the transient instance before flushing" exception will throw.
            Book book = new Book()
            bindData(book, publisher) // use data binding here to set publisher id for the instance
            book.setId(i)
            book.setTitle("title $i")
            book.setAuthor("author $i")
            book.setPrice(123.456)
            session.insert(book)
        }
        tx.commit()
        render "finished!"
    }
}

Any way to skip loading publisher from db and improve the processing performance? (All publishers exist in the table already).

Body:
You can try to use bindData as below

    StatelessSession session = sessionFactory.openStatelessSession()
    for (int i = 0; i < count; i++) {
        def publisher = ["publisher": (i % 1000)] // make publisher id
        //The above code have to load publisher from db, or "save the transient instance before flushing" exception will throw.
        Book book = new Book()
        bindData(book, publisher) // use data binding here to set publisher id for the instance
        book.setId(start + i)
        book.setTitle("title $i")
        book.setAuthor("author $i")
        book.setPrice(123.456)
        session.insert(book)
    }

// Add a relation between publisher and book in domain publisher

class Publisher {

    String name

    static hasMany = [book: Book] // add one line here

    static constraints = {

    }

    static mapping = {
        id generator: 'assigned'
    }
}

Ref: http://docs.grails.org/latest/ref/Controllers/bindData.html

Hope it can help.


问:
Why can Android Studio not connect to physical devices?
Up until very recently Android Studio had no problems sending APKs to Android devices over USB. But now, although it works fine with the emulator, I cannot send APKs to either of the two physical devices I have tried.

"adb devices" shows no devices connected, even when the phone is connected over a USB cable (I tried other cables too) and when USB debugging IS enabled on the device.

I have tried revoking USB debugging authorisation on the devices, but on restarting adb and reconnecting the device am not asked to authorise the new access.

I've tried rebooting the phones, rebooting the dev machine (a MacBook) and killing and restarting adb, but with no success. I wonder if a recent Android tools update has reset the USB device auth, but how do I re-auth?

It's a problem as the app I'm working on scans barcodes so I really do need a physical device for testing.

UPDATE 1
Ah, so it seems if a USB device is not authorised, it still shows in the list but marked as such. The devices do not show in the list at all so it seems it is not an authorisation issue.

On a Samsung J5, when it is connected to the MacBook, no notification shows. When a Pixel 2 XL is connected to USB, the phone shows the "USB debugging connected" notification, but adb devices does not list it.

UPDATE 2
On making sure adb is running, then connecting both devices to the MacBook with USB and then running "adb devices", I am seeing this:

List of devices attached
* daemon not running; starting now at tcp:5037
ADB server didn't ACK
Full server startup log: /var/folders/_3/zzf_y_vx2rnc685ysjf1hqr40000gn/T//adb.501.log
Server had pid: 13977
--- adb starting (pid 13977) ---
adb I 12-08 10:10:52 13977 807310 main.cpp:57] Android Debug Bridge version 1.0.39
adb I 12-08 10:10:52 13977 807310 main.cpp:57] Version 27.0.0-4455170
adb I 12-08 10:10:52 13977 807310 main.cpp:57] Installed as /Users/admin/android-sdk/platform-tools/adb
adb I 12-08 10:10:52 13977 807310 main.cpp:57]
adb I 12-08 10:10:52 13977 807310 adb_auth_host.cpp:416] adb_auth_init...
adb I 12-08 10:10:52 13977 807310 adb_auth_host.cpp:174] read_key_file '/Users/admin/.android/adbkey'...
adb F 12-08 10:10:52 13977 807320 transport_usb.cpp:37] Check failed: usb_packet_size < 4096ULL (usb_packet_size=5120, 4096ULL=4096)

failed to start daemon
error: cannot connect to daemon

If I then use kill-server and start-server, adb fails to start, showing the same output.

答:
This is a bug in the 27.0.0 Android tools, this question has answers that explain solutions, and a link to the bug in the Google bug tracker

Android Studio - ADB start server fails, adbkey check fails


问:
OpenGL- move camera inside skybox
I have a skybox and found out that it is impossible to move inside it ( only rotating, not moving closer to person inside it or so, this is not zoom, it is exactly movement) , as is written in this tutorial https://learnopengl.com/#!Advanced-OpenGL/Cubemaps. As soon as I enable translation for the camera, the skybox become rather ugly, with corners and all sides visible, so the idea to move camera and move the skybox at the same time is not really good. What is the appropriate solution? I think it is a rather obvious problem, but I can not find any solutions anywhere. Or maybe I need to use another construction, not skybox for this purpose.

here are two states - the first one I get when translate is enabled. I want in the second image to move closer to mountains.

答:
Even though this question a few years old, the solution to this problem is that you have to set the view matrix AFTER you "use" your shader for the the skybox. You can't just set the view matrix once in your loop and expect to work with all shaders that have a view uniform.

So the problem is that OP has something like this based on the tutorial within the main loop:

```<code>    glm::mat4 view = mCamera.GetViewMatrix();

    glDepthFunc(GL_LEQUAL);
    mSkyboxShader.Use();
    mSkyboxShader.SetMat4("view", view);
    mSkyboxShader.SetMat4("projection", projection);
    mSkybox.Render(mSkyboxTexture);
    glDepthFunc(GL_LESS);
</code>```

Regardless of code, this treats your skybox like any other object that you can move to. The solution is:

```<code>glm::mat4 view = mCamera.GetViewMatrix();

glDepthFunc(GL_LEQUAL);
mSkyboxShader.Use();
view = mCamera.GetViewMatrix(); <----Solution
mSkyboxShader.SetMat4("view", view);
...
</code>```

You have to update the view after you activate the shader before applying it to a uniform for each shader program that needs a view matrix.

Title: OpenGL- move camera inside skybox

Body:
Even though this question a few years old, the solution to this problem is that you have to set the view matrix AFTER you "use" your shader for the the skybox. You can't just set the view matrix once in your loop and expect to work with all shaders that have a view uniform.

So the problem is that OP has something like this based on the tutorial within the main loop:

    glm::mat4 view = mCamera.GetViewMatrix();

    glDepthFunc(GL_LEQUAL);
    mSkyboxShader.Use();
    mSkyboxShader.SetMat4("view", view);
    mSkyboxShader.SetMat4("projection", projection);
    mSkybox.Render(mSkyboxTexture);
    glDepthFunc(GL_LESS);

Regardless of code, this treats your skybox like any other object that you can move to. The solution is:

glm::mat4 view = mCamera.GetViewMatrix();

glDepthFunc(GL_LEQUAL);
mSkyboxShader.Use();
view = mCamera.GetViewMatrix(); <----Solution
mSkyboxShader.SetMat4("view", view);
...

You have to update the view after you activate the shader before applying it to a uniform for each shader program that needs a view matrix.


问:
Vue selectize, getting json data from option?
I'm using vue2-selectize to display list of options fetched from axios call:

```<code><template>
    <selectize v-model="selected" :settings="settings">
        <option v-for="option in options" :value="option.id">
            ({{ option.author }}) - {{ option.description }}
        </option>
    </selectize>
</template>

<script>
    export default {
        props: ['old-value'],

        data() {
            return {
                selected: this.oldValue,
                options: [],
                settings: {
                    preload: true,
                    placeholder: "Search All Authors",
                    dropdownParent: 'body',
                    closeOnSelect: true,

                    render: {
                        option: function (data) {
                            console.log(data);
                            return '<div>' +
                                data.displayName +
                                '<div class="item-bio">' +
                                data.bio +
                                '</div>';
                        }
                    },

                    load: async (query, callback) => {
                        axios.get(route('api.showAllAuthors')).then(response => {
                            this.options = response.data;
                            callback();
                        })
                    }
                },
            }
        },
    }
</script>
</code>```

The issue is that once you setup the <option> for the select you can only work with the two values it passes to the render function (text and value) and not the original object (whereas the actual <option> has access to this object).

The manual mentions the optional parameter of dataAttr available for <option> tags, but setting <option :data-data="option"> has no effect and I still can't access the original properties.

How can I access the original JSON attributes that the <option> is using in the render function?

答:
```<code>var value = selectizeObject.getValue(),
    optionJson = selectizeObject.options[value];
</code>```

selectizeObject is object for given select / input. For example with jQuery:

```<code>var selectizeObject = $('#my-select')[0].selectize;
</code>```

Body:
I'm using vue2-selectize to display list of options fetched from axios call:

<template>
    <selectize v-model="selected" :settings="settings">
        <option v-for="option in options" :value="option.id">
            ({{ option.author }}) - {{ option.description }}
        </option>
    </selectize>
</template>

The issue is that once you setup the <option> for the select you can only work with the two values it passes to the render function (text and value) and not the original object (whereas the actual <option> has access to this object).

The manual mentions the optional parameter of dataAttr available for <option> tags, but setting <option :data-data="option"> has no effect and I still can't access the original properties.

How can I access the original JSON attributes that the <option> is using in the render function?

Body:
var value = selectizeObject.getValue(),
    optionJson = selectizeObject.options[value];

selectizeObject is object for given select / input. For example with jQuery:

var selectizeObject = $('#my-select')[0].selectize;


问:
Acceptance testing preloading of data into GAE dev server datastore
In my application I have a set of of DAOs which I inject into my application layer.  For an acceptance test I'm writing, I want to preload the dev_server datastore with data, so I use the same Spring config in my JUnit test (using the @ContextConfiguration annotation) to inject an instance of the relevant DAO into my test.  When I actually go to store some data eg:

```<code>dao.add(entity)
</code>```

I get the dreaded "No API environment is registered for this thread."

```<code>Caused by: java.lang.NullPointerException: No API environment is registered for this thread.
 at com.google.appengine.api.datastore.DatastoreApiHelper.getCurrentAppId(DatastoreApiHelper.java:108)
 at com.google.appengine.api.datastore.DatastoreApiHelper.getCurrentAppIdNamespace(DatastoreApiHelper.java:118)
    ....
</code>```

This is probably because my test case hasn't read in the GAE application-web.xml with the app details (although I'm guessing here I could really be wrong); so it doesn't know to write to the same datastore that the app running on the dev_server is reading/writing to.

How can I get my test to "point" to the same datastore as the app?  Is there some "datasource" mechanism that I can inject both into the app and the test?  Is there a way to get my test to force the datastore api to read the needed config?

答:
Here is a page that talks about how to do unit tests that connect to a dev datastore.  Is this the kind of thing you're looking for?  Basically it talks about two classes, LocalServiceTestHelper and LocalDatastoreServiceTestConfig that you can use to set up an environment for testing.  While the example given is for unit tests, I believe it will also work for your situation.

You can then configure things like whether the dev datastore is written to disk or just kept in memory (for faster tests).  If you want this data to go to the same place as your dev server, you will probably want to adjust this, as I think the default is the "in memory" option.  If you look at the javadoc there is a "setBackingStoreLocation" method where you can point to whatever file you want.

Body:
In my application I have a set of of DAOs which I inject into my application layer.  For an acceptance test I'm writing, I want to preload the dev_server datastore with data, so I use the same Spring config in my JUnit test (using the @ContextConfiguration annotation) to inject an instance of the relevant DAO into my test.  When I actually go to store some data eg:

dao.add(entity)

I get the dreaded "No API environment is registered for this thread."

Caused by: java.lang.NullPointerException: No API environment is registered for this thread.
 at com.google.appengine.api.datastore.DatastoreApiHelper.getCurrentAppId(DatastoreApiHelper.java:108)
 at com.google.appengine.api.datastore.DatastoreApiHelper.getCurrentAppIdNamespace(DatastoreApiHelper.java:118)
    ....

This is probably because my test case hasn't read in the GAE application-web.xml with the app details (although I'm guessing here I could really be wrong); so it doesn't know to write to the same datastore that the app running on the dev_server is reading/writing to.

How can I get my test to "point" to the same datastore as the app?  Is there some "datasource" mechanism that I can inject both into the app and the test?  Is there a way to get my test to force the datastore api to read the needed config?

ContentLicense: CC BY-SA 2.5


问:
Speed up split and write out to file in python
I'm curious if there is a faster way to deal with big text files...
I need to read quite a huge TXT file ( around 40MB :-/ ) which contains data separated by ";", remove the first 10 line as they are informative and not the main data, and then output just the first instance from each line so line[0] after split...

My current code does what it needs to, but it takes forever...

```<code>def remove_lines(input, output):
    lines = open(input).readlines()
    # clean the file before use
    open('output', 'w').close()
    # remove first lines and split by ; then output
    for l in lines[10:]:
        l = l.split(';')
        open(output, 'a').write(l[0] + "\n")
</code>```

Its not like I need to do it often, maybe once a week so I can let it crunch as long as I want, but I'm curious if it can be speed up somehow...

答:
As @zwer's solution, reading and processing in the loop allows I/O and cpu to be better utilized / interleaved ... And save memory.
This is more readable to my eyes:

```<code>def remove_lines(in_file, out_file):
    with open(in_file) as input, open(out_file, 'w') as output:
        for _ in range(10):
            input.readline()
        for line in input:
            output.write(line.split(';',1)[0] + '\n')
</code>```

With a small amount of cpu mixed with I/O there is not much more optimizing that can be done.

Body:
I'm curious if there is a faster way to deal with big text files...
I need to read quite a huge TXT file ( around 40MB :-/ ) which contains data separated by ";", remove the first 10 line as they are informative and not the main data, and then output just the first instance from each line so line[0] after split...

My current code does what it needs to, but it takes forever...

def remove_lines(input, output):
    lines = open(input).readlines()
    # clean the file before use
    open('output', 'w').close()
    # remove first lines and split by ; then output
    for l in lines[10:]:
        l = l.split(';')
        open(output, 'a').write(l[0] + "\n")

Its not like I need to do it often, maybe once a week so I can let it crunch as long as I want, but I'm curious if it can be speed up somehow...

Body:
As @zwer's solution, reading and processing in the loop allows I/O and cpu to be better utilized / interleaved ... And save memory.
This is more readable to my eyes:

def remove_lines(in_file, out_file):
    with open(in_file) as input, open(out_file, 'w') as output:
        for _ in range(10):
            input.readline()
        for line in input:
            output.write(line.split(';',1)[0] + '\n')

With a small amount of cpu mixed with I/O there is not much more optimizing that can be done.


问:
rstrip on python behaving awkwardly: 'HelloWorld'.rstrip('World') deletes everything after 'He'

I had started learning python recently, and I have encountered a awkward behavior with rstrip.

My understanding is that the str.rstrip() will delete all characters as soon as it encounters one of the character it took in an argument.

```<code>>>> a = 'HelloWorld'
>>> a.rstrip('l')
'HelloWorld'
>>> a = 'HelloWorld'
>>> a.rstrip('World')
'He'
</code>```

I'm totally confused by the result I've got.

Shouldn't the first code supposed be producing 'He' instead?

答:
The [rl]strip methods strip away any char that is in the string that you pass as argument. Since l and o are in 'World', they get stripped as well.

From the rstrip docs:

the characters in the string will be stripped from the end of the string this method is called on.

... not the string passed itself is stripped, but its characters!

Body:
I had started learning python recently, and I have encountered a awkward behavior with rstrip.

My understanding is that the str.rstrip() will delete all characters as soon as it encounters one of the character it took in an argument.

>>> a = 'HelloWorld'
>>> a.rstrip('l')
'HelloWorld'
>>> a = 'HelloWorld'
>>> a.rstrip('World')
'He'

I'm totally confused by the result I've got.

Shouldn't the first code supposed be producing 'He' instead?


问:
PHP - How do you find files with the same numerical prefix and store them in an array
I have a directory of images and I need to be able to scan through the directory and find files with the same numerical prefix and store them in a list/array

images/

1a.jpg

1b.jpg

1c.jpg

2a.jpg

2b.jpg

.

.

.

10a.jpg

10b.jpg

.

.

.

100a.jpg

100b.jpg

100c.jpg

.

etc.

Desired outcome after function

list "1"

1a.jpg

1b.jpg

1c.jpg

.

.

.

list "2"

2a.jpg

2b.jpg

.

.

.

list "10"

10a.jpg

10b.jpg

.

.

.

list "100"

100a.jpg

100b.jpg

100c.jpg

.

etc.

from what I've gobbled up in my research. I'm guessing it should go something like this:

```<code><?php
    // find image files starting with number prefix(1,2...10...100...etc)

    foreach (glob("1*.jpg") as $filename) {
        echo "$filename";
    }
?>
</code>```

The above example will output something similar to:

1a.jpg

1b.jpg

1c.jpg

But How do I run this function for all files in my directory? (1a.jpg, 2a.jpg, 3a.jpg... 24a.jpg.. 112a.jpg, 112b.jpg)

答:
Have a look at the glob php function, seems to fit your needs.</p>

```<code>glob("images/1[a-z].jpg");
glob("images/10[a-z].jpg");
//example for your need 1 followed by everything but not a number :
glob("images/1[^0-9]*.jpg");
</code>```

Body:
I have a directory of images and I need to be able to scan through the directory and find files with the same numerical prefix and store them in a list/array

images/

1a.jpg

1b.jpg

1c.jpg

2a.jpg

2b.jpg

.

.

.

10a.jpg

10b.jpg

.

.

.

100a.jpg

100b.jpg

100c.jpg

.

etc.

Desired outcome after function

list "1"

1a.jpg

1b.jpg

1c.jpg

.

.

.

list "2"

2a.jpg

2b.jpg

.

.

.

list "10"

10a.jpg

10b.jpg

.

.

.

list "100"

100a.jpg

100b.jpg

100c.jpg

.

etc.

from what I've gobbled up in my research. I'm guessing it should go something like this:

<?php
    // find image files starting with number prefix(1,2...10...100...etc)

    foreach (glob("1*.jpg") as $filename) {
        echo "$filename";
    }
?>

The above example will output something similar to:

1a.jpg

1b.jpg

1c.jpg

But How do I run this function for all files in my directory? (1a.jpg, 2a.jpg, 3a.jpg... 24a.jpg.. 112a.jpg, 112b.jpg)

Body:
Have a look at the glob php function, seems to fit your needs.

glob("images/1[a-z].jpg");
glob("images/10[a-z].jpg");
//example for your need 1 followed by everything but not a number :
glob("images/1[^0-9]*.jpg");


问:
MIkrotik backup script
I need your help, I am trying to create a backup file on mikrotik, but it always fail to create a backup can you help me please?

```<code>/system backup save name=([/system identity get name]"_"[/system clock get date]"log")
</code>```

Format  should be Hostname_MonthDaybackup.backup. For example Mikrotik_1205Log.backup

Can you help me please? Thank you.

Adrian

答: and you can easily backup configuration of mikrotik by winbox -> files section then copy backup file to your system by drag & drop . and you can show history of older backup files. or restore any of backup files </p>

Title: MIkrotik backup script

Body:
I need your help, I am trying to create a backup file on mikrotik, but it always fail to create a backup can you help me please?

/system backup save name=([/system identity get name]"_"[/system clock get date]"log")

Format  should be Hostname_MonthDaybackup.backup. For example Mikrotik_1205Log.backup

Can you help me please? Thank you.

Adrian


问:
How to run dos2unix for all the files in subfolders in bash?
I am using dos2unix *.sh to convert all the .sh files in the current directory.

So how to convert all the .sh files in the subfolders as well?

I tried this but it does not work for bash:
How to run dos2unix for all files in a directory and subdirecty in Powershell

答:
you could use find:

```<code>find . -type f -name "*.sh" -exec dos2unix {} \+;
</code>```

this locates all *.sh (-name "*.sh") files (-type f) in the current directory (recursing into subdirectories as well) and executes on all of them the dos2unix utility

Body:
you could use find:

find . -type f -name "*.sh" -exec dos2unix {} \+;

this locates all *.sh (-name "*.sh") files (-type f) in the current directory (recursing into subdirectories as well) and executes on all of them the dos2unix utility


问:
What is the fastest sorting algorithm for a small number of integers?
I am wondering what the fastest algorithm would be for this.  I have 8 integers between 0 and 3000 and I need to sort them.  Although there are only 8 integers, this operation will be performed millions of times.</p>

答: For very small numbers of ints, bubble sort can be very fast.  Bubble sort with numerical comparisons can be written with a very low overhead and for small n, the actual speed differences between O(n log n) and O(n^2) washes out.</p>


问:
How to forcefully remove Google default selected Account in Gmail API?
I am trying to remove default selected account from gmail api when logout from app in android.

this is GoogleAccountCredential  function to establish connection of gmail account.

```<code>GoogleAccountCredential  mCredential = GoogleAccountCredential.usingOAuth2(
                getApplicationContext(), Arrays.asList(AppController.SCOPES))
                .setBackOff(new ExponentialBackOff());
</code>```

答:
Gmail API doesn't Provide And default account select method you can just call this method to select account when required

```<code>startActivityForResult(
        mCredential.newChooseAccountIntent(),
        REQUEST_ACCOUNT_PICKER);
</code>```

just remember to pass null to mCredential when logout

Body:
I am trying to remove default selected account from gmail api when logout from app in android.

this is GoogleAccountCredential  function to establish connection of gmail account.

GoogleAccountCredential  mCredential = GoogleAccountCredential.usingOAuth2(
                getApplicationContext(), Arrays.asList(AppController.SCOPES))
                .setBackOff(new ExponentialBackOff());

Body:
Gmail API doesn't Provide And default account select method you can just call this method to select account when required

startActivityForResult(
        mCredential.newChooseAccountIntent(),
        REQUEST_ACCOUNT_PICKER);

just remember to pass null to mCredential when logout


问:
How the GNU builtin function `__builtin_unreachable ` works in this code snippet?
I have a code snippet in my project in which the __builtin_unreachable function has been used but I don't know why it is needed here.

And I read from GNU __builtin_unreachable, it seems that the __builtin_unreachable function is used to inform the compiler this line will never be reached during the CPU run time, so that a lot of complains in compilation can be prevented in advance. But I am not understood why this feature is needed in this code snippet, it seems nothing will happen by removing the __builtin_unreachable.

```<code># define ATHCONTAINERS_ASSUME(x) do { if (!(x)) __builtin_unreachable(); } while(0)

inline
void*
AuxVectorData::Cache::getDataArray (SG::auxid_t auxid,
                                    AuxVectorData& parent)
{
  // This function is important for performance.
  // Be careful when changing it.

  void* ptr = cachePtr (auxid);
  if (ATHCONTAINERS_UNLIKELY (ptr == 0)) {
    // We don't have the variable cached.
    // Call the out-of-line routine to get it cached.
    ptr = parent.getDataOol (auxid, false);

    // These inform the compiler of what the previous call did.
    // They tell the optimizer that it can now assume that this cache
    // entry is valid.
    ATHCONTAINERS_ASSUME (ptr != 0);
    ATHCONTAINERS_ASSUME (cachePtr (auxid) != 0);
    ATHCONTAINERS_ASSUME (cachePtr (auxid) == ptr);
  }
  return ptr;
}
</code>```

答:
As the code comment indicates, it tells stories to the optimizer.

The first thing this tells, is that the compiler can assume that the return value is not a null pointer. It would probably improve the readability of the code if another gcc extension would be used instead, namely
__attribute__((__returns_nonnull__)). Adding this to the interface of getDataArray would also guarantee that property, even if the the compiler decides that he can't inline it for whatever reason.

But it is telling more than that. It also tells (or tries to tell) that future calls to cachePtr with the same parameter will return the same result.

All these properties would probably better be guaranteed by removing the unused parent parameter (to avoid aliasing analysis) and by also adding __attribute__((__const__)) to getDataArray.

Body:
I have a code snippet in my project in which the __builtin_unreachable function has been used but I don't know why it is needed here.

And I read from GNU __builtin_unreachable, it seems that the __builtin_unreachable function is used to inform the compiler this line will never be reached during the CPU run time, so that a lot of complains in compilation can be prevented in advance. But I am not understood why this feature is needed in this code snippet, it seems nothing will happen by removing the __builtin_unreachable.

# define ATHCONTAINERS_ASSUME(x) do { if (!(x)) __builtin_unreachable(); } while(0)

inline
void*
AuxVectorData::Cache::getDataArray (SG::auxid_t auxid,
                                    AuxVectorData& parent)
{
  // This function is important for performance.
  // Be careful when changing it.

  void* ptr = cachePtr (auxid);
  if (ATHCONTAINERS_UNLIKELY (ptr == 0)) {
    // We don't have the variable cached.
    // Call the out-of-line routine to get it cached.
    ptr = parent.getDataOol (auxid, false);

    // These inform the compiler of what the previous call did.
    // They tell the optimizer that it can now assume that this cache
    // entry is valid.
    ATHCONTAINERS_ASSUME (ptr != 0);
    ATHCONTAINERS_ASSUME (cachePtr (auxid) != 0);
    ATHCONTAINERS_ASSUME (cachePtr (auxid) == ptr);
  }
  return ptr;
}


问:
How to get the dropdown nav child elements to follow the parent position from top
Progress and what I want to do should be clear here:

https://codepen.io/RautSamir/pen/RjzEKY

Under Offices, I need the child objects to show right under and hopefully same width as parent.

code:

```<code>    <div class="navItem" style="display:inline">
<button class="dropbtn"> Home </button>
</div>

<div class="dropdown" style="display:inline">
<button onclick="myFunction()" class="dropbtn">Offices</button>
  <div id="myDropdown" class="dropdown-content">
    <a href="#home">Regional</a>
    <a href="#about">Global</a>
    <a href="#contact">Local</a>
  </div>
</div>

<div class="navItem" style="display:inline">
<button class="dropbtn"> Who we are</button>
</div>

<div class="navItem" style="display:inline">
<button class="dropbtn"> Contact </button>
</div>

<div class="navItem" style="display:inline">
<button class="dropbtn" id="searchBox"> Search </button>
</div>
</code>```

答:
The changes made :

Setting width to 100%(you can adjust the size and reduce it to 97,98 so the additional padding isn't in effect and it looks perfectly aligned to the action button) and removing min-width from dropdown content.

Using left:0 so that the dropdown gets aligned with respect to parent element.

The offices parent div should also have the class of "navItem" since its one of the rest of your inline buttons.

Codepen : https://codepen.io/anon/pen/YEodjR

function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {

    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dropbtn {
  background-color: gray;
  color: white;
  padding: 16px;
  font-size: 16px;
  border: none;
  cursor: pointer;
  width: 19.5%;
}

.dropbtn:hover,
.dropbtn:focus {
  background-color: black;
  text-style: bold;
}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  left: 0;
  background-color: #f9f9f9;
  width: 98%;
  overflow: auto;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown a:hover {
  background-color: #f1f1f1
}

.show {
  display: block;
}</code>```

  <button class="dropbtn"> Home </button>

  <button onclick="myFunction()" class="dropbtn">Offices</button>

    Regional
    Global
    Local

  <button class="dropbtn"> Who we are</button>

  <button class="dropbtn"> Contact </button>

  <button class="dropbtn" id="searchBox"> Search </button>

```

Body:
Progress and what I want to do should be clear here:

https://codepen.io/RautSamir/pen/RjzEKY

Under Offices, I need the child objects to show right under and hopefully same width as parent.

code:

<button class="dropbtn"> Home </button>

<button onclick="myFunction()" class="dropbtn">Offices</button>

    Regional
    Global
    Local

<button class="dropbtn"> Who we are</button>

<button class="dropbtn"> Contact </button>

<button class="dropbtn" id="searchBox"> Search </button>

Body:
The changes made :

Setting width to 100%(you can adjust the size and reduce it to 97,98 so the additional padding isn't in effect and it looks perfectly aligned to the action button) and removing min-width from dropdown content.

Using left:0 so that the dropdown gets aligned with respect to parent element.

The offices parent div should also have the class of "navItem" since its one of the rest of your inline buttons.

Codepen : https://codepen.io/anon/pen/YEodjR

function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {

    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}

.dropbtn {
  background-color: gray;
  color: white;
  padding: 16px;
  font-size: 16px;
  border: none;
  cursor: pointer;
  width: 19.5%;
}

.dropbtn:hover,
.dropbtn:focus {
  background-color: black;
  text-style: bold;
}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  left: 0;
  background-color: #f9f9f9;
  width: 98%;
  overflow: auto;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown a:hover {
  background-color: #f1f1f1
}

.show {
  display: block;
}

<div class="navItem" style="display:inline">
  <button class="dropbtn"> Home </button>
</div>

<div class="navItem dropdown" style="display:inline">
  <button onclick="myFunction()" class="dropbtn">Offices</button>
  <div id="myDropdown" class="dropdown-content">
    <a href="#home">Regional</a>
    <a href="#about">Global</a>
    <a href="#contact">Local</a>
  </div>
</div>

<div class="navItem" style="display:inline">
  <button class="dropbtn"> Who we are</button>
</div>

<div class="navItem" style="display:inline">
  <button class="dropbtn"> Contact </button>
</div>

<div class="navItem" style="display:inline">
  <button class="dropbtn" id="searchBox"> Search </button>
</div>


问:
Intermittent issue of HttpAntiForgeryException on Production only
I am getting AntiForgery error on Production server intermittently.
Details:-

Issue occurred on login page only, After reload it works

Issue is intermittent

Form authentication is used and site is deployed on single server.

System.Web.Mvc.HttpAntiForgeryException (0x80004005): The anti-forgery
   cookie token and form field token do not match.
  Steps to produce:-
  * Logged in to site
  * Leave it open for long or close the browse
  * Open the login page again after 1-2 hour..
  you may get this error of anti forgery token "The anti-forgery
   cookie token and form field token do not match."
  But its not guaranteed that we encounter error. We get error only intermittently which gets resolved once user try to login again.

I tried so many option but could not resolve the issue.

答:
the reason for this error can be
 1. you have setup the server at a new location or
 2. you have reset the IIS while the application is still in use for some client (because on reset it generates a new token for that session)</p>


问:
Convert Column of List to Dataframe
I have a column of lists in a spark dataframe. </p>

<pre class="lang-python prettyprint-override"><code>+-----------------+
|features         |
+-----------------+
|[0,45,63,0,0,0,0]|
|[0,0,0,85,0,69,0]|
|[0,89,56,0,0,0,0]|
+-----------------+
</code>```

<p>How do I convert that to a spark dataframe where each element in the list is a column in the dataframe? We can assume that the lists will be the same size. </p>

<p>For Example, </p>

<pre class="lang-python prettyprint-override"><code>+--------------------+
|c1|c2|c3|c4|c5|c6|c7|
+--------------------+
|0 |45|63|0 |0 |0 |0 |
|0 |0 |0 |85|0 |69|0 |
|0 |89|56|0 |0 |0 |0 |
+--------------------+
</code>```

Title: Convert Column of List to Dataframe

Body:
I have a column of lists in a spark dataframe.

+-----------------+
|features         |
+-----------------+
|[0,45,63,0,0,0,0]|
|[0,0,0,85,0,69,0]|
|[0,89,56,0,0,0,0]|
+-----------------+

How do I convert that to a spark dataframe where each element in the list is a column in the dataframe? We can assume that the lists will be the same size.

For Example,

+--------------------+
|c1|c2|c3|c4|c5|c6|c7|
+--------------------+
|0 |45|63|0 |0 |0 |0 |
|0 |0 |0 |85|0 |69|0 |
|0 |89|56|0 |0 |0 |0 |
+--------------------+

Body:
What you describe is actually the invert of the VectorAssembler operation.

You can do it by converting to an intermediate RDD, as follows:

spark.version
# u'2.2.0'

# your data:
df.show(truncate=False)
# +-----------------+
# |        features |
# +-----------------+
# |[0,45,63,0,0,0,0]|
# |[0,0,0,85,0,69,0]|
# |[0,89,56,0,0,0,0]|
# +-----------------+

dimensionality = 7
out = df.rdd.map(lambda x: [float(x[0][i]) for i in range(dimensionality)]).toDF(schema=['c'+str(i+1) for i in range(dimensionality)])
out.show()
# +---+----+----+----+---+----+---+
# | c1|  c2|  c3|  c4| c5|  c6| c7|
# +---+----+----+----+---+----+---+
# |0.0|45.0|63.0| 0.0|0.0| 0.0|0.0|
# |0.0| 0.0| 0.0|85.0|0.0|69.0|0.0|
# |0.0|89.0|56.0| 0.0|0.0| 0.0|0.0|
# +---+----+----+----+---+----+---+


问:
Custom errormessage for property converter
Is it possible to use a ressource to set the errormessage on a property convert error?

```<code>[Range(0, 10, ErrorMessageResourceName = "Error", ErrorMessageResourceType = typeof(Properties.Resources))]
[DataMember]
public int MyProperty
{
  get; set;
}
</code>```

The problem occourres if I try to set MyProperty to "aaa". I get an error saying "Cannot convert 'aaa'". It is that message that I wish to customize.

答: I found a solution for my problem. I have created an extention for the controls I use in my XAML code (typically a TextBox). In the extention I handle the format exception and find the appropriate resource.</p>

Body:
Is it possible to use a ressource to set the errormessage on a property convert error?

[Range(0, 10, ErrorMessageResourceName = "Error", ErrorMessageResourceType = typeof(Properties.Resources))]
[DataMember]
public int MyProperty
{
  get; set;
}

The problem occourres if I try to set MyProperty to "aaa". I get an error saying "Cannot convert 'aaa'". It is that message that I wish to customize.


问:
Symfony2: How to access to service from repository
I have class ModelsRepository:

```<code>class ModelsRepository extends EntityRepository
{}
</code>```

And service

```<code>container_data:
 class:        ProjectName\MyBundle\Common\Container
 arguments:    [@service_container]
</code>```

I want get access from ModelsRepository to service container_data. I can't transmit service from controller used constructor.

Do you know how to do it?

答:
I strongly agree that this should only be done when absolutely necessary. Though there is a quite simpler approach possible now (tested with Symfony 2.8).

Implement in your repository "ContainerAwareInterface"

Use the "ContainerAwareTrait"

adjust the services.yml

RepositoryClass:

```<code>namespace AcmeBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use AcmeBundle\Entity\User;

class UserRepository extends EntityRepository implements ContainerAwareInterface
{

    use ContainerAwareTrait;

    public function findUserBySomething($param)
    {
        $service = $this->container->get('my.other.service');
    }

}
</code>```

services.yml:

```<code>acme_bundle.repository.user:
    lazy: true
    class: AcmeBundle\Repository\UserRepository
    factory: ['@doctrine.orm.entity_manager', getRepository]
    arguments:
        - "AcmeBundle:Entity/User"
    calls:
        - method: setContainer
          arguments:
            - '@service_container'
</code>```

Body:
I have class ModelsRepository:

class ModelsRepository extends EntityRepository
{}

And service

container_data:
 class:        ProjectName\MyBundle\Common\Container
 arguments:    [@service_container]

I want get access from ModelsRepository to service container_data. I can't transmit service from controller used constructor.

Do you know how to do it?

Body:
I strongly agree that this should only be done when absolutely necessary. Though there is a quite simpler approach possible now (tested with Symfony 2.8).

Implement in your repository "ContainerAwareInterface"

Use the "ContainerAwareTrait"

adjust the services.yml

RepositoryClass:

namespace AcmeBundle\Repository;

use Doctrine\ORM\EntityRepository;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use AcmeBundle\Entity\User;

class UserRepository extends EntityRepository implements ContainerAwareInterface
{

    use ContainerAwareTrait;

    public function findUserBySomething($param)
    {
        $service = $this->container->get('my.other.service');
    }

}

services.yml:

acme_bundle.repository.user:
    lazy: true
    class: AcmeBundle\Repository\UserRepository
    factory: ['@doctrine.orm.entity_manager', getRepository]
    arguments:
        - "AcmeBundle:Entity/User"
    calls:
        - method: setContainer
          arguments:
            - '@service_container'


问:
Regex - International Password Match Expression
I'm trying to compose a pattern which matches passwords in any language.

The matcher requirement is :-

1 Upper Char (Min)

1 Lower Char (Min)

1 Digit (Min)

1 Symbol (Min)

8 Characters length or above

As i'm sure you can see from my pattern below, I'm lost!!

/^(?=.*[\p{Ll}])(?=.*[\p{Lu}])(?=.*\p{Nd})(?=.*[@$!%*?&])[\p{Lu}\p{Ll}\p{Nd}$@$!%*?&]{8,}$/u

Test strings

关键字157aA$89

P455word123!

答:
The \p{Lu} matches uppercase Unicode letters, and \p{Ll} matches lowercase Unicode letters. Chinese letters are caseless, they can be matched with \p{L} (together with all other letters).

Use \p{L} in the consuming part:

```<code>/^(?=.*\p{Ll})(?=.*\p{Lu})(?=.*\p{Nd})(?=.*[@$!%*?&])[\p{L}\p{Nd}@$!%*?&]{8,}$/u
                                                      ^^^^^
</code>```

See this regex demo.

Note that a password will still have to have an uppercase and lowercase letters. If you just want to require a Chinese letter or an uppercase with lowercase letters, use

```<code>/^(?:(?=.*\p{Han})|(?=.*\p{Ll})(?=.*\p{Lu}))(?=.*\p{Nd})(?=.*[@$!%*?&])[\p{L}\p{Nd}$@!%*?&]{8,}$/u
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
</code>```

Here, (?:(?=.*\p{Han})|(?=.*\p{Ll})(?=.*\p{Lu})) will require either a Chinese letter (\p{Han}) or an uppercase+lowercase letter.

Body:
The \p{Lu} matches uppercase Unicode letters, and \p{Ll} matches lowercase Unicode letters. Chinese letters are caseless, they can be matched with \p{L} (together with all other letters).

Use \p{L} in the consuming part:

/^(?=.*\p{Ll})(?=.*\p{Lu})(?=.*\p{Nd})(?=.*[@$!%*?&])[\p{L}\p{Nd}@$!%*?&]{8,}$/u
                                                      ^^^^^

See this regex demo.

Note that a password will still have to have an uppercase and lowercase letters. If you just want to require a Chinese letter or an uppercase with lowercase letters, use

/^(?:(?=.*\p{Han})|(?=.*\p{Ll})(?=.*\p{Lu}))(?=.*\p{Nd})(?=.*[@$!%*?&])[\p{L}\p{Nd}$@!%*?&]{8,}$/u
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Here, (?:(?=.*\p{Han})|(?=.*\p{Ll})(?=.*\p{Lu})) will require either a Chinese letter (\p{Han}) or an uppercase+lowercase letter.


问:
How to find minimum of BigDecimal field in collection with java streams?
I want to use java streams to iterate a list and find the BigDecimal minimum price. The following illustrates, but does not work (because min() cannot accept BigDecimal.

```<code>class Product {
    public BigDecimal price;
}

List<Product> products;
products.stream().min((Product) p -> p.price);
</code>```

答:
To solve this, please use the following code:

```<code>products.stream().min(Comparator.comparing(p -> p.price)).get();
</code>```

Comparator.comparing method requires a Function that takes an input and returns a Comparable. This Comparable, in turn, is used by the comparing method to create a Comparator. The min method uses the Comparator to compare the elements in the stream.
The lambda expression p->p.price creates a Function that takes an BigDecimal and returns an BigDecimal (which is a Comparable). Here, the lambda expression does not do much but in situations where you have a class that doesn't implement Comparable and you want to compare objects of that class using a property of that class that is Comparable, this is very useful.
The call to get() is required because max(Comparator) return an Optional object.

Body:
I want to use java streams to iterate a list and find the BigDecimal minimum price. The following illustrates, but does not work (because min() cannot accept BigDecimal.

class Product {
    public BigDecimal price;
}

List<Product> products;
products.stream().min((Product) p -> p.price);

Body:
To solve this, please use the following code:

products.stream().min(Comparator.comparing(p -> p.price)).get();

Comparator.comparing method requires a Function that takes an input and returns a Comparable. This Comparable, in turn, is used by the comparing method to create a Comparator. The min method uses the Comparator to compare the elements in the stream.
The lambda expression p->p.price creates a Function that takes an BigDecimal and returns an BigDecimal (which is a Comparable). Here, the lambda expression does not do much but in situations where you have a class that doesn't implement Comparable and you want to compare objects of that class using a property of that class that is Comparable, this is very useful.
The call to get() is required because max(Comparator) return an Optional object.


问:
Issue with Powermock
I am trying to use Powermockito in my test cases to test a void delete()method inside of a legacy public final ClassToTest but its throwing this exception when I am calling mockStatic on ClassToTest

Here is the exception :

```<code>java.lang.NoClassDefFoundError:

org/mockito/internal/creation/instance/InstantationException
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMethodInvocationControl(DefaultMockCreator.java:121)
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMock(DefaultMockCreator.java:69)
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.mock(DefaultMockCreator.java:46)
    at org.powermock.api.mockito.PowerMockito.mockStatic(PowerMockito.java:71)
    at nl.naturalis.nba.etl.ClassToTestTest.testLogDuration(ClassToTestTest.java:87)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:326)
    at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89)
    at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:310)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:131)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.access$100(PowerMockJUnit47RunnerDelegateImpl.java:59)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner$TestExecutorStatement.evaluate(PowerMockJUnit47RunnerDelegateImpl.java:147)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.evaluateStatement(PowerMockJUnit47RunnerDelegateImpl.java:107)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:298)
    at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
    at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:218)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:160)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:134)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:136)
    at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:121)
    at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:57)
    at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:539)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:761)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:461)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:207)
Caused by: java.lang.ClassNotFoundException: org.mockito.internal.creation.instance.InstantationException
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:202)
    at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass1(DeferSupportingClassLoader.java:89)
    at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:79)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 37 more
</code>```

My ivy.xml for dependencies looks like this:

```<code><dependency org="junit" name="junit" rev="4.11"/>
<dependency org="org.mockito" name="mockito-all" rev="1.9.5"/>
<dependency org="org.powermock" name="powermock-module-junit4" rev="1.7.3"/>
<dependency org="org.powermock" name="powermock-api-mockito" rev="1.7.3"/>
<dependency org="org.powermock" name="powermock-core" rev="1.7.3"/>
</code>```

Inside the test method i m using these annotation :

```<code>@RunWith( PowerMockRunner.class )
@PrepareForTest( ClassToTest.class )
@PowerMockIgnore( {"javax.management.*"})
</code>```

I did a debug to find to find that it fails exactly at this point when it tries to load this class :

```<code>org.powermock.api.mockito.repackaged.ClassImposterizer
</code>```

Is there is something I m missing in the dependencies? or something else i am doing wrong?

答:
The org/mockito/internal/creation/instance/InstantationException class has been introduced in the 2.x version of Mockito and is not available in you 1.9.5 version.

Also based on the compatibility table, you should aim for Powermock 1.5.6 version as its the latest supporting the 1.9.5 Mockito. supported versions

Title: Issue with Powermock

Body:
I am trying to use Powermockito in my test cases to test a void delete()method inside of a legacy public final ClassToTest but its throwing this exception when I am calling mockStatic on ClassToTest

Here is the exception :

java.lang.NoClassDefFoundError:

org/mockito/internal/creation/instance/InstantationException
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMethodInvocationControl(DefaultMockCreator.java:121)
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMock(DefaultMockCreator.java:69)
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.mock(DefaultMockCreator.java:46)
    at org.powermock.api.mockito.PowerMockito.mockStatic(PowerMockito.java:71)
    at nl.naturalis.nba.etl.ClassToTestTest.testLogDuration(ClassToTestTest.java:87)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:326)
    at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89)
    at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:310)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:131)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.access$100(PowerMockJUnit47RunnerDelegateImpl.java:59)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner$TestExecutorStatement.evaluate(PowerMockJUnit47RunnerDelegateImpl.java:147)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.evaluateStatement(PowerMockJUnit47RunnerDelegateImpl.java:107)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:298)
    at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
    at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:218)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:160)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:134)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:136)
    at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:121)
    at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:57)
    at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:539)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:761)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:461)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:207)
Caused by: java.lang.ClassNotFoundException: org.mockito.internal.creation.instance.InstantationException
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:202)
    at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass1(DeferSupportingClassLoader.java:89)
    at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:79)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 37 more

My ivy.xml for dependencies looks like this:

<dependency org="junit" name="junit" rev="4.11"/>
<dependency org="org.mockito" name="mockito-all" rev="1.9.5"/>
<dependency org="org.powermock" name="powermock-module-junit4" rev="1.7.3"/>
<dependency org="org.powermock" name="powermock-api-mockito" rev="1.7.3"/>
<dependency org="org.powermock" name="powermock-core" rev="1.7.3"/>

Inside the test method i m using these annotation :

@RunWith( PowerMockRunner.class )
@PrepareForTest( ClassToTest.class )
@PowerMockIgnore( {"javax.management.*"})

I did a debug to find to find that it fails exactly at this point when it tries to load this class :

org.powermock.api.mockito.repackaged.ClassImposterizer

Is there is something I m missing in the dependencies? or something else i am doing wrong?


答:
Define the left position as zero (relative to it's parent, not the window).

To make it as width as it's parent, use right: 0.

You'll notice a 4px difference, that's because of the inline-block on the parent. You can fix that by setting the right position to 4px.

function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {

    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dropbtn {
  background-color: gray;
  color: white;
  padding: 16px;
  font-size: 16px;
  border: none;
  cursor: pointer;
  width: 19.5%;
}

.dropbtn:hover,
.dropbtn:focus {
  background-color: black;
  /*invalid
  text-style: bold;*/
}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  overflow: auto;
  left: 0;
  right: 4px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown a:hover {
  background-color: #f1f1f1
}

.show {
  display: block;
}</code>```

  <button class="dropbtn"> Home </button>

  <button onclick="myFunction()" class="dropbtn">Offices</button>

    Regional
    Global
    Local

  <button class="dropbtn"> Who we are</button>

  <button class="dropbtn"> Contact </button>

  <button class="dropbtn" id="searchBox"> Search </button>

```

Title: How to get the dropdown nav child elements to follow the parent position from top

Body:
Define the left position as zero (relative to it's parent, not the window).

To make it as width as it's parent, use right: 0.

You'll notice a 4px difference, that's because of the inline-block on the parent. You can fix that by setting the right position to 4px.

function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {

    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}

.dropbtn {
  background-color: gray;
  color: white;
  padding: 16px;
  font-size: 16px;
  border: none;
  cursor: pointer;
  width: 19.5%;
}

.dropbtn:hover,
.dropbtn:focus {
  background-color: black;
  /*invalid
  text-style: bold;*/
}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  overflow: auto;
  left: 0;
  right: 4px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown a:hover {
  background-color: #f1f1f1
}

.show {
  display: block;
}

<div class="navItem" style="display:inline">
  <button class="dropbtn"> Home </button>
</div>

<div class="dropdown" style="display:inline">
  <button onclick="myFunction()" class="dropbtn">Offices</button>
  <div id="myDropdown" class="dropdown-content">
    <a href="#home">Regional</a>
    <a href="#about">Global</a>
    <a href="#contact">Local</a>
  </div>
</div>

<div class="navItem" style="display:inline">
  <button class="dropbtn"> Who we are</button>
</div>

<div class="navItem" style="display:inline">
  <button class="dropbtn"> Contact </button>
</div>

<div class="navItem" style="display:inline">
  <button class="dropbtn" id="searchBox"> Search </button>
</div>


答:
try to use in intellij Idea dependency analyzer plugin and resolve conflicts, this is looks like a dependency conflict.
PS update mockito to the latest 2.* version, i did it without conflicts or problems and the new version is very good </p>

Title: Issue with Powermock


问:
DoCmd.ApplyFilter Syntax
I'm having a little trouble applying a filter that refers to multiple text boxes in a form for the Where Condition.

I have a button called Search_All, and am trying to set up the first two text boxes:

```<code>Private Sub Search_All_Click()
       DoCmd.ApplyFilter , "[ESN] like '*' & [Forms]![Search]![ESN TEXT]  & '*' Or [CommentsField] like '*' & [Forms]![Search]![COMMENTS TEXT] & '*'"
End Sub
</code>```

I can enter a value for ESN and filter successfully, but when I enter something into the COMMENTS TEXT it filters everything out and doesn't display any records.

答:
Try cleaning up the quotes:</p>

```<code>DoCmd.ApplyFilter , "[ESN] Like '*" & [Forms]![Search]![ESN TEXT]  & "*' Or [CommentsField] Like '*" & [Forms]![Search]![COMMENTS TEXT] & "*'"
</code>```

Title: DoCmd.ApplyFilter Syntax

Body:
I'm having a little trouble applying a filter that refers to multiple text boxes in a form for the Where Condition.

I have a button called Search_All, and am trying to set up the first two text boxes:

Private Sub Search_All_Click()
       DoCmd.ApplyFilter , "[ESN] like '*' & [Forms]![Search]![ESN TEXT]  & '*' Or [CommentsField] like '*' & [Forms]![Search]![COMMENTS TEXT] & '*'"
End Sub

I can enter a value for ESN and filter successfully, but when I enter something into the COMMENTS TEXT it filters everything out and doesn't display any records.

Body:
Try cleaning up the quotes:

DoCmd.ApplyFilter , "[ESN] Like '*" & [Forms]![Search]![ESN TEXT]  & "*' Or [CommentsField] Like '*" & [Forms]![Search]![COMMENTS TEXT] & "*'"


问:
Soft Keyboard copies UI part
I am new to android and creating an registration form in app. When we click on edit text soft keyboard opens. but when keyboard opens it shows part of ui in keyboard suggestion. the image is below.

thanks in advance for any help.

The image link is below

答:
In your AndroidManifest.xml add this line:

```<code>android:windowSoftInputMode="adjustPan"
</code>```

This will not push/cover your UI.

Title: Soft Keyboard copies UI part

Body:
In your AndroidManifest.xml add this line:

android:windowSoftInputMode="adjustPan"

This will not push/cover your UI.


问:
Creating a Google Apps Script to convert data in a spreadsheet to lines of code
I am attempting to build a script using Google Apps Scripts that will take data inputted in a spreadsheet, and convert it into a specified type of code.

Meaning, data would be inputted into a spreadsheet in Google Drive Spreadsheets, then we would run this script to convert the data that was entered into the spreadsheet into a JSON code file that Roku uses with there Direct Publisher service to create a feed for a Roku app. The plan is to allow people, who do not know how to code a JSON file to be able to input data into the spreadsheet (new content for the Roku Streaming App), and then have a script create the code based on the spreadsheet and update the file that is sent to Roku for the app.

I understand how to code in JSON, but I am not sure how to go about creating a script to take the data in a spreadsheet and convert it to the JSON code format. Any help or ideas??

答:
You can make a spreadsheet with a key column (column 1) and a value column (column2).
Then use:

```<code>var sheet = SpreadsheetApp.getActivateSheet(),
    sheetRows = sheet.getSheetValues(1, 1, sheet.getLastRow(), 2),
    jsonObject = sheetRows.reduce(function(roku, row) {
        if (row[0] === '') {
            return;
        }
        roku[row[0]] = row[1];
        return roku;
    }, {});

Drive.createFile(Utilities.newBlob(JSON.stringify(jsonObject, null, '\t')).setName('roku.json');
</code>```

The code uses Array.reduce to transfere the rows into an object and JSON.stringify to convert it to JSON. It then saves the JSON file in the users drive as roku.json.

A way to give this functionality to your users can be through a custom menu.

Body:
You can make a spreadsheet with a key column (column 1) and a value column (column2).
Then use:

var sheet = SpreadsheetApp.getActivateSheet(),
    sheetRows = sheet.getSheetValues(1, 1, sheet.getLastRow(), 2),
    jsonObject = sheetRows.reduce(function(roku, row) {
        if (row[0] === '') {
            return;
        }
        roku[row[0]] = row[1];
        return roku;
    }, {});

Drive.createFile(Utilities.newBlob(JSON.stringify(jsonObject, null, '\t')).setName('roku.json');

The code uses Array.reduce to transfere the rows into an object and JSON.stringify to convert it to JSON. It then saves the JSON file in the users drive as roku.json.

A way to give this functionality to your users can be through a custom menu.

ContentLicense: CC BY-SA 4.0


问:
Looping through models content in Razor
I want to loop through each item in my model in my razor view but I want to group all items together. I then want to loop through each group. Imagine I have a table:

```<code>ID   GroupNo    GroupName
1    1          Group1
2    1          Group2
3    1          Group3
4    2          Group1
5    2          Group2
6    3          Group56
</code>```

I want to do something like:

```<code>@foreach (var group in Model.GroupNo) {
    <section>
        <header>Group No is @group.GroupNo</header>
        @foreach (var item in group) {
            <p>GroupName: @item.GroupName</p>
        }
    </section>
}
</code>```

So my output is:

```<code>Group No is 1
GroupName: Group1
GroupName: Group2
GroupName: Group3
Group No is 2
GroupName: Group1
GroupName: Group2
Group No is 3
GroupName: Group56
</code>```

Is this possible?

Thanks

答:
```<code>@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>

        @{
            String[] name = {"Prashant", "Rishabh", "Zaheer", "Pratima", "Rahul"};
            int i = 1;
            while (i <= 5)
            {
                foreach(var x in name)
                {
                       <p>@i.  @x</p>
                       i++;
                };
                break;
            }
        }
    </div>
</body>
</html>

O/p-
1. Prashant

2. Rishabh

3. Zaheer

4. Pratima

5. Rahul
</code>```

Title: Looping through models content in Razor

Body:
I want to loop through each item in my model in my razor view but I want to group all items together. I then want to loop through each group. Imagine I have a table:

ID   GroupNo    GroupName
1    1          Group1
2    1          Group2
3    1          Group3
4    2          Group1
5    2          Group2
6    3          Group56

I want to do something like:

@foreach (var group in Model.GroupNo) {

        Group No is @group.GroupNo
        @foreach (var item in group) {

GroupName: @item.GroupName

        }

}

So my output is:

Group No is 1
GroupName: Group1
GroupName: Group2
GroupName: Group3
Group No is 2
GroupName: Group1
GroupName: Group2
Group No is 3
GroupName: Group56

Is this possible?

Thanks