问:
Database file is inexplicably locked during SQLite commit
I'm performing a large number of INSERTS to a SQLite database.  I'm using just one thread.  I batch the writes to improve performance and have a bit of security in case of a crash.  Basically I cache up a bunch of data in memory and then when I deem appropriate, I loop over all of that data and perform the INSERTS.  The code for this is shown below:

```<code>    public void Commit()
    {
        using (SQLiteConnection conn = new SQLiteConnection(this.connString))
        {
            conn.Open();
            using (SQLiteTransaction trans = conn.BeginTransaction())
            {
                using (SQLiteCommand command = conn.CreateCommand())
                {
                    command.CommandText = "INSERT OR IGNORE INTO [MY_TABLE] (col1, col2) VALUES (?,?)";

                    command.Parameters.Add(this.col1Param);
                    command.Parameters.Add(this.col2Param);

                    foreach (Data o in this.dataTemp)
                    {
                        this.col1Param.Value = o.Col1Prop;
                        this. col2Param.Value = o.Col2Prop;

                        command.ExecuteNonQuery();
                    }
                }
                this.TryHandleCommit(trans);
            }
            conn.Close();
        }
    }
</code>```

I now employ the following gimmick to get the thing to eventually work:

```<code>    private void TryHandleCommit(SQLiteTransaction trans)
    {
        try
        {
            trans.Commit();
        }
        catch (Exception e)
        {
            Console.WriteLine("Trying again...");
            this.TryHandleCommit(trans);
        }
    }
</code>```

I create my DB like so:

```<code>    public DataBase(String path)
    {
        //build connection string
        SQLiteConnectionStringBuilder connString = new SQLiteConnectionStringBuilder();
        connString.DataSource = path;
        connString.Version = 3;
        connString.DefaultTimeout = 5;
        connString.JournalMode = SQLiteJournalModeEnum.Persist;
        connString.UseUTF16Encoding = true;

        using (connection = new SQLiteConnection(connString.ToString()))
        {
            //check for existence of db
            FileInfo f = new FileInfo(path);

            if (!f.Exists)  //build new blank db
            {
                SQLiteConnection.CreateFile(path);
                connection.Open();

                using (SQLiteTransaction trans = connection.BeginTransaction())
                {
                    using (SQLiteCommand command = connection.CreateCommand())
                    {
                        command.CommandText = DataBase.CREATE_MATCHES;
                        command.ExecuteNonQuery();

                        command.CommandText = DataBase.CREATE_STRING_DATA;
                        command.ExecuteNonQuery();
                        //TODO add logging
                    }
                    trans.Commit();
                }
                connection.Close();
            }
        }
    }
</code>```

I then export the connection string and use it to obtain new connections in different parts of the program.

At seemingly random intervals, though at far too great a rate to ignore or otherwise workaround this problem, I get unhandled SQLiteException: Database file is locked.  This occurs when I attempt to commit the transaction.  No errors seem to occur prior to then.  This does not always happen.  Sometimes the whole thing runs without a hitch.

No reads are being performed on these files before the commits finish.

I have the very latest SQLite binary.

I'm compiling for .NET 2.0.

I'm using VS 2008.

The db is a local file.

All of this activity is encapsulated within one thread / process.

Virus protection is off (though I think that was only relevant if you were connecting over a network?).

As per Scotsman's post I have implemented the following changes:

Journal Mode set to Persist

DB files stored in C:\Docs + Settings\ApplicationData via System.Windows.Forms.Application.AppData windows call

No inner exception

Witnessed on two distinct machines (albeit very similar hardware and software)

Have been running Process Monitor - no extraneous processes are attaching themselves to the DB files - the problem is definitely in my code...

Does anyone have any idea whats going on here?

I know I just dropped a whole mess of code, but I've been trying to figure this out for way too long.  My thanks to anyone who makes it to the end of this question!

brian

UPDATES:

Thanks for the suggestions so far!  I've implemented many of the suggested changes.  I feel that we are getting closer to the answer...however...

The code above technically works however it is non-deterministic!  It is not guaranteed to do anything aside from spin in neutral forever.  In practice it seems to work somewhere between the 1st and 10th iteration.  If i batch my commits at a reasonable interval damage will be mitigated but I really do not want to leave things in this state...

More suggestions welcome!

答:
I started facing this same problem today: I'm studying asp.net mvc, building my first application completely from scratch. Sometimes, when I'd write to the database, I'd get the same exception, saying the database file was locked.

I found it really strange, since I was completely sure that there was just one connection open at that time (based on process explorer's listing of active file handles).

I've also built the whole data access layer from scratch, using System.Data.SQLite .Net provider, and, when I planned it, I took special care with connections and transactions, in order to ensure no connection or transaction was left hanging around.

The tricky part was that setting a breakpoint on ExecuteNonQuery() command and running the application in debug mode would make the error disappear!
Googling, I found something interesting on this site: http://www.softperfect.com/board/read.php?8,5775. There, someone replied the thread suggesting the author to put the database path on the anti-virus ignore list.

I added the database file to the ignore list of my anti-virus (Microsoft Security Essentials) and it solved my problem. No more database locked errors!

Body:
I'm performing a large number of INSERTS to a SQLite database.  I'm using just one thread.  I batch the writes to improve performance and have a bit of security in case of a crash.  Basically I cache up a bunch of data in memory and then when I deem appropriate, I loop over all of that data and perform the INSERTS.  The code for this is shown below:

    public void Commit()
    {
        using (SQLiteConnection conn = new SQLiteConnection(this.connString))
        {
            conn.Open();
            using (SQLiteTransaction trans = conn.BeginTransaction())
            {
                using (SQLiteCommand command = conn.CreateCommand())
                {
                    command.CommandText = "INSERT OR IGNORE INTO [MY_TABLE] (col1, col2) VALUES (?,?)";

                    command.Parameters.Add(this.col1Param);
                    command.Parameters.Add(this.col2Param);

                    foreach (Data o in this.dataTemp)
                    {
                        this.col1Param.Value = o.Col1Prop;
                        this. col2Param.Value = o.Col2Prop;

                        command.ExecuteNonQuery();
                    }
                }
                this.TryHandleCommit(trans);
            }
            conn.Close();
        }
    }

I now employ the following gimmick to get the thing to eventually work:

    private void TryHandleCommit(SQLiteTransaction trans)
    {
        try
        {
            trans.Commit();
        }
        catch (Exception e)
        {
            Console.WriteLine("Trying again...");
            this.TryHandleCommit(trans);
        }
    }

I create my DB like so:

    public DataBase(String path)
    {
        //build connection string
        SQLiteConnectionStringBuilder connString = new SQLiteConnectionStringBuilder();
        connString.DataSource = path;
        connString.Version = 3;
        connString.DefaultTimeout = 5;
        connString.JournalMode = SQLiteJournalModeEnum.Persist;
        connString.UseUTF16Encoding = true;

        using (connection = new SQLiteConnection(connString.ToString()))
        {
            //check for existence of db
            FileInfo f = new FileInfo(path);

            if (!f.Exists)  //build new blank db
            {
                SQLiteConnection.CreateFile(path);
                connection.Open();

                using (SQLiteTransaction trans = connection.BeginTransaction())
                {
                    using (SQLiteCommand command = connection.CreateCommand())
                    {
                        command.CommandText = DataBase.CREATE_MATCHES;
                        command.ExecuteNonQuery();

                        command.CommandText = DataBase.CREATE_STRING_DATA;
                        command.ExecuteNonQuery();
                        //TODO add logging
                    }
                    trans.Commit();
                }
                connection.Close();
            }
        }
    }

I then export the connection string and use it to obtain new connections in different parts of the program.

At seemingly random intervals, though at far too great a rate to ignore or otherwise workaround this problem, I get unhandled SQLiteException: Database file is locked.  This occurs when I attempt to commit the transaction.  No errors seem to occur prior to then.  This does not always happen.  Sometimes the whole thing runs without a hitch.

No reads are being performed on these files before the commits finish.

I have the very latest SQLite binary.

I'm compiling for .NET 2.0.

I'm using VS 2008.

The db is a local file.

All of this activity is encapsulated within one thread / process.

Virus protection is off (though I think that was only relevant if you were connecting over a network?).

As per Scotsman's post I have implemented the following changes:

Journal Mode set to Persist

DB files stored in C:\Docs + Settings\ApplicationData via System.Windows.Forms.Application.AppData windows call

No inner exception

Witnessed on two distinct machines (albeit very similar hardware and software)

Have been running Process Monitor - no extraneous processes are attaching themselves to the DB files - the problem is definitely in my code...

Does anyone have any idea whats going on here?

I know I just dropped a whole mess of code, but I've been trying to figure this out for way too long.  My thanks to anyone who makes it to the end of this question!

brian

UPDATES:

Thanks for the suggestions so far!  I've implemented many of the suggested changes.  I feel that we are getting closer to the answer...however...

The code above technically works however it is non-deterministic!  It is not guaranteed to do anything aside from spin in neutral forever.  In practice it seems to work somewhere between the 1st and 10th iteration.  If i batch my commits at a reasonable interval damage will be mitigated but I really do not want to leave things in this state...

More suggestions welcome!


来源: stackexchange

问:
Put Array in a particular Form in Typescript/Angular
I´m new to stackoverflow and not an english native speaker, so apologies for any mistakes.
We have an Angular/C# project in a course of study and I need an Angular mat-select which works with an ID (number) but displays a String instead.
In my typescript class I already have an Array<number> fruitIDs . Now I want to take every element of the array and apply a function fruitName(fruitID) on it (fruitName(fruitID) returns a string).
My problem is that I need to put the elements of the array and their corresponding function values in a form like:

```<code>fruits =
[{value: idOfFirstFruit, viewValue: fruitName(idOfFirstFruit)},
{value: idOfSecondFruit, viewValue: fruitName(idOfSecondFruit)},....]
</code>```

If I have an object in this form my mat-select can access and save value but display `fruitName(value)' instead.
I hope anyone can help. Thanks in advance!

答:
Ok, if anybody is interested, I found the solution:</p>

```<code>var fruitNrs:Array<number> = this.fruits.map(item => {return item.fruitNr});
var objArray: Array<{value:number,viewValue:string}> = [];
    for (let fruitNr of fruitNrs){
        objArray.push({value:fruitNr,viewValue:this.fruitname(fruitNr)});
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I´m new to stackoverflow and not an english native speaker, so apologies for any mistakes.
We have an Angular/C# project in a course of study and I need an Angular mat-select which works with an ID (number) but displays a String instead.
In my typescript class I already have an Array<number> fruitIDs . Now I want to take every element of the array and apply a function fruitName(fruitID) on it (fruitName(fruitID) returns a string).
My problem is that I need to put the elements of the array and their corresponding function values in a form like:

fruits =
[{value: idOfFirstFruit, viewValue: fruitName(idOfFirstFruit)},
{value: idOfSecondFruit, viewValue: fruitName(idOfSecondFruit)},....]

If I have an object in this form my mat-select can access and save value but display `fruitName(value)' instead.
I hope anyone can help. Thanks in advance!

Body:
Ok, if anybody is interested, I found the solution:

var fruitNrs:Array<number> = this.fruits.map(item => {return item.fruitNr});
var objArray: Array<{value:number,viewValue:string}> = [];
    for (let fruitNr of fruitNrs){
        objArray.push({value:fruitNr,viewValue:this.fruitname(fruitNr)});
    }


问:
Verify the center of circle instance is a Point object, not tuple
The Circle class takes Point object as the center of circle.
To verify the center of the circle instance is a Point object, I added an if not isinstance() statement in init. This if statement raises TypeError when center is not a Point object.

```<code>def __init__(self, center=(0,0), radius=1):
        Point.__init__(self,center)
        self.center=center
        self.radius=radius
        if not isinstance(center,Point):
            raise TypeError("The center must be a Point!")
</code>```

However, the code seems to accept any tuple in the form of (x,y) to be Point object. Is there a way to only pass the Point object to be center and anything else any tuple to be TypeError?

The desired output is shown in the following:

```<code>>>> circle  =   Circle(center=4,    radius=1.5)
[Traceback...]
TypeError:  The center  must    be  a   Point!
>>> circle  =   Circle(center=Point(3,4),   radius=2)
>>> circle.center   =   (3, 4)
[Traceback...]
TypeError:  The center  must    be  a   Point!
</code>```

The following is the code for Point class:

```<code>import math
class Point:
    def __init__(self,x=0,y=0):
        self.x = x
        self.y = y
        self.data=[x,y]
    def __getitem__(self, index):
        return self.data[index]
    def __iter__(self):
        yield self.x
        yield self.y
    def __add__(self,other):
        return Point(self.x+other.x,self.y+other.y)
    def __mul__(self,n):
        return Point(self.x*n,self.y*n)
    def __rmul__(self,n):
        return Point(n*self.x,n*self.y)
    @classmethod
    def from_tuple (cls, self=(0,0)):
        return cls(*self)
    def loc_from_tuple(self,t=(0,0)):
        self.x=t[0]
        self.y=t[1]
    def __str__(self):
        return "Point at ({0}, {1})".format(self.x,self.y)
    def __repr__(self):
        return"Point(x={0}, y={1})".format(self.x,self.y)
</code>```

The following is class Circle

```<code>class Circle(Point):
    def __init__(self, center=(0,0), radius=1):
        Point.__init__(self,center)
        self.center=center
        self.radius=radius
        if not isinstance(center,Point):
            raise TypeError("The center must be a Point!")

    def __getitem__(self,item):
        return self.center[item]
    def __str__(self):
        return "Circle with center at ({0}, {1}) and radius {2}".format(self.center.x, self.center.y, self.radius)
    def __repr__(self):
        return "Circle(center=Point({0}, {1}), radius={2})".format(self.center[0],self.center[1],self.radius)
    def __add__(self,other):
        return Circle(
        Point(self.center.x+other.center.x,
        self.center.y+other.center.y),
        self.radius+other.radius)
    @classmethod
    def from_tuple(cls, center,radius):
        return cls(center, radius)
    @property
    def radius(self):
        return self._radius
    @radius.setter
    def radius(self, radius):
        if radius<0:
            raise ValueError('The radius cannot be negative')
        self._radius=radius
</code>```

This is what I am getting.

答:
Here what's happening in your code.
When you create a circle with a center=Point (a Point object), your code create a Point with a Point as argument in center since you wrote

```<code>Point.__init__(self,center) # center is a Point object which is not what you want
</code>```

This is not in accordance with the default value of center (which is a tuple), when you instantiate the Circle object with no center this will not work since the tuple center will not pass

```<code>isinstance(center,Point)
</code>```

To use the inheritance, do as follow (also, not verifying that center is a tuple make more sense) :

```<code>class Circle(Point):
    def __init__(self, center=(0,0), radius=1):
        x, y = center
        super(Circle, self).__init__(x, y)
        self.center = center # This is not useful
        self.radius = radius
        if not isinstance(center, tuple):
            raise TypeError("The center must be a tuple!")

    @property
    def center(self): # This if a better way to access the center
        return(self.x, self.y)
</code>```

Body:
The Circle class takes Point object as the center of circle.
To verify the center of the circle instance is a Point object, I added an if not isinstance() statement in init. This if statement raises TypeError when center is not a Point object.

def __init__(self, center=(0,0), radius=1):
        Point.__init__(self,center)
        self.center=center
        self.radius=radius
        if not isinstance(center,Point):
            raise TypeError("The center must be a Point!")

However, the code seems to accept any tuple in the form of (x,y) to be Point object. Is there a way to only pass the Point object to be center and anything else any tuple to be TypeError?

The desired output is shown in the following:

>>> circle  =   Circle(center=4,    radius=1.5)
[Traceback...]
TypeError:  The center  must    be  a   Point!
>>> circle  =   Circle(center=Point(3,4),   radius=2)
>>> circle.center   =   (3, 4)
[Traceback...]
TypeError:  The center  must    be  a   Point!

The following is the code for Point class:

import math
class Point:
    def __init__(self,x=0,y=0):
        self.x = x
        self.y = y
        self.data=[x,y]
    def __getitem__(self, index):
        return self.data[index]
    def __iter__(self):
        yield self.x
        yield self.y
    def __add__(self,other):
        return Point(self.x+other.x,self.y+other.y)
    def __mul__(self,n):
        return Point(self.x*n,self.y*n)
    def __rmul__(self,n):
        return Point(n*self.x,n*self.y)
    @classmethod
    def from_tuple (cls, self=(0,0)):
        return cls(*self)
    def loc_from_tuple(self,t=(0,0)):
        self.x=t[0]
        self.y=t[1]
    def __str__(self):
        return "Point at ({0}, {1})".format(self.x,self.y)
    def __repr__(self):
        return"Point(x={0}, y={1})".format(self.x,self.y)

The following is class Circle

class Circle(Point):
    def __init__(self, center=(0,0), radius=1):
        Point.__init__(self,center)
        self.center=center
        self.radius=radius
        if not isinstance(center,Point):
            raise TypeError("The center must be a Point!")

    def __getitem__(self,item):
        return self.center[item]
    def __str__(self):
        return "Circle with center at ({0}, {1}) and radius {2}".format(self.center.x, self.center.y, self.radius)
    def __repr__(self):
        return "Circle(center=Point({0}, {1}), radius={2})".format(self.center[0],self.center[1],self.radius)
    def __add__(self,other):
        return Circle(
        Point(self.center.x+other.center.x,
        self.center.y+other.center.y),
        self.radius+other.radius)
    @classmethod
    def from_tuple(cls, center,radius):
        return cls(center, radius)
    @property
    def radius(self):
        return self._radius
    @radius.setter
    def radius(self, radius):
        if radius<0:
            raise ValueError('The radius cannot be negative')
        self._radius=radius

This is what I am getting.

Body:
Here what's happening in your code.
When you create a circle with a center=Point (a Point object), your code create a Point with a Point as argument in center since you wrote

Point.__init__(self,center) # center is a Point object which is not what you want

This is not in accordance with the default value of center (which is a tuple), when you instantiate the Circle object with no center this will not work since the tuple center will not pass

isinstance(center,Point)

To use the inheritance, do as follow (also, not verifying that center is a tuple make more sense) :

class Circle(Point):
    def __init__(self, center=(0,0), radius=1):
        x, y = center
        super(Circle, self).__init__(x, y)
        self.center = center # This is not useful
        self.radius = radius
        if not isinstance(center, tuple):
            raise TypeError("The center must be a tuple!")

    @property
    def center(self): # This if a better way to access the center
        return(self.x, self.y)


问:
Why I cannot display Firebase data in ListView
Can someone help me in this problem, I try to display job from the firebase in Listview, but it doesn't display anything! I have tried different codes from topic at stack and different sites but receive error at

```<code>adapter=new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1,retrieve());
</code>```

and this

```<code>lv.setAdapter(adapter);
</code>```

with nullexception

Javacode

```<code>package com.gumption.zeeshanahmed.jobaps;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.ArrayList;

 public class EditsJobs extends AppCompatActivity {

     ListView lv;
     ArrayAdapter<String> adapter;
     ArrayList<String> spacecrafts=new ArrayList<>();

// Declaring String variable ( In which we are storing firebase server URL
//).
     public static final String Firebase_Server_URL =
     "https://jobaps70.firebaseio.com/";

// Declaring String variables to store name & phone number get from
//EditText.
      String PriceHolder, JobDescriptionHolder;
      FirebaseHelper helper;

// Declaring Firebase object.
      Firebase firebase;

// Creating FirebaseAuth.
      FirebaseAuth firebaseAuth ;

// Creating FirebaseAuth.
      FirebaseUser firebaseUser;

// Creating Boolean variable that holds EditText is empty or not status.
      Boolean EditTextStatus ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edits_jobs);

//Actionbar
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setIcon(R.drawable.logo);
    getSupportActionBar().setBackgroundDrawable(new
    ColorDrawable(getResources().getColor(R.color.Snow)));

// Adding MainActivity context into Firebase context.

    Firebase.setAndroidContext(EditsJobs.this);

// Passing firebase Server URL into firebase object.

    firebase = new Firebase(Firebase_Server_URL);
    firebaseAuth = FirebaseAuth.getInstance();

// On activity start check whether there is user previously logged in or
//   not.

    if(firebaseAuth.getCurrentUser() == null){

        // Finishing current Profile activity.
        finish();

        // If user already not log in then Redirect to LoginActivity .
        Intent intent = new Intent(EditsJobs.this, LoginActivity.class);
        startActivity(intent);

        // Showing toast message.
        Toast.makeText(EditsJobs.this, "Please Log in to continue",
        Toast.LENGTH_LONG).show();

    }

    // Adding firebaseAuth current user info into firebaseUser object.
    firebaseUser = firebaseAuth.getCurrentUser();

    // Getting logged in user email from firebaseUser.getEmail() method and
     set into TextView.
    setTitle( firebaseUser.getEmail());
    setTitleColor(R.color.DarkGray);

    // ListView element

    lv = (ListView) findViewById(R.id.datadisplist);
    adapter=new ArrayAdapter<String>
    (this,android.R.layout.simple_list_item_1,retrieve());
    lv.setAdapter(adapter);
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int
        position, long id) {
            Toast.makeText(EditsJobs.this, retrieve().get(position),
            Toast.LENGTH_SHORT).show();
         }
    });

}

 private void fetchData(DataSnapshot dataSnapshot)
{
    jobsdetails.clear();
    for (DataSnapshot ds : dataSnapshot.getChildren())
    {
        String jobs=ds.getValue(JobDetails.class).getjob();
        jobsdetails.add(jobs);
    }
}

//RETRIEVE
public ArrayList<String> retrieve(){
firebase.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        fetchData(dataSnapshot);
    }

    @Override
    public void onChildChanged(DataSnapshot dataSnapshot, String s) {
        fetchData(dataSnapshot);

    }

    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot) {

    }

    @Override
    public void onChildMoved(DataSnapshot dataSnapshot, String s) {

    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {

    }

});

return spacecrafts;
}
}
</code>```

XML

```<code>   <?xml version="1.0" encoding="utf-8"?>
   <RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context="com.gumption.zeeshanahmed.jobaps.EditsJobs">
   <TextView
    android:id="@+id/texteditjobs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/text_edit_jobs"
    android:textSize="40sp"
    android:textAlignment="center"/>

    <ListView
        android:id="@+id/datadisplist"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/texteditjobs"
        android:background="@color/Khaki"/>
       </RelativeLayout>
</code>```

JobDetail

```<code> public class JobDetails {

    private String price;
    private String jobDescription;
    private String jobSpinner;
    public String email;
    public JobDetails() {
        // This is default constructor.
    }

    public String getPrice() {

        return price;
    }

    public void setPrice(String pri) {

        this.price = pri;
    }

    public String getjobDescription() {

        return jobDescription;

    }

    public void setjobDescription(String jobd) {

        this.jobDescription = jobd;
    }

    public void setjob(String jry) {

        this.jobSpinner = jry ;

    }

    public String getjob() {

        return jobSpinner;

    }

    public void setemail(String jel) {

        this.email = jel ;

    }

    public String getemail() {

        return email;

    }
}
</code>```

Using textView

when i use text view the data is displayed only one atmost!

```<code>// Adding click listener to Show data button.
    ShowButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // Adding addValueEventListener method on firebase object.
            firebase.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot MainSnapshot) {

              for (DataSnapshot SubSnapshot : MainSnapshot.getChildren()) {

              JobDetails jobdetails =SubSnapshot.getValue(JobDetails.class);
                    for
                        // Adding name and phone number of student into
                      string that is coming from server.

                        String ShowDataString = "Job: " +
                        jobdetails.getjob() + "\nJob Description: " +
                        jobdetails.getjobDescription() + "\n\n";

                        // Apply complete string variable into TextView.
                        ShowDataTextView.setText(ShowDataString);
               }
                    }
                }

                @Override
                public void onCancelled(FirebaseError firebaseError) {
                    System.out.println("Data Access Failed" +
                firebaseError.getMessage());
                }
            });
        }
        });
</code>```

with Xml

```<code>   <TextView
    android:id="@+id/showmetadata"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/show"
    android:textSize="40sp"
    android:textAlignment="center"/>
</code>```

It will be very helpful if someone help will me with this. Please and thank
you!

**Tried listview **

Now i tried listview, and it crashes here is the code and error

```<code> public class WorkActivity extends AppCompatActivity {

//    Spinner jobSpin;

ListView lv;
Button ShowButton;
// Define a String ArrayList for the job
private ArrayList<String> jobdes=new ArrayList<>();

// Define an ArrayAdapter for the list
private ArrayAdapter<String> arrayAdapter;

// Declaring String variable ( In which we are storing firebase server URL
).
public static final String Firebase_Server_URL =
"https://jobaps70.firebaseio.com/";
public static final String Firebase_Server_URL1 =
 "https://jobaps70.firebaseio.com/jobs";

// Declaring String variables to store name & phone number get from
EditText.
String PriceHolder, JobDescriptionHolder;
FirebaseHelper helper;

// Declaring Firebase object.
Firebase firebase,firebase1;

// Creating FirebaseAuth.
FirebaseAuth firebaseAuth ;

// Creating FirebaseAuth.
FirebaseUser firebaseUser;

// Creating Boolean variable that holds EditText is empty or not status.
Boolean EditTextStatus ;

TextView ShowDataTextView ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edits_jobs);

      //        Actionbar
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setIcon(R.drawable.logo);
    getSupportActionBar().setBackgroundDrawable(new
    ColorDrawable(getResources().getColor(R.color.Snow)));

    ShowButton = (Button)findViewById(R.id.show);

    // Adding MainActivity context into Firebase context.
    Firebase.setAndroidContext(WorkActivity.this);

    // Passing firebase Server URL into firebase object.
    firebase = new Firebase(Firebase_Server_URL);
    firebase1=new Firebase(Firebase_Server_URL1);

    firebaseAuth = FirebaseAuth.getInstance();

    // On activity start check whether there is user previously logged in or
       not.
    if(firebaseAuth.getCurrentUser() == null){

        // Finishing current Profile activity.
        finish();

        // If user already not log in then Redirect to LoginActivity .
        Intent intent = new Intent(WorkActivity.this, LoginActivity.class);
        startActivity(intent);

        // Showing toast message.
        Toast.makeText(WorkActivity.this, "Please Log in to continue",
        Toast.LENGTH_LONG).show();

    }

    // Adding firebaseAuth current user info into firebaseUser object.
    firebaseUser = firebaseAuth.getCurrentUser();

    // Getting logged in user email from firebaseUser.getEmail() method and
        set into TextView.
    setTitle( firebaseUser.getEmail());
    setTitleColor(R.color.DarkGray);
      firebase.child("jobs");

    // Associate the jobs' list with the corresponding ListView
    lv = (ListView) findViewById(R.id.lvshow);

    // Set the ArrayAdapter to the ListView
    arrayAdapter = new ArrayAdapter<String>(this,
       android.R.layout.simple_list_item_1, jobdes);
    lv.setAdapter(arrayAdapter);

    // Attach a ChildEventListener to the teacher database, so we can
          retrieve the job entries
    firebase.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {

            // Get the value from the DataSnapshot and add it to the jobs'
         list
            JobDetails jo = (JobDetails)
         dataSnapshot.getValue(JobDetails.class);
            String joString = String.valueOf(jo);
            arrayAdapter.add(joString);
 //

            // Notify the ArrayAdapter that there was a change
            arrayAdapter.notifyDataSetChanged();
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(FirebaseError databaseError) {

        }
    });
}

}
</code>```

Error

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.gumption.zeeshanahmed.jobaps, PID: 4774
              java.lang.RuntimeException: Unable to start activity
              ComponentInfo{com.gumption.zeeshanahmed.jobaps/
              com.gumption.zeeshanahmed.jobaps.WorkActivity}:
              java.lang.NullPointerException: Attempt to invoke virtual
              method 'void
             android.widget.ListView.setAdapter(android.widget.ListAdapter)'
             on a null object reference at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                  at android.app.ActivityThread.-wrap11(ActivityThread.java)
                  at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:148)at
 android.app.ActivityThread.main(ActivityThread.java:5417)
                  at java.lang.reflect.Method.invoke(Native Method) at
 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run
 (ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main
 (ZygoteInit.java:616)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method
 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a
 null object reference at
 com.gumption.zeeshanahmed.jobaps.WorkActivity.onCreate
 (WorkActivity.java:109)
              at android.app.Activity.performCreate(Activity.java:6237) at
 android.app.Instrumentation.callActivityOnCreate
 (Instrumentation.java:1107) at
 android.app.ActivityThread.performLaunchActivity
 (ActivityThread.java:2369)atandroid.app.ActivityThread.handleLaunchActivity
 (ActivityThread.java:2476) at android.app.ActivityThread.-
  wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage
 (ActivityThread.java:1344) at android.os.Handler.dispatchMessage
 (Handler.java:102) at android.os.Looper.loop(Looper.java:148) at
 android.app.ActivityThread.main(ActivityThread.java:5417) at
 java.lang.reflect.Method.invoke(Native Method) at
 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run
 (ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main
 (ZygoteInit.java:616)
</code>```

java Error line

It is showing error at this

```<code> lv.setAdapter(arrayAdapter);
</code>```

答:
The problem in your code is retrieve(), which is a method that returns an ArrayList<String> named spacecrafts. This ArrayList<String> is initialized in the first lines of your code but never updated. With other words, you are using spacecrafts in your adapter which is empty.

To solve this problem, every time you get data from your Firebase add it to the right ArrayList<String>. One more thing to node, due the asynchronous behaviour of those methods, you cannot return an ArrayList<String> in the way you do because it will always be empty. You need to declare and use/update that ArrayList inside that method.

Body:
Can someone help me in this problem, I try to display job from the firebase in Listview, but it doesn't display anything! I have tried different codes from topic at stack and different sites but receive error at

adapter=new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1,retrieve());

and this

lv.setAdapter(adapter);

with nullexception

Javacode

package com.gumption.zeeshanahmed.jobaps;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.ArrayList;

 public class EditsJobs extends AppCompatActivity {

     ListView lv;
     ArrayAdapter<String> adapter;
     ArrayList<String> spacecrafts=new ArrayList<>();

// Declaring String variable ( In which we are storing firebase server URL
//).
     public static final String Firebase_Server_URL =
     "https://jobaps70.firebaseio.com/";

// Declaring String variables to store name & phone number get from
//EditText.
      String PriceHolder, JobDescriptionHolder;
      FirebaseHelper helper;

// Declaring Firebase object.
      Firebase firebase;

// Creating FirebaseAuth.
      FirebaseAuth firebaseAuth ;

// Creating FirebaseAuth.
      FirebaseUser firebaseUser;

// Creating Boolean variable that holds EditText is empty or not status.
      Boolean EditTextStatus ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edits_jobs);

//Actionbar
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setIcon(R.drawable.logo);
    getSupportActionBar().setBackgroundDrawable(new
    ColorDrawable(getResources().getColor(R.color.Snow)));

// Adding MainActivity context into Firebase context.

    Firebase.setAndroidContext(EditsJobs.this);

// Passing firebase Server URL into firebase object.

    firebase = new Firebase(Firebase_Server_URL);
    firebaseAuth = FirebaseAuth.getInstance();

// On activity start check whether there is user previously logged in or
//   not.

    if(firebaseAuth.getCurrentUser() == null){

        // Finishing current Profile activity.
        finish();

        // If user already not log in then Redirect to LoginActivity .
        Intent intent = new Intent(EditsJobs.this, LoginActivity.class);
        startActivity(intent);

        // Showing toast message.
        Toast.makeText(EditsJobs.this, "Please Log in to continue",
        Toast.LENGTH_LONG).show();

    }

    // Adding firebaseAuth current user info into firebaseUser object.
    firebaseUser = firebaseAuth.getCurrentUser();

    // Getting logged in user email from firebaseUser.getEmail() method and
     set into TextView.
    setTitle( firebaseUser.getEmail());
    setTitleColor(R.color.DarkGray);

    // ListView element

    lv = (ListView) findViewById(R.id.datadisplist);
    adapter=new ArrayAdapter<String>
    (this,android.R.layout.simple_list_item_1,retrieve());
    lv.setAdapter(adapter);
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int
        position, long id) {
            Toast.makeText(EditsJobs.this, retrieve().get(position),
            Toast.LENGTH_SHORT).show();
         }
    });

}

 private void fetchData(DataSnapshot dataSnapshot)
{
    jobsdetails.clear();
    for (DataSnapshot ds : dataSnapshot.getChildren())
    {
        String jobs=ds.getValue(JobDetails.class).getjob();
        jobsdetails.add(jobs);
    }
}

//RETRIEVE
public ArrayList<String> retrieve(){
firebase.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        fetchData(dataSnapshot);
    }

    @Override
    public void onChildChanged(DataSnapshot dataSnapshot, String s) {
        fetchData(dataSnapshot);

    }

    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot) {

    }

    @Override
    public void onChildMoved(DataSnapshot dataSnapshot, String s) {

    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {

    }

});

return spacecrafts;
}
}

XML

   <?xml version="1.0" encoding="utf-8"?>
   <RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context="com.gumption.zeeshanahmed.jobaps.EditsJobs">
   <TextView
    android:id="@+id/texteditjobs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/text_edit_jobs"
    android:textSize="40sp"
    android:textAlignment="center"/>

    <ListView
        android:id="@+id/datadisplist"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/texteditjobs"
        android:background="@color/Khaki"/>
       </RelativeLayout>

JobDetail

 public class JobDetails {

    private String price;
    private String jobDescription;
    private String jobSpinner;
    public String email;
    public JobDetails() {
        // This is default constructor.
    }

    public String getPrice() {

        return price;
    }

    public void setPrice(String pri) {

        this.price = pri;
    }

    public String getjobDescription() {

        return jobDescription;

    }

    public void setjobDescription(String jobd) {

        this.jobDescription = jobd;
    }

    public void setjob(String jry) {

        this.jobSpinner = jry ;

    }

    public String getjob() {

        return jobSpinner;

    }

    public void setemail(String jel) {

        this.email = jel ;

    }

    public String getemail() {

        return email;

    }
}

Using textView

when i use text view the data is displayed only one atmost!

// Adding click listener to Show data button.
    ShowButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // Adding addValueEventListener method on firebase object.
            firebase.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot MainSnapshot) {

              for (DataSnapshot SubSnapshot : MainSnapshot.getChildren()) {

              JobDetails jobdetails =SubSnapshot.getValue(JobDetails.class);
                    for
                        // Adding name and phone number of student into
                      string that is coming from server.

                        String ShowDataString = "Job: " +
                        jobdetails.getjob() + "\nJob Description: " +
                        jobdetails.getjobDescription() + "\n\n";

                        // Apply complete string variable into TextView.
                        ShowDataTextView.setText(ShowDataString);
               }
                    }
                }

                @Override
                public void onCancelled(FirebaseError firebaseError) {
                    System.out.println("Data Access Failed" +
                firebaseError.getMessage());
                }
            });
        }
        });

with Xml

   <TextView
    android:id="@+id/showmetadata"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/show"
    android:textSize="40sp"
    android:textAlignment="center"/>

It will be very helpful if someone help will me with this. Please and thank
you!

**Tried listview **

Now i tried listview, and it crashes here is the code and error

 public class WorkActivity extends AppCompatActivity {

//    Spinner jobSpin;

ListView lv;
Button ShowButton;
// Define a String ArrayList for the job
private ArrayList<String> jobdes=new ArrayList<>();

// Define an ArrayAdapter for the list
private ArrayAdapter<String> arrayAdapter;

// Declaring String variable ( In which we are storing firebase server URL
).
public static final String Firebase_Server_URL =
"https://jobaps70.firebaseio.com/";
public static final String Firebase_Server_URL1 =
 "https://jobaps70.firebaseio.com/jobs";

// Declaring String variables to store name & phone number get from
EditText.
String PriceHolder, JobDescriptionHolder;
FirebaseHelper helper;

// Declaring Firebase object.
Firebase firebase,firebase1;

// Creating FirebaseAuth.
FirebaseAuth firebaseAuth ;

// Creating FirebaseAuth.
FirebaseUser firebaseUser;

// Creating Boolean variable that holds EditText is empty or not status.
Boolean EditTextStatus ;

TextView ShowDataTextView ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edits_jobs);

      //        Actionbar
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setIcon(R.drawable.logo);
    getSupportActionBar().setBackgroundDrawable(new
    ColorDrawable(getResources().getColor(R.color.Snow)));

    ShowButton = (Button)findViewById(R.id.show);

    // Adding MainActivity context into Firebase context.
    Firebase.setAndroidContext(WorkActivity.this);

    // Passing firebase Server URL into firebase object.
    firebase = new Firebase(Firebase_Server_URL);
    firebase1=new Firebase(Firebase_Server_URL1);

    firebaseAuth = FirebaseAuth.getInstance();

    // On activity start check whether there is user previously logged in or
       not.
    if(firebaseAuth.getCurrentUser() == null){

        // Finishing current Profile activity.
        finish();

        // If user already not log in then Redirect to LoginActivity .
        Intent intent = new Intent(WorkActivity.this, LoginActivity.class);
        startActivity(intent);

        // Showing toast message.
        Toast.makeText(WorkActivity.this, "Please Log in to continue",
        Toast.LENGTH_LONG).show();

    }

    // Adding firebaseAuth current user info into firebaseUser object.
    firebaseUser = firebaseAuth.getCurrentUser();

    // Getting logged in user email from firebaseUser.getEmail() method and
        set into TextView.
    setTitle( firebaseUser.getEmail());
    setTitleColor(R.color.DarkGray);
      firebase.child("jobs");

    // Associate the jobs' list with the corresponding ListView
    lv = (ListView) findViewById(R.id.lvshow);

    // Set the ArrayAdapter to the ListView
    arrayAdapter = new ArrayAdapter<String>(this,
       android.R.layout.simple_list_item_1, jobdes);
    lv.setAdapter(arrayAdapter);

    // Attach a ChildEventListener to the teacher database, so we can
          retrieve the job entries
    firebase.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {

            // Get the value from the DataSnapshot and add it to the jobs'
         list
            JobDetails jo = (JobDetails)
         dataSnapshot.getValue(JobDetails.class);
            String joString = String.valueOf(jo);
            arrayAdapter.add(joString);
 //

            // Notify the ArrayAdapter that there was a change
            arrayAdapter.notifyDataSetChanged();
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(FirebaseError databaseError) {

        }
    });
}

}

Error

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.gumption.zeeshanahmed.jobaps, PID: 4774
              java.lang.RuntimeException: Unable to start activity
              ComponentInfo{com.gumption.zeeshanahmed.jobaps/
              com.gumption.zeeshanahmed.jobaps.WorkActivity}:
              java.lang.NullPointerException: Attempt to invoke virtual
              method 'void
             android.widget.ListView.setAdapter(android.widget.ListAdapter)'
             on a null object reference at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                  at android.app.ActivityThread.-wrap11(ActivityThread.java)
                  at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:148)at
 android.app.ActivityThread.main(ActivityThread.java:5417)
                  at java.lang.reflect.Method.invoke(Native Method) at
 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run
 (ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main
 (ZygoteInit.java:616)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method
 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a
 null object reference at
 com.gumption.zeeshanahmed.jobaps.WorkActivity.onCreate
 (WorkActivity.java:109)
              at android.app.Activity.performCreate(Activity.java:6237) at
 android.app.Instrumentation.callActivityOnCreate
 (Instrumentation.java:1107) at
 android.app.ActivityThread.performLaunchActivity
 (ActivityThread.java:2369)atandroid.app.ActivityThread.handleLaunchActivity
 (ActivityThread.java:2476) at android.app.ActivityThread.-
  wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage
 (ActivityThread.java:1344) at android.os.Handler.dispatchMessage
 (Handler.java:102) at android.os.Looper.loop(Looper.java:148) at
 android.app.ActivityThread.main(ActivityThread.java:5417) at
 java.lang.reflect.Method.invoke(Native Method) at
 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run
 (ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main
 (ZygoteInit.java:616)

java Error line

It is showing error at this

 lv.setAdapter(arrayAdapter);


问:
Why does space in Bash string subscripts matter here?
I'm experimenting with bash scripting and noticed the following behavior:

```<code>file="test.jar"
echo "${file: -4}" #prints .jar
echo "${file:-4}"  #prints test.jar
</code>```

Very confusing behavior actually. Can someone explain why the second case prints the whole test.jar?

答:
This is due to inconsistent syntax. {"string":-}  means default (all the string), whatever follows -. So you need either a space or parenthesis:

```<code>{"string": -4}
{"string":(-4)}
</code>```

Read bash string manipulation.

Body:
I'm experimenting with bash scripting and noticed the following behavior:

file="test.jar"
echo "${file: -4}" #prints .jar
echo "${file:-4}"  #prints test.jar

Very confusing behavior actually. Can someone explain why the second case prints the whole test.jar?

Body:
This is due to inconsistent syntax. {"string":-}  means default (all the string), whatever follows -. So you need either a space or parenthesis:

{"string": -4}
{"string":(-4)}

Read bash string manipulation.


问:
angular cli installation fails at step fetchMetadata: sill resolveWithNewModule chokidar@1.7.0 checking installable status
I am new to angular cli.
Trying to install angular cli on windows machine in my company(behind proxy). Have installed node and npm.
Using npm I also installed typescript packages.
However the angular cli installation fails at below step:

```<code>[   ...............] / fetchMetadata: sill resolveWithNewModule chokidar@1.7.0 checking installable status
</code>```

I am running below command :

```<code>npm install -g @angular/cli@latest
</code>```

Below is the log being shown on the command prompt:

```<code>npm ERR! code EINTEGRITY
npm ERR! sha512-WIr7iDkdmdbxu/Gh6eKEZJL6KPE74/5MEsf2whTOFNxbIoIixogroLdKYqB6FDav4Wavh/lZdzzd3b2KxIXC5Q== integrity checksum failed when using sha512: wanted sha512-WIr
7iDkdmdbxu/Gh6eKEZJL6KPE74/5MEsf2whTOFNxbIoIixogroLdKYqB6FDav4Wavh/lZdzzd3b2KxIXC5Q== but got sha512-2DqIGeAfFMb8eI+LZWl53bx0sCPMI5M8SVVIXjRomxiUY1Jcy2NK79gnR2gRam3TDi
lxUjaUlRoCBVIC9KpVNg==. (1597 bytes)
npm WARN tar invalid entry
npm WARN tar invalid entry
npm WARN tar invalid entry

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\<UserID>\AppData\Roaming\npm-cache\_logs\2017-12-06T05_21_15_837Z-debug.log
</code>```

Note: I have also set the proxy to npm config and have set strict-ssl=false

答:
I managed to resolve this issue by following these steps.

rm -rf node_modules/

npm cache clean --force

npm cache verify

npm i -g @angular/cli

Also make sure you set the proxies properly.

Body:
I am new to angular cli.
Trying to install angular cli on windows machine in my company(behind proxy). Have installed node and npm.
Using npm I also installed typescript packages.
However the angular cli installation fails at below step:

[   ...............] / fetchMetadata: sill resolveWithNewModule chokidar@1.7.0 checking installable status

I am running below command :

npm install -g @angular/cli@latest

Below is the log being shown on the command prompt:

npm ERR! code EINTEGRITY
npm ERR! sha512-WIr7iDkdmdbxu/Gh6eKEZJL6KPE74/5MEsf2whTOFNxbIoIixogroLdKYqB6FDav4Wavh/lZdzzd3b2KxIXC5Q== integrity checksum failed when using sha512: wanted sha512-WIr
7iDkdmdbxu/Gh6eKEZJL6KPE74/5MEsf2whTOFNxbIoIixogroLdKYqB6FDav4Wavh/lZdzzd3b2KxIXC5Q== but got sha512-2DqIGeAfFMb8eI+LZWl53bx0sCPMI5M8SVVIXjRomxiUY1Jcy2NK79gnR2gRam3TDi
lxUjaUlRoCBVIC9KpVNg==. (1597 bytes)
npm WARN tar invalid entry
npm WARN tar invalid entry
npm WARN tar invalid entry

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\<UserID>\AppData\Roaming\npm-cache\_logs\2017-12-06T05_21_15_837Z-debug.log

Note: I have also set the proxy to npm config and have set strict-ssl=false


问:
Best practice of API call from Activities
I am in a bit trouble finding out the best practice. I need an expert opinion on this. My scenario is I have an API which returns me the list of applicants for a particular job. In my parent activity, I have the list of jobs and I am asking that, should I call the API on button click from the parent activity and pass it over to the child or should I just transact the activities and call the API from the child activity? Please give me a good advice to improve the user experience and speed. Because the retrieved JSON will be quite huge in terms of data. Thank you</p>

答:
In General

If the data is not used by the main activity itself, there is no reason to make the API call from the main activity. Call the child activity when the user clicks the button and start fetching the data in the child activity.

User experience

If the size of the data is huge, like you explained, or the user has a poor internet connection, you obviously need to give the user feedback in form of a loading animation in the child activity. As an example you could use a library like this.

Performance

The will be no performance difference between fetching the data in the main or in the child activity. To gain overall performance, make shure to cache the fetched data.
In the child activity you could load the data (list of applicants for a particular job) in small portions to quickly show the first few records. This will also strongly increase the users experience.

I hope this answers you question in a proper way.
Sorry for poor english.


问:
Justify the last line of a div?
I don't think the "why?" of this question is important...but what I need to do is to text-align:justify the last line of text from a DIV. Normally, the last line (or the first if there are no other lines, which is the current case) of a div isn't justified, but aligned left. I know it might not make sense at all, but I absolutely need the last line to be justified!

答:
This is the cleanest hack I could come up with/find. Your mileage may vary.

I tested my example in IE8, Firefox, Chrome, Opera, Safari.

IE7 does not implement the :after pseudo-class, so it won't work there.

If you need IE7 support, it would probably work to stick the " ___" inside an extraneous span at the end of the div (use JS?).

Live Demo (see code)

CSS:

```<code>div {
    width: 618px;
    text-align: justify
}
div:after {
    content: " __________________________________________________________";
    line-height: 0;
    visibility: hidden
}
</code>```

HTML:

```<code><div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean dui dolor, bibendum quis accumsan porttitor, fringilla sed libero. Phasellus felis ante, egestas at adipiscing lobortis, lobortis id mi. Praesent pulvinar dictum purus. Duis rhoncus bibendum vehicula. Vestibulum mollis, metus a consectetur semper, urna enim sollicitudin lacus, vel imperdiet turpis nisl at metus. Integer iaculis pretium dui, a viverra dolor lobortis pellentesque. Aliquam quis felis nec purus semper interdum. Nam ac dolor in sem tincidunt egestas. Ut nisl tortor, laoreet eu vestibulum id, bibendum at ipsum. Maecenas elementum bibendum orci, ac eleifend felis tincidunt in. Fusce elementum lacinia feugiat.
</div>
</code>```

Unfortunately, it seems to make the div a line taller than it needs to be.

ContentLicense: CC BY-SA 2.5

Title: Justify the last line of a div?

Body:
This is the cleanest hack I could come up with/find. Your mileage may vary.

I tested my example in IE8, Firefox, Chrome, Opera, Safari.

IE7 does not implement the :after pseudo-class, so it won't work there.

If you need IE7 support, it would probably work to stick the " ___" inside an extraneous span at the end of the div (use JS?).

Live Demo (see code)

CSS:

div {
    width: 618px;
    text-align: justify
}
div:after {
    content: " __________________________________________________________";
    line-height: 0;
    visibility: hidden
}

HTML:

<div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean dui dolor, bibendum quis accumsan porttitor, fringilla sed libero. Phasellus felis ante, egestas at adipiscing lobortis, lobortis id mi. Praesent pulvinar dictum purus. Duis rhoncus bibendum vehicula. Vestibulum mollis, metus a consectetur semper, urna enim sollicitudin lacus, vel imperdiet turpis nisl at metus. Integer iaculis pretium dui, a viverra dolor lobortis pellentesque. Aliquam quis felis nec purus semper interdum. Nam ac dolor in sem tincidunt egestas. Ut nisl tortor, laoreet eu vestibulum id, bibendum at ipsum. Maecenas elementum bibendum orci, ac eleifend felis tincidunt in. Fusce elementum lacinia feugiat.
</div>

Unfortunately, it seems to make the div a line taller than it needs to be.


问:
Changing text of labels defined in a loop

I'm trying to make a scalable counter.

In the first window you enter how many counters you want.

In the second window there are labels and buttons used to add one to the label.

Here is my code:

```<code>from tkinter import *

root = Tk()

def newWindow():
    window = Toplevel()
    for i in range(int(textbox.get())):
        exec("global label"+ str(i))
        exec("label" + str(i) + " = Label(window, text = '0')")
        exec("label" + str(i) + ".grid(row = 0, column = i)")
        exec("global button"+ str(i))
        exec("button" + str(i) + " = Button(window, text = 'Add', command = lambda: setText(label" + str(i) + "))")
        exec("button" + str(i) + ".grid(row = 1, column = i)")

def setText(label):
    label.config(text = str(int(label.cget("text")) + 1))

textbox = Entry(root)
textbox.grid(row = 0)
submitButton = Button(root, text = "Submit", command = newWindow)
submitButton.grid(row = 0, column = 1)

root.mainloop()
</code>```

However this is the error I get:

```<code>name 'label_' is not defined
</code>```

where _ is i.

Making them global didn't fix this either.

Help please!

答:
If you're using exec in this way, you're doing something very wrong.

The simple solution is to add widgets to a list or dictionary. Though, in this specific case you don't need that because you're never referencing the label anywhere but in the button command.

Here's a working example:

```<code>from tkinter import *

root = Tk()

def newWindow():
    global labels
    window = Toplevel()
    labels = {}
    for i in range(int(textbox.get())):
        label = Label(window, text='0')
        button = Button(window, text='Add', command = lambda l=label: setText(l))

        label.grid(row=0, column=i)
        button.grid(row=1, column=i)

        # this allows you to access any label later with something
        # like labels[3].configure(...)
        labels[i] = label

def setText(label):
    label.config(text = str(int(label.cget("text")) + 1))

textbox = Entry(root)
textbox.grid(row = 0)
submitButton = Button(root, text = "Submit", command = newWindow)
submitButton.grid(row = 0, column = 1)

root.mainloop()
</code>```

If you wanted to make use of labels, you could have your button pass in the index, and let setText get the widget from the dictionary:

```<code>def setText(i):
    label = labels[i]
    label.configure(...)
...
button = Button(..., command=lambda i=i: setText(i))
</code>```

Body:
I'm trying to make a scalable counter.

In the first window you enter how many counters you want.

In the second window there are labels and buttons used to add one to the label.

Here is my code:

from tkinter import *

root = Tk()

def newWindow():
    window = Toplevel()
    for i in range(int(textbox.get())):
        exec("global label"+ str(i))
        exec("label" + str(i) + " = Label(window, text = '0')")
        exec("label" + str(i) + ".grid(row = 0, column = i)")
        exec("global button"+ str(i))
        exec("button" + str(i) + " = Button(window, text = 'Add', command = lambda: setText(label" + str(i) + "))")
        exec("button" + str(i) + ".grid(row = 1, column = i)")

def setText(label):
    label.config(text = str(int(label.cget("text")) + 1))

textbox = Entry(root)
textbox.grid(row = 0)
submitButton = Button(root, text = "Submit", command = newWindow)
submitButton.grid(row = 0, column = 1)

root.mainloop()

However this is the error I get:

name 'label_' is not defined

where _ is i.

Making them global didn't fix this either.

Help please!

Body:
If you're using exec in this way, you're doing something very wrong.

The simple solution is to add widgets to a list or dictionary. Though, in this specific case you don't need that because you're never referencing the label anywhere but in the button command.

Here's a working example:

from tkinter import *

root = Tk()

def newWindow():
    global labels
    window = Toplevel()
    labels = {}
    for i in range(int(textbox.get())):
        label = Label(window, text='0')
        button = Button(window, text='Add', command = lambda l=label: setText(l))

        label.grid(row=0, column=i)
        button.grid(row=1, column=i)

        # this allows you to access any label later with something
        # like labels[3].configure(...)
        labels[i] = label

def setText(label):
    label.config(text = str(int(label.cget("text")) + 1))

textbox = Entry(root)
textbox.grid(row = 0)
submitButton = Button(root, text = "Submit", command = newWindow)
submitButton.grid(row = 0, column = 1)

root.mainloop()

If you wanted to make use of labels, you could have your button pass in the index, and let setText get the widget from the dictionary:

def setText(i):
    label = labels[i]
    label.configure(...)
...
button = Button(..., command=lambda i=i: setText(i))


问:
Spring-data-redis: When within a transaction, get operations would return null
When working on a project using redis(4.0) and spring-data-redis.

It seems when within a transaction, the get operations would return null in java program.

e.g HashOperation's get() method would return null when called between multi() and exec().

But if put the get() before multi(), it can get the value.

So, why was that?

答:
After testing & thinking, I think this is the reasonable behavior, since transaction is executed within redis as an atomic operation, it's impossible to return a value in the middle of a transaction via network back to client, thus null is reasonable.

All the values are returned by the exec() methods as a List after execution of the transaction.

So, when debugging, in the middle of transaction, the value should be null, since it's not executed yet.

Suggestion:

If calculation within a transaction need to read value from redis, then just read those values first, before multi().

Then between multi() and exec() only do update operations, but no read operations.


问:
how to get the list of folders in a test lab in ALM using REST API?
I am looking for a way to get the list of folders under a test lab and display it in some UI. Is there a way to get the list using REST API? I tried /test-set-folders but I didn't see the folders that I am expecting.</p>

答:
There are two types of folder hierarchy test lab and test plan. Both are different entity types.
In side the test lab, you can have following kind of hierarchy

```<code>Folder1

   Folder2

       Test-set1 <-- this is test set (not a folder)
</code>```

http://..../test-set-folders whill give you the list of folders, not the test-sets. This is paginated result. So if you have more than specified limit then it will display the first 100 or whatever is the limit. To get the next set of folders, you need to fetch the next page.

http://..../test-set-folders?page-size=100&start-index=101

Using above query it will bring next set of folders and you can further iterate till last page by changing start-index (increment by page-size)

Hope this will help.

Body:
There are two types of folder hierarchy test lab and test plan. Both are different entity types.
In side the test lab, you can have following kind of hierarchy

Folder1

   Folder2

       Test-set1 <-- this is test set (not a folder)

http://..../test-set-folders whill give you the list of folders, not the test-sets. This is paginated result. So if you have more than specified limit then it will display the first 100 or whatever is the limit. To get the next set of folders, you need to fetch the next page.

http://..../test-set-folders?page-size=100&start-index=101

Using above query it will bring next set of folders and you can further iterate till last page by changing start-index (increment by page-size)

Hope this will help.


问:
Make WPF TextBlock non clickable
I've got a simple UserControl with a TextBlock and two buttons.

```<code><Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="150" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="1*" />
    </Grid.RowDefinitions>
    <TextBlock Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="2" Height="30" Text="Please install updates" Foreground="#FFF" FontWeight="Bold" Margin="0,0,0,20" Grid.RowSpan="2"/>
    <Button Grid.Column="0" Grid.Row="1" Content="Restart Now" Margin="5 0 0 0" Width="80" Height="25" HorizontalAlignment="Right" />
    <Button Grid.Column="1" Grid.Row="1" Content="Snooze" Width="60" Height="25" Margin="10 0 0 0" HorizontalAlignment="Left" Click="bttnOK_Click" />
</Grid>
</code>```

For some reason TextBlock is clickable and when you click it, it closes the control.

Desired behavior: Non clickable TextBlock. When clicking TextBlock, control stays open.

答:
It seems you have added <TextBlock ... Grid.RowSpan=2/> which makes the TextBlock enter the region of Buttons.
Alternatively if removing the RowSpan in TextBlock doesn't solve the issue, try adding IsHitTestVisible=false to TextBlock.

It looks like this,

```<code><Grid>
<Grid.ColumnDefinitions>
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="150" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
    <RowDefinition Height="*" />
    <RowDefinition Height="1*" />
</Grid.RowDefinitions>
<TextBlock Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="2" Height="30" Text="Please install updates" Foreground="#FFF" FontWeight="Bold" Margin="0,0,0,20"/>
<Button Grid.Column="0" Grid.Row="1" Content="Restart Now" Margin="5 0 0 0" Width="80" Height="25" HorizontalAlignment="Right" />
<Button Grid.Column="1" Grid.Row="1" Content="Snooze" Width="60" Height="25" Margin="10 0 0 0" HorizontalAlignment="Left" Click="bttnOK_Click" />
</code>```

ContentLicense: CC BY-SA 4.0

Title: Make WPF TextBlock non clickable

Body:
I've got a simple UserControl with a TextBlock and two buttons.

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="150" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="1*" />
    </Grid.RowDefinitions>
    <TextBlock Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="2" Height="30" Text="Please install updates" Foreground="#FFF" FontWeight="Bold" Margin="0,0,0,20" Grid.RowSpan="2"/>
    <Button Grid.Column="0" Grid.Row="1" Content="Restart Now" Margin="5 0 0 0" Width="80" Height="25" HorizontalAlignment="Right" />
    <Button Grid.Column="1" Grid.Row="1" Content="Snooze" Width="60" Height="25" Margin="10 0 0 0" HorizontalAlignment="Left" Click="bttnOK_Click" />
</Grid>

For some reason TextBlock is clickable and when you click it, it closes the control.

Desired behavior: Non clickable TextBlock. When clicking TextBlock, control stays open.

Body:
It seems you have added <TextBlock ... Grid.RowSpan=2/> which makes the TextBlock enter the region of Buttons.
Alternatively if removing the RowSpan in TextBlock doesn't solve the issue, try adding IsHitTestVisible=false to TextBlock.

It looks like this,

<Grid>
<Grid.ColumnDefinitions>
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="150" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
    <RowDefinition Height="*" />
    <RowDefinition Height="1*" />
</Grid.RowDefinitions>
<TextBlock Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="2" Height="30" Text="Please install updates" Foreground="#FFF" FontWeight="Bold" Margin="0,0,0,20"/>
<Button Grid.Column="0" Grid.Row="1" Content="Restart Now" Margin="5 0 0 0" Width="80" Height="25" HorizontalAlignment="Right" />
<Button Grid.Column="1" Grid.Row="1" Content="Snooze" Width="60" Height="25" Margin="10 0 0 0" HorizontalAlignment="Left" Click="bttnOK_Click" />


问:
Find a character in a data frame and change adjacent rows
I have a large data frame with 250,000 rows and 35 columns. A simpler sample can be generated by the following code:

```<code>data.frame(a=letters[sample(10,26,replace = T)],b=letters[1:26],c=letters[26:1])
</code>```

I want to search for every occurrence of a chosen character, let's say "h" and then change the cell containing "h" and 5 rows above "h" to NA.

答:
We can use lapply to identify the character and replace to NA, and also replace the previous 5 rows. Assuming that your data frame is dt. I created the dt as follows.

```<code>set.seed(155)

dt <- data.frame(a=letters[sample(10,26,replace = T)],b=letters[1:26],c=letters[26:1],
                 stringsAsFactors = FALSE)
head(dt)
#   a b c
# 1 h a z
# 2 e b y
# 3 h c x
# 4 h d w
# 5 e e v
# 6 d f u
</code>```

And then we can first replace all h to NA.

```<code>dt2 <- dt
dt2[dt2 == "h"] <- NA

# head(dt2)
#      a b c
# 1 <NA> a z
# 2    e b y
# 3 <NA> c x
# 4 <NA> d w
# 5    e e v
# 6    d f u
</code>```

We can then replace all the previous 5 rows by NA as follows. dt3 is the final output.

```<code>dt3 <- dt2
dt3[] <- lapply(dt3, function(x){
  index <- which(is.na(x))
  index2 <- lapply(index, function(x) x:(x - 5))
  index3 <- unique(unlist(index2))
  index4 <- index3[index3 > 0]
  x[index4] <- NA
  return(x)
})

dt3
#       a    b    c
# 1  <NA>    a    z
# 2  <NA>    b    y
# 3  <NA> <NA>    x
# 4  <NA> <NA>    w
# 5  <NA> <NA>    v
# 6  <NA> <NA>    u
# 7  <NA> <NA>    t
# 8     f <NA>    s
# 9     e    i    r
# 10    f    j    q
# 11    j    k    p
# 12    b    l    o
# 13    b    m    n
# 14    e    n <NA>
# 15    b    o <NA>
# 16    i    p <NA>
# 17    e    q <NA>
# 18    f    r <NA>
# 19    i    s <NA>
# 20    b    t    g
# 21    g    u    f
# 22    e    v    e
# 23    c    w    d
# 24    c    x    c
# 25    b    y    b
# 26    e    z    a
</code>```

Body:
I have a large data frame with 250,000 rows and 35 columns. A simpler sample can be generated by the following code:

data.frame(a=letters[sample(10,26,replace = T)],b=letters[1:26],c=letters[26:1])

I want to search for every occurrence of a chosen character, let's say "h" and then change the cell containing "h" and 5 rows above "h" to NA.

Body:
We can use lapply to identify the character and replace to NA, and also replace the previous 5 rows. Assuming that your data frame is dt. I created the dt as follows.

set.seed(155)

dt <- data.frame(a=letters[sample(10,26,replace = T)],b=letters[1:26],c=letters[26:1],
                 stringsAsFactors = FALSE)
head(dt)
#   a b c
# 1 h a z
# 2 e b y
# 3 h c x
# 4 h d w
# 5 e e v
# 6 d f u

And then we can first replace all h to NA.

dt2 <- dt
dt2[dt2 == "h"] <- NA

# head(dt2)
#      a b c
# 1 <NA> a z
# 2    e b y
# 3 <NA> c x
# 4 <NA> d w
# 5    e e v
# 6    d f u

We can then replace all the previous 5 rows by NA as follows. dt3 is the final output.

dt3 <- dt2
dt3[] <- lapply(dt3, function(x){
  index <- which(is.na(x))
  index2 <- lapply(index, function(x) x:(x - 5))
  index3 <- unique(unlist(index2))
  index4 <- index3[index3 > 0]
  x[index4] <- NA
  return(x)
})

dt3
#       a    b    c
# 1  <NA>    a    z
# 2  <NA>    b    y
# 3  <NA> <NA>    x
# 4  <NA> <NA>    w
# 5  <NA> <NA>    v
# 6  <NA> <NA>    u
# 7  <NA> <NA>    t
# 8     f <NA>    s
# 9     e    i    r
# 10    f    j    q
# 11    j    k    p
# 12    b    l    o
# 13    b    m    n
# 14    e    n <NA>
# 15    b    o <NA>
# 16    i    p <NA>
# 17    e    q <NA>
# 18    f    r <NA>
# 19    i    s <NA>
# 20    b    t    g
# 21    g    u    f
# 22    e    v    e
# 23    c    w    d
# 24    c    x    c
# 25    b    y    b
# 26    e    z    a


问:
Getting started with Websphere portal 6.1
Okay, my company is a bank. The upper management is dead set on a websphere IBM portal. Apparently IBM is tossing them a bone they can't refuse. We're also a very big IBM shop anyhow with A LOT of LotusNotes applications.

In my experience with IBM, they generally make you go through them to learn their stuff. I'm having to sort of jump in head first so that I can give an overview of the product to the development team. I'm specifically trying to find free portal development resources. Heck a hello world portal would be fine. Also, when I say portal, this also includes portlets.

Another issue is that I learn best by doing. Can someone point me to a freetrial link or something for websphere portal? Really, I just need anything that will let me get my feet wet with the sort of coding that I'll need to do for the actual portal.

Thoughts, comments, suggestions are all welcome in any way/shape/form.

答:
For me, these two are very good CMS solutions:

Liferay

Alfresco

Liferay is an open source Portal based on Java. It has payed solutions.
Alfresco is only a CMS solution but it has social applications and many nice content management features.

To be honest, I've tested both Liferay and WebSphere Portal (I am a certified admin). Liferay seems more appealing at first but it lacks a couple of features (At least the versions I tred) that will slow you down in the middle of the deployment. It doesnt have many portlets from start (You will have to develop them)

Also, if you are planning on making a site that relies heavily on customization and personalization, Liferay doesnt have that much support.

WepSphere portal also have much better support for SSO (Single Sign On) and the security is better (Since you are a bank)

Hope it helps.

OwnerDisplayName: jason


问:
HTML Buttons Clicks sequential or parallel?
Is the click handling/detection for html buttons sequential or parallel? I already googled this topic but didn't find any usefull articles.</p>

答:
This article at MDN describes the event loop very well:

Each message is processed completely before any other message is processed. This offers some nice properties when reasoning about your program, including the fact that whenever a function runs, it cannot be pre-empted and will run entirely before any other code runs (and can modify data the function manipulates).

https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop


问:
How to use JIRA AUI functions in my own custom field - velocity edit.vm
I am trying use some AUI in my JIRA - in edit mode of my own custom field written in JAVA.
I found this page: https://docs.atlassian.com/aui/latest/sandbox/# and in future I would like to use set an example Auiselect2.

https://docs.atlassian.com/aui/5.5.1/docs/auiselect2.html - here is written, that this is only experimental, so which steps I should do to use it? In examples bellow you can see, I was trying to add this funcionality, but it simple did not work. I was using an example mentioned in docs -

edit.vm:

```<code>$webResourceManager.requireResource("cz.firma.rozy:zakaznik")

<form class="aui">
    <select id="select2-example" multiple>
        <option value="CONF">Confluence</option>
        <option value="JIRA">JIRA</option>
        <option value="BAM">Bamboo</option>
        <option value="JAG">JIRA Agile</option>
        <option value="CAP">JIRA Capture</option>
        <option value="AUI">AUI</option>
    </select>
</form>
</code>```

and zakaznik.js

```<code>AJS.$(function() {
    AJS.$("#select2-example").auiSelect2();
});
</code>```

And my atlassian-plugin.xml is:

```<code><web-resource key="zakaznik-resources" name="zakaznik Web Resources">
    <dependency>com.atlassian.auiplugin:ajs</dependency>
    <dependency>com.atlassian.auiplugin:jquery</dependency>
    <dependency>com.atlassian.auiplugin:jquery-ui-other</dependency>
    <dependency>com.atlassian.auiplugin:aui-select2</dependency>
    <context>atl.general</context>
    <context>atl.admin</context>
    <resource type="download" name="zakaznik.css" location="/css/zakaznik.css"/>
    <resource type="download" name="zakaznik.js" location="/js/zakaznik.js"/>
    <resource type="download" name="images/" location="/images"/>
    <context>zakaznik</context>
  </web-resource>

...
  <customfield-type name="Pridani zakaznika" i18n-name-key="customer-add.name" key="customer-add" class="cz.firma.rozy.jira.customfields.CustomerCustomField">
    <description key="customer-add.description">Plugin, ktery prida zakaznika z abry</description>
    <resource name="view" type="velocity" location="templates/viewCustomer.vm"/>
    <resource name="edit" type="velocity" location="templates/edit.vm"/>
  </customfield-type>
</code>```

But when I visit the edit mode, no jQuery is done - and browsers console does not write any error or warning.

答:
You just need to add following in your edit.vm

```<code>$webResourceManager.requireResourcesForContext("zakaznik")
</code>```

I don't agree with other answer provided. When we have already added the js in the resource file why do it again in edit.vm file. Just refer to the web resource we have already created with it's context.

Body:
I am trying use some AUI in my JIRA - in edit mode of my own custom field written in JAVA.
I found this page: https://docs.atlassian.com/aui/latest/sandbox/# and in future I would like to use set an example Auiselect2.

https://docs.atlassian.com/aui/5.5.1/docs/auiselect2.html - here is written, that this is only experimental, so which steps I should do to use it? In examples bellow you can see, I was trying to add this funcionality, but it simple did not work. I was using an example mentioned in docs -

edit.vm:

$webResourceManager.requireResource("cz.firma.rozy:zakaznik")

<form class="aui">
    <select id="select2-example" multiple>
        <option value="CONF">Confluence</option>
        <option value="JIRA">JIRA</option>
        <option value="BAM">Bamboo</option>
        <option value="JAG">JIRA Agile</option>
        <option value="CAP">JIRA Capture</option>
        <option value="AUI">AUI</option>
    </select>
</form>

and zakaznik.js

AJS.$(function() {
    AJS.$("#select2-example").auiSelect2();
});

And my atlassian-plugin.xml is:

<web-resource key="zakaznik-resources" name="zakaznik Web Resources">
    <dependency>com.atlassian.auiplugin:ajs</dependency>
    <dependency>com.atlassian.auiplugin:jquery</dependency>
    <dependency>com.atlassian.auiplugin:jquery-ui-other</dependency>
    <dependency>com.atlassian.auiplugin:aui-select2</dependency>
    <context>atl.general</context>
    <context>atl.admin</context>
    <resource type="download" name="zakaznik.css" location="/css/zakaznik.css"/>
    <resource type="download" name="zakaznik.js" location="/js/zakaznik.js"/>
    <resource type="download" name="images/" location="/images"/>
    <context>zakaznik</context>
  </web-resource>

...
  <customfield-type name="Pridani zakaznika" i18n-name-key="customer-add.name" key="customer-add" class="cz.firma.rozy.jira.customfields.CustomerCustomField">
    <description key="customer-add.description">Plugin, ktery prida zakaznika z abry</description>
    <resource name="view" type="velocity" location="templates/viewCustomer.vm"/>
    <resource name="edit" type="velocity" location="templates/edit.vm"/>
  </customfield-type>

But when I visit the edit mode, no jQuery is done - and browsers console does not write any error or warning.

Body:
You just need to add following in your edit.vm

$webResourceManager.requireResourcesForContext("zakaznik")

I don't agree with other answer provided. When we have already added the js in the resource file why do it again in edit.vm file. Just refer to the web resource we have already created with it's context.


问:
Scala: Class that is similar to QuantileTransformer in python
I am looking for a Scala implementation of Python's sklearn.preprocessing.QuantileTransformer class. There doesn't seem to be a single Class that can implement the entire functionality in scala.

The Python implementation has 3 major parts:

1) Compute quantiles for given data and percentile array using numpy.percentile(). If quantile lies between two input data points, then linear interpolation is used. The closest I can find in Scala is in breeze, which has percentile() function (Observation: The DataFrame.stats.approxQuantile() does not perform the linear interpolation and thus can't be used here).

2) Uses numpy.interp() to convert the input range of values to a given range. Eg If input data range is 1-100, it can be converted to any given range say 0-1. Again this uses linear interpolation when input data is present between 2 quantiles. The closest I can find in Scala is breeze.interpolation class.

3)Calculate the inverse CDF using numpy.ppf(). I believe, for this I can use the NormalDistribution class as one answer below or StandardScaler class.

Anything better to make the coding short and simple?

答: The Apache Commons Math library has a NormalDistribution class, which has an inverseCumulativeProbability method that calculates the specified quantile value. That should suit your purposes.


问:
Lagom persistentEntityRegistry.register doesn't work
I'm trying to configure my first Entity with Cassandra and Lagom.

I'm asking about how Lagom save the entity in Cassandra?

For example, this is my UserServiceImpl class:

```<code>public class UserServiceImpl implements UserService {

    private final PersistentEntityRegistry persistentEntityRegistry;

    @Inject
    public UserServiceImpl(PersistentEntityRegistry persistentEntityRegistry) {
        this.persistentEntityRegistry = persistentEntityRegistry;
        persistentEntityRegistry.register(UserEntity.class);
    }

    @Override
    public ServiceCall<NotUsed, String> getUserInfo(String id) {
        return (request) -> {
            // Look up the user entity for the given ID.
            PersistentEntityRef<UserCommand> ref = persistentEntityRegistry.refFor(UserEntity.class, id);
            // Ask the entity the Hello command.
            return ref.ask(new UserCommand.Hello(id, Optional.empty()));
        };
    }
}
</code>```

So by executing:

persistentEntityRegistry.register(UserEntity.class);

Should I have a user table into Cassandra? because I only have:

I can't understand should I create the table user before starting my Lagom project or we only save the event?

Any help, please

答:
Lagom does not require a table for the entity because it's not based on an object-relational mapping or anything similar. Its persistence layer is based on the principles of Event Sourcing.

The messages table will contain the events that are emitted by your entity and its state is recovered each time you bring it back into memory.

Basically, the events are being saved in json format in the messages table.

We also have the concept of snapshots. The entity state may be saved as a snapshot (also using json). This happens after every 100 events and it's a small optimization to avoid to replay the events from scratch each time.

I'll try to explain shortly the whole mechanism.

A command is sent to an entity and events are persisted (that happens in the command handler). After the events are persisted, they are applied to the entity to mutate it (that happens on the event handler).

You restart the service and send a new command to that same entity. At that point the entity is not in memory, so Lagom will bring it into memory but before handling that new command it will replay the history of events for this entity in order to bring it back to the state it had when the system went down.

After that, the command is applied and new events are persisted.

After 100 events a snapshot of the entity will be saved and next time, when it's needed to replay that same entity, we load first the snapshot and then we apply the events that took place after the snapshot. So, in that case we don't need to replay the whole event history.

Body:
I'm trying to configure my first Entity with Cassandra and Lagom.

I'm asking about how Lagom save the entity in Cassandra?

For example, this is my UserServiceImpl class:

public class UserServiceImpl implements UserService {

    private final PersistentEntityRegistry persistentEntityRegistry;

    @Inject
    public UserServiceImpl(PersistentEntityRegistry persistentEntityRegistry) {
        this.persistentEntityRegistry = persistentEntityRegistry;
        persistentEntityRegistry.register(UserEntity.class);
    }

    @Override
    public ServiceCall<NotUsed, String> getUserInfo(String id) {
        return (request) -> {
            // Look up the user entity for the given ID.
            PersistentEntityRef<UserCommand> ref = persistentEntityRegistry.refFor(UserEntity.class, id);
            // Ask the entity the Hello command.
            return ref.ask(new UserCommand.Hello(id, Optional.empty()));
        };
    }
}

So by executing:

persistentEntityRegistry.register(UserEntity.class);

Should I have a user table into Cassandra? because I only have:

I can't understand should I create the table user before starting my Lagom project or we only save the event?

Any help, please


问:
How do I let python know that I click "search" button for aspx website?
I want to get all the shareholding in CCASS and % of the total number of issued shares from on 03/04/2017. Here is the link.

http://www.hkexnews.hk/sdw/search/mutualmarket.aspx?t=hk

Here is my code.

```<code>import requests
from bs4 import BeautifulSoup
url = "http://www.hkexnews.hk/sdw/search/mutualmarket.aspx?t=hk"
data = {
"sortBy":"",
"alertMsg":"",
"ddlShareholdingDay":"03",
"ddlShareholdingMonth":"04",
"ddlShareholdingYear":"2017",
}
req = requests.post(url, data)
soup = BeautifulSoup(req.content, 'html.parser')
print(soup)
</code>```

Then the output shows the data of the original website, which is the data without clicking "search" button.

I think the problem is form data, I don't know how to let python know that I click "search" button.

Here is the form data.
form data

The rest of the form data are __VIEWSTATE, __VIEWSTATEGENERATOR and __EVENTVALIDATION.

By the way, I don't know what is btnSearch.x and btnSearch.y, they are always changing when I click "search".

Thank you very much.

答:
Here is my code to handle date, 360 days max. to scrap, include the date of typhoon no. 8 pausing trading</p>

```<code>for i in range(360):
    datetime_today = datetime.date.today() - datetime.timedelta(days=i)
    datetime_today = datetime_today + datetime.timedelta(days=-1)
    trade_day = datetime.datetime.strptime(str(datetime_today), '%Y-%m-%d').date()

    weekdaylist = [0,1,2,3,4]
    if trade_day.weekday() in weekdaylist:
        day_list.append(str(trade_day))
holidays = ['2017-08-23', '2017-10-02', '2017-10-05', '2017-05-30', '2017-05-01', '2017-05-03', '2017-04-17', '2017-04-14', '2017-04-04','2017-01-30','2017-01-31','2017-01-02']
day_list = [x for x in day_list if x not in holidays]
</code>```

Body:
I want to get all the shareholding in CCASS and % of the total number of issued shares from on 03/04/2017. Here is the link.

http://www.hkexnews.hk/sdw/search/mutualmarket.aspx?t=hk

Here is my code.

import requests
from bs4 import BeautifulSoup
url = "http://www.hkexnews.hk/sdw/search/mutualmarket.aspx?t=hk"
data = {
"sortBy":"",
"alertMsg":"",
"ddlShareholdingDay":"03",
"ddlShareholdingMonth":"04",
"ddlShareholdingYear":"2017",
}
req = requests.post(url, data)
soup = BeautifulSoup(req.content, 'html.parser')
print(soup)

Then the output shows the data of the original website, which is the data without clicking "search" button.

I think the problem is form data, I don't know how to let python know that I click "search" button.

Here is the form data.
form data

The rest of the form data are __VIEWSTATE, __VIEWSTATEGENERATOR and __EVENTVALIDATION.

By the way, I don't know what is btnSearch.x and btnSearch.y, they are always changing when I click "search".

Thank you very much.

Body:
Here is my code to handle date, 360 days max. to scrap, include the date of typhoon no. 8 pausing trading

for i in range(360):
    datetime_today = datetime.date.today() - datetime.timedelta(days=i)
    datetime_today = datetime_today + datetime.timedelta(days=-1)
    trade_day = datetime.datetime.strptime(str(datetime_today), '%Y-%m-%d').date()

    weekdaylist = [0,1,2,3,4]
    if trade_day.weekday() in weekdaylist:
        day_list.append(str(trade_day))
holidays = ['2017-08-23', '2017-10-02', '2017-10-05', '2017-05-30', '2017-05-01', '2017-05-03', '2017-04-17', '2017-04-14', '2017-04-04','2017-01-30','2017-01-31','2017-01-02']
day_list = [x for x in day_list if x not in holidays]


问:
Read excel (xlsx) file in java using Apoche POI (getting weird numbers)
I have to open a testdate for a schoolproject. This testdate is a excel(xlsx) file that includes number, letter, date and time. But with the code below it reads the excel file, but i get weird numbers like 42538.0 and 1.153481443E9. after date.

```<code>public class Page4_Controller implements Initializable {

    @FXML
    private Button button1;

    public void Button1Action(ActionEvent event) throws IOException {
        //Initialize excel file
        FileChooser fc = new FileChooser();
        fc.getExtensionFilters().addAll(
                new ExtensionFilter("Excel Files", "*.xlsx"));
        File selectedFile = fc.showOpenDialog(null);

        // Read file
        readXLSXFile(selectedFile.getAbsolutePath());
    }

    public static void readXLSXFile(String excelFilePath) throws IOException {
        FileInputStream fys = new FileInputStream(new File(excelFilePath));

        //Create workbook instance that refers to .xlsx file
        XSSFWorkbook wb = new XSSFWorkbook(fys);

        //Create a sheet object to retrive the sheet
        XSSFSheet sheet = wb.getSheetAt(0);

        //That is for evalueate the cell type
        FormulaEvaluator forlulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
        DataFormatter df = new DataFormatter();

        //Default data for database (comes later)
        //String airport = sheet.getRow(1).getCell(1).getStringCellValue();
        //Date date = sheet.getRow(2).getCell(1).getDateCellValue();

        for (Row row : sheet) {
            for (Cell cell : row) {
                switch (forlulaEvaluator.evaluateInCell(cell).getCellType()) {
                    //If cell is a numeric format
                    case Cell.CELL_TYPE_NUMERIC:
                        System.out.print(cell.getNumericCellValue() + "\t");
                        System.out.print(df.formatCellValue(cell) + "\t");
                        break;
                    //If cell is a string format
                    case Cell.CELL_TYPE_STRING:
                        System.out.print(cell.getRichStringCellValue() + "\t");
                        break;
                }

            }
            System.out.println();
        }
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
    }

}
</code>```

答:
Dates in Excel are represented as a "serial number", where the part in front of the decimal separator are the days since 1-1-1900, and the part after the decimal is the fraction of the day, so noon is 0.5. So if you get the number itself, you have to do the conversion manually.

POI can do the conversion for you. See How to read Excel cell having Date with Apache POI? for an example.

Body:
I have to open a testdate for a schoolproject. This testdate is a excel(xlsx) file that includes number, letter, date and time. But with the code below it reads the excel file, but i get weird numbers like 42538.0 and 1.153481443E9. after date.

public class Page4_Controller implements Initializable {

    @FXML
    private Button button1;

    public void Button1Action(ActionEvent event) throws IOException {
        //Initialize excel file
        FileChooser fc = new FileChooser();
        fc.getExtensionFilters().addAll(
                new ExtensionFilter("Excel Files", "*.xlsx"));
        File selectedFile = fc.showOpenDialog(null);

        // Read file
        readXLSXFile(selectedFile.getAbsolutePath());
    }

    public static void readXLSXFile(String excelFilePath) throws IOException {
        FileInputStream fys = new FileInputStream(new File(excelFilePath));

        //Create workbook instance that refers to .xlsx file
        XSSFWorkbook wb = new XSSFWorkbook(fys);

        //Create a sheet object to retrive the sheet
        XSSFSheet sheet = wb.getSheetAt(0);

        //That is for evalueate the cell type
        FormulaEvaluator forlulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
        DataFormatter df = new DataFormatter();

        //Default data for database (comes later)
        //String airport = sheet.getRow(1).getCell(1).getStringCellValue();
        //Date date = sheet.getRow(2).getCell(1).getDateCellValue();

        for (Row row : sheet) {
            for (Cell cell : row) {
                switch (forlulaEvaluator.evaluateInCell(cell).getCellType()) {
                    //If cell is a numeric format
                    case Cell.CELL_TYPE_NUMERIC:
                        System.out.print(cell.getNumericCellValue() + "\t");
                        System.out.print(df.formatCellValue(cell) + "\t");
                        break;
                    //If cell is a string format
                    case Cell.CELL_TYPE_STRING:
                        System.out.print(cell.getRichStringCellValue() + "\t");
                        break;
                }

            }
            System.out.println();
        }
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
    }

}


问:
How do you enable customers use their openid on your website, just like stackoverflow?
I want customers to use their openId on my site. I googled for this but didn't find any good tutorial. I use PHP and MySQL.

There is one at Plaxo. But it says we should download something from JanRain.com.

I saw the openId module of Drupal. It doesn't want anything to be downloaded.

Can anyone tell me what to do exactly?

答: I only glanced at it, but does http://www.saeven.net/openid.htm do the trick for you?</p>

OwnerDisplayName: iSattar

OwnerDisplayName: Andy