问:
Pattern Matching Python
I'm currently stuck on trying to make a naive algorithm which given a piece of a  pattern e.g aabba
search for it in a text e.g abbbbaababaabbaaabbaa one letter at a time. It will compare a with the text if that is right then compares the next letter and if that's wrong the whole pattern will shift one and compare a with b etc

we were give code example

```<code>print "Input text: ",
text = raw_input()
print "Input pattern: ",
pattern = raw_input()

index = text.find(pattern)
while index > -1:
    print index
    index = text.find(pattern, index+1)
</code>```

but the find() function in python is too fast(I need a non optimized sort of algorithm, using while
and for loops statements I guess).

Any help appreciated,
Thanks

答:
I guess here's what you need, the following code does character-by-character comparison. You may also replace the calls to find by iterations over text which includes checks whether the first character of text matches the first character of pattern:

```<code>def my_find(text, pattern):
    '''Find the start index of a pattern string in a text.
    Return -1 if not found, and assume that pattern is not empty'''

    found = False
    current_start_index = text.find(pattern[0])
    index_text = current_start_index
    index_pattern = 0

    while not found and index_text + len(pattern) - 1 < len(text) and \
            current_start_index != -1:

        index_text += 1
        index_pattern += 1

        while index_text < len(text) and \
                index_pattern < len(pattern) and \
                text[index_text] == pattern[index_pattern]:

            if index_pattern == len(pattern) - 1:
                found = True
                break
            else:
                index_text += 1
                index_pattern += 1

        if not found:
            current_start_index = text.find(pattern[0],current_start_index + 1)
            index_text = current_start_index

    if found:
        return current_start_index
    else:
        -1
</code>```

Title: Pattern Matching Python

Body:
I'm currently stuck on trying to make a naive algorithm which given a piece of a  pattern e.g aabba
search for it in a text e.g abbbbaababaabbaaabbaa one letter at a time. It will compare a with the text if that is right then compares the next letter and if that's wrong the whole pattern will shift one and compare a with b etc

we were give code example

print "Input text: ",
text = raw_input()
print "Input pattern: ",
pattern = raw_input()

index = text.find(pattern)
while index > -1:
    print index
    index = text.find(pattern, index+1)

but the find() function in python is too fast(I need a non optimized sort of algorithm, using while
and for loops statements I guess).

Any help appreciated,
Thanks

Body:
I guess here's what you need, the following code does character-by-character comparison. You may also replace the calls to find by iterations over text which includes checks whether the first character of text matches the first character of pattern:

def my_find(text, pattern):
    '''Find the start index of a pattern string in a text.
    Return -1 if not found, and assume that pattern is not empty'''

    found = False
    current_start_index = text.find(pattern[0])
    index_text = current_start_index
    index_pattern = 0

    while not found and index_text + len(pattern) - 1 < len(text) and \
            current_start_index != -1:

        index_text += 1
        index_pattern += 1

        while index_text < len(text) and \
                index_pattern < len(pattern) and \
                text[index_text] == pattern[index_pattern]:

            if index_pattern == len(pattern) - 1:
                found = True
                break
            else:
                index_text += 1
                index_pattern += 1

        if not found:
            current_start_index = text.find(pattern[0],current_start_index + 1)
            index_text = current_start_index

    if found:
        return current_start_index
    else:
        -1


来源: stackexchange

问:
How to join two lists of parent/child objects using LINQ while grouping on child key
I want to create a list of CustomerOrder and group the quantity by item_id. The code nearly works, but it doesn't group on item_id.

I also think there is something wrong in terms of performance/memory usage. It works when the total list size is ~1000 but when it gets upto ~30,000 it has memory issues.

I suspect the issue is with "select new Customer". I probably shouldn't be using ToList(), I couldn't do it as IEnumerable.
I thought that GroupJoin would be the way to go, but I can't get that to work either. The example I found using group join had a "foreign key" value in the child table, I don't have that.

```<code>public class CustomerOrder
{
    public int order_id { get; set; }
    public List<OrderLine> OrderLines { get; set; }
}

public class OrderLine
{
    public int item_id { get; set; }
    public int quantity { get; set; }
}

public class Program
{
    public static void Main()
    {
        List<CustomerOrder> list1 = new List<CustomerOrder>()
        {new CustomerOrder{order_id = 1, OrderLines = new List<OrderLine>()
        {new OrderLine()
        {item_id = 123, quantity = 2}, new OrderLine()
        {item_id = 456, quantity = 3}}}};

        List<CustomerOrder> list2 = new List<CustomerOrder>()
        {new CustomerOrder{order_id = 1, OrderLines = new List<OrderLine>()
        {new OrderLine()
        {item_id = 456, quantity = 2}, new OrderLine()
        {item_id = 789, quantity = 3}}}};

        var orderdetails =
            from g in list1.Concat(list2).GroupBy(x => x.order_id) select new CustomerOrder { order_id = g.Key, OrderLines = g.SelectMany(x => x.OrderLines).ToList() };

        foreach (var item in orderdetails)
        {
            Console.WriteLine(item.order_id);
            foreach (var line in item.OrderLines)
            {
                Console.WriteLine("{0} {1}", line.item_id, line.quantity);
            }
        }
    }
}
</code>```

The current output is:

```<code>1
123 2
456 3
456 2
789 3
</code>```

My desired output is:

```<code>1
123 2
456 5
789 3
</code>```

Each list should be unique based on order_id but there would be overlap in terms of order_lines. One list will almost always be significantly larger than the other. The current ratio is 29,500:500 on a 30K sample.

答:
You need to group your OrderLines too:

```<code>var orderdetails =
    from g in list1.Concat(list2).GroupBy(x => x.order_id)
    select new CustomerOrder
    {
        order_id = g.Key,
        OrderLines = g
            .SelectMany(x => x.OrderLines)
            .GroupBy(ol => ol.item_id)
            .Select(g => new OrderLine
            {
                item_id = g.Key, quantity = g.Sum(gg => gg.quantity)
            })
            .ToList()
    };
</code>```

As for performance to handle 30k+ entries (especially if first collection is guaranteed to have unique orders) I think better would be create a dictionary from  the first collection, switching to for/foreach loop on the second collection and in it add/update elements in dictionary (including the child objects) and not create new ones.

Or at least try:

```<code>var orderdetails =  list1
    .Concat(list2)
    .GroupBy(x => x.order_id)
    .Select(g =>
    {
        // may be better to materialize group,
        // and use it for First and SelectMany
        var order = g.First();
        order.OrderLines = g
            .SelectMany(og => og.OrderLines)
            .GroupBy(ol => ol.item_id)
            .Select(olg =>
            {
                var line = olg.First();
                line.quantity = olg.Sum(ol => ol.quantity);
                return line;
            })
            .ToList();
        return order;
    })
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to create a list of CustomerOrder and group the quantity by item_id. The code nearly works, but it doesn't group on item_id.

I also think there is something wrong in terms of performance/memory usage. It works when the total list size is ~1000 but when it gets upto ~30,000 it has memory issues.

I suspect the issue is with "select new Customer". I probably shouldn't be using ToList(), I couldn't do it as IEnumerable.
I thought that GroupJoin would be the way to go, but I can't get that to work either. The example I found using group join had a "foreign key" value in the child table, I don't have that.

public class CustomerOrder
{
    public int order_id { get; set; }
    public List<OrderLine> OrderLines { get; set; }
}

public class OrderLine
{
    public int item_id { get; set; }
    public int quantity { get; set; }
}

public class Program
{
    public static void Main()
    {
        List<CustomerOrder> list1 = new List<CustomerOrder>()
        {new CustomerOrder{order_id = 1, OrderLines = new List<OrderLine>()
        {new OrderLine()
        {item_id = 123, quantity = 2}, new OrderLine()
        {item_id = 456, quantity = 3}}}};

        List<CustomerOrder> list2 = new List<CustomerOrder>()
        {new CustomerOrder{order_id = 1, OrderLines = new List<OrderLine>()
        {new OrderLine()
        {item_id = 456, quantity = 2}, new OrderLine()
        {item_id = 789, quantity = 3}}}};

        var orderdetails =
            from g in list1.Concat(list2).GroupBy(x => x.order_id) select new CustomerOrder { order_id = g.Key, OrderLines = g.SelectMany(x => x.OrderLines).ToList() };

        foreach (var item in orderdetails)
        {
            Console.WriteLine(item.order_id);
            foreach (var line in item.OrderLines)
            {
                Console.WriteLine("{0} {1}", line.item_id, line.quantity);
            }
        }
    }
}

The current output is:

1
123 2
456 3
456 2
789 3

My desired output is:

1
123 2
456 5
789 3

Each list should be unique based on order_id but there would be overlap in terms of order_lines. One list will almost always be significantly larger than the other. The current ratio is 29,500:500 on a 30K sample.

Body:
You need to group your OrderLines too:

var orderdetails =
    from g in list1.Concat(list2).GroupBy(x => x.order_id)
    select new CustomerOrder
    {
        order_id = g.Key,
        OrderLines = g
            .SelectMany(x => x.OrderLines)
            .GroupBy(ol => ol.item_id)
            .Select(g => new OrderLine
            {
                item_id = g.Key, quantity = g.Sum(gg => gg.quantity)
            })
            .ToList()
    };

As for performance to handle 30k+ entries (especially if first collection is guaranteed to have unique orders) I think better would be create a dictionary from  the first collection, switching to for/foreach loop on the second collection and in it add/update elements in dictionary (including the child objects) and not create new ones.

Or at least try:

var orderdetails =  list1
    .Concat(list2)
    .GroupBy(x => x.order_id)
    .Select(g =>
    {
        // may be better to materialize group,
        // and use it for First and SelectMany
        var order = g.First();
        order.OrderLines = g
            .SelectMany(og => og.OrderLines)
            .GroupBy(ol => ol.item_id)
            .Select(olg =>
            {
                var line = olg.First();
                line.quantity = olg.Sum(ol => ol.quantity);
                return line;
            })
            .ToList();
        return order;
    })


问:
Get specific data from JSON file to listview
Trying to get second user data only

which have id :2 (whole his data)

Problem is when I get data, it show all users, not only second.

I heard about I can get it using Arraylist, but cant figure out how to make it.

```<code>mListView.get(position).get(Mykey);
</code>```

is there anyway to get specific user data, not show all users data, I'm new in android

users.json

```<code>[
{
"id": "1",
"name": "tester1",
"username": "user1",
"verify": "1",
"about": "tesst",
"description": "description....... etc",
"mobile": "+.....",
"lvl": "1",
"imageurl": "..../pic.png",
"technologyexists": "1",
"password": "xxx"
},
{
"id": "2",
"name": "tester2",
"username": "user2",
"verify": "0",
"about": "tesst",
"description": "description ....... etc",
"mobile": "+.....",
"lvl": "1",
"imageurl": "..../pic.png",
"technologyexists": "1",
"password": "xxx"
},
{
"id": "3",
"name": "tester3",
"username": "user3",
"verify": "0",
"about": "tesst",
"description": "description ....... etc",
"mobile": "+.....",
"lvl": "1",
"imageurl": "..../pic.png",
"technologyexists": "1",
"password": "xxx"
}
]
</code>```

ActivityMain

```<code>class Spacecraft {
    /*
    INSTANCE FIELDS
     */
    @SerializedName("id")
    private String id;

    @SerializedName("name")
    private String name;

    @SerializedName("username")
    private String username;

    @SerializedName("password")
    private String password;

    @SerializedName("about")
    private String about;

    @SerializedName("description")
    private String description;

    @SerializedName("mobile")
    private String mobile;

    @SerializedName("lvl")
    private String lvl;

    @SerializedName("imageurl")
    private String imageURL;

    @SerializedName("technologyexists")
    private int technologyexists;

    @SerializedName("verify")
    private String verify;
    ////////

    public Spacecraft(String id, String name, String username,String password, String about, String description,  String mobile, String lvl, String imageURL, int technologyexists, String verify) {

        this.id = id;
        this.name = name;

        this.username = username;
        this.password = password;

        this.about = about;
        this.description = description;

        this.mobile = mobile;
        this.lvl = lvl;

        this.imageURL = imageURL;
        this.technologyexists = technologyexists;

        this.verify = verify;

    }

    /*
     *GETTERS AND SETTERS
     */
    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public String getusername() {
        return username;
    }

    public String getpassword() {
        return password;
    }

    public String getAbout() {
        return about;
    }

    public String getImageURL() {
        return imageURL;
    }

    public String getMobile() {
        return mobile;
    }

    public String getlvl() {
        return lvl;
    }

    public String getDescription() {
        return description;
    }

    public String getVerify() {
        return verify;
    }

    public int getTechnologyExists() {
        return technologyexists;
    }

    /*
    TOSTRING
     */
    @Override
    public String toString() {
        return name;
    }
}

 interface MyAPIService {

    @GET("/users.json")
    Call<List<Spacecraft>> getSpacecrafts();
}

    static class RetrofitClientInstance {

    private static Retrofit retrofit;
    private static final String BASE_URL = "http://Server_ip_to_get_json_file:80/";

    public static Retrofit getRetrofitInstance() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

    class ListViewAdapter extends BaseAdapter{

    private List<Spacecraft> spacecrafts;
    private Context context;

    public ListViewAdapter(Context context,List<Spacecraft> spacecrafts){
        this.context = context;
        this.spacecrafts = spacecrafts;
    }

    @Override
    public int getCount() {
        return spacecrafts.size();
    }

    @Override
    public Object getItem(int pos) {
        return spacecrafts.get(pos);
    }

    @Override
    public long getItemId(int pos) {
        return pos;
    }

    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        if(view==null)
        {
            view=LayoutInflater.from(context).inflate(R.layout.model,viewGroup,false);
        }

        TextView nameTxt = view.findViewById(R.id.nameTextView);
        TextView txtPropellant = view.findViewById(R.id.propellantTextView);
        CheckBox chkTechExists = view.findViewById(R.id.myCheckBox);
        ImageView spacecraftImageView = view.findViewById(R.id.spacecraftImageView);

        final Spacecraft thisSpacecraft= spacecrafts.get(position);

        nameTxt.setText(thisSpacecraft.getName());
        //  txtPropellant.setText("Lvl : "+thisSpacecraft.getPropellant());
        txtPropellant.setText("Lvl : "+thisSpacecraft.getlvl());
        chkTechExists.setChecked( thisSpacecraft.getTechnologyExists()==1);
        chkTechExists.setEnabled(false);

        if(thisSpacecraft.getImageURL() != null && thisSpacecraft.getImageURL().length()>0)
        {
            Picasso.get().load(thisSpacecraft.getImageURL()).placeholder(R.drawable.pic).into(spacecraftImageView);
        }else {
            Toast.makeText(context, "Empty Image URL", Toast.LENGTH_LONG).show();
            Picasso.get().load(R.drawable.pic).into(spacecraftImageView);
        }

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //  Toast.makeText(context, "This : " + thisSpacecraft.getName(), Toast.LENGTH_SHORT).show();

                //  Toast.makeText(context, "This : " + thisSpacecraft.getImageURL(), Toast.LENGTH_SHORT).show();

                Intent myIntent = new Intent(Main3Activity.this, Main4Activity.class);

                myIntent.putExtra("Name", thisSpacecraft.getName());
                myIntent.putExtra("Uri", thisSpacecraft.getImageURL());

                myIntent.putExtra("Mobile", thisSpacecraft.getMobile());
                myIntent.putExtra("Lvl", thisSpacecraft.getlvl());

                myIntent.putExtra("Description", thisSpacecraft.getDescription());

                myIntent.putExtra("About", thisSpacecraft.getAbout());

                myIntent.putExtra("Verify", thisSpacecraft.getVerify());

                myIntent.putExtra("User_ID", thisSpacecraft.getId());

                myIntent.putExtra("Username", thisSpacecraft.getusername());

                myIntent.putExtra("Password", thisSpacecraft.getpassword());

                myIntent.putExtra("Username_me", Username_me);

                startActivity(myIntent);

                update();
            }
        });

        return view;
    }
}

  private ListViewAdapter adapter;
private ListView mListView;
ProgressBar myProgressBar;
private int mImageResource;

private void populateListView(List<Spacecraft> spacecraftList) {
    mListView = findViewById(R.id.mListView);

    adapter = new ListViewAdapter(this,spacecraftList);
    mListView.setAdapter(adapter);
}

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

           final ProgressBar myProgressBar= findViewById(R.id.myProgressBar);
    myProgressBar.setIndeterminate(true);
    myProgressBar.setVisibility(View.VISIBLE);

    /*Create handle for the RetrofitInstance interface*/
    MyAPIService myAPIService = RetrofitClientInstance.getRetrofitInstance().create(MyAPIService.class);

    Call<List<Spacecraft>> call = myAPIService.getSpacecrafts();
    call.enqueue(new Callback<List<Spacecraft>>() {

           @Override
        public void onResponse(Call<List<Spacecraft>> call, Response<List<Spacecraft>> response) {
            myProgressBar.setVisibility(View.GONE);
            populateListView(response.body());
        }
        @Override
        public void onFailure(Call<List<Spacecraft>> call, Throwable throwable) {
            myProgressBar.setVisibility(View.GONE);
            //  Toast.makeText(Main3Activity.this, throwable.getMessage(), Toast.LENGTH_LONG).show();
            Toast.makeText(Main3Activity.this, "Check Your Internet Connection", Toast.LENGTH_LONG).show();
        }
    });
}

}
</code>```

答:
```<code>String id = object.getString("id");

if(id.equals("1"))
{
   //do your code
}
</code>```

Body:
Trying to get second user data only

which have id :2 (whole his data)

Problem is when I get data, it show all users, not only second.

I heard about I can get it using Arraylist, but cant figure out how to make it.

mListView.get(position).get(Mykey);

is there anyway to get specific user data, not show all users data, I'm new in android

users.json

[
{
"id": "1",
"name": "tester1",
"username": "user1",
"verify": "1",
"about": "tesst",
"description": "description....... etc",
"mobile": "+.....",
"lvl": "1",
"imageurl": "..../pic.png",
"technologyexists": "1",
"password": "xxx"
},
{
"id": "2",
"name": "tester2",
"username": "user2",
"verify": "0",
"about": "tesst",
"description": "description ....... etc",
"mobile": "+.....",
"lvl": "1",
"imageurl": "..../pic.png",
"technologyexists": "1",
"password": "xxx"
},
{
"id": "3",
"name": "tester3",
"username": "user3",
"verify": "0",
"about": "tesst",
"description": "description ....... etc",
"mobile": "+.....",
"lvl": "1",
"imageurl": "..../pic.png",
"technologyexists": "1",
"password": "xxx"
}
]

ActivityMain

class Spacecraft {
    /*
    INSTANCE FIELDS
     */
    @SerializedName("id")
    private String id;

    @SerializedName("name")
    private String name;

    @SerializedName("username")
    private String username;

    @SerializedName("password")
    private String password;

    @SerializedName("about")
    private String about;

    @SerializedName("description")
    private String description;

    @SerializedName("mobile")
    private String mobile;

    @SerializedName("lvl")
    private String lvl;

    @SerializedName("imageurl")
    private String imageURL;

    @SerializedName("technologyexists")
    private int technologyexists;

    @SerializedName("verify")
    private String verify;
    ////////

    public Spacecraft(String id, String name, String username,String password, String about, String description,  String mobile, String lvl, String imageURL, int technologyexists, String verify) {

        this.id = id;
        this.name = name;

        this.username = username;
        this.password = password;

        this.about = about;
        this.description = description;

        this.mobile = mobile;
        this.lvl = lvl;

        this.imageURL = imageURL;
        this.technologyexists = technologyexists;

        this.verify = verify;

    }

    /*
     *GETTERS AND SETTERS
     */
    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public String getusername() {
        return username;
    }

    public String getpassword() {
        return password;
    }

    public String getAbout() {
        return about;
    }

    public String getImageURL() {
        return imageURL;
    }

    public String getMobile() {
        return mobile;
    }

    public String getlvl() {
        return lvl;
    }

    public String getDescription() {
        return description;
    }

    public String getVerify() {
        return verify;
    }

    public int getTechnologyExists() {
        return technologyexists;
    }

    /*
    TOSTRING
     */
    @Override
    public String toString() {
        return name;
    }
}

 interface MyAPIService {

    @GET("/users.json")
    Call<List<Spacecraft>> getSpacecrafts();
}

    static class RetrofitClientInstance {

    private static Retrofit retrofit;
    private static final String BASE_URL = "http://Server_ip_to_get_json_file:80/";

    public static Retrofit getRetrofitInstance() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

    class ListViewAdapter extends BaseAdapter{

    private List<Spacecraft> spacecrafts;
    private Context context;

    public ListViewAdapter(Context context,List<Spacecraft> spacecrafts){
        this.context = context;
        this.spacecrafts = spacecrafts;
    }

    @Override
    public int getCount() {
        return spacecrafts.size();
    }

    @Override
    public Object getItem(int pos) {
        return spacecrafts.get(pos);
    }

    @Override
    public long getItemId(int pos) {
        return pos;
    }

    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        if(view==null)
        {
            view=LayoutInflater.from(context).inflate(R.layout.model,viewGroup,false);
        }

        TextView nameTxt = view.findViewById(R.id.nameTextView);
        TextView txtPropellant = view.findViewById(R.id.propellantTextView);
        CheckBox chkTechExists = view.findViewById(R.id.myCheckBox);
        ImageView spacecraftImageView = view.findViewById(R.id.spacecraftImageView);

        final Spacecraft thisSpacecraft= spacecrafts.get(position);

        nameTxt.setText(thisSpacecraft.getName());
        //  txtPropellant.setText("Lvl : "+thisSpacecraft.getPropellant());
        txtPropellant.setText("Lvl : "+thisSpacecraft.getlvl());
        chkTechExists.setChecked( thisSpacecraft.getTechnologyExists()==1);
        chkTechExists.setEnabled(false);

        if(thisSpacecraft.getImageURL() != null && thisSpacecraft.getImageURL().length()>0)
        {
            Picasso.get().load(thisSpacecraft.getImageURL()).placeholder(R.drawable.pic).into(spacecraftImageView);
        }else {
            Toast.makeText(context, "Empty Image URL", Toast.LENGTH_LONG).show();
            Picasso.get().load(R.drawable.pic).into(spacecraftImageView);
        }

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //  Toast.makeText(context, "This : " + thisSpacecraft.getName(), Toast.LENGTH_SHORT).show();

                //  Toast.makeText(context, "This : " + thisSpacecraft.getImageURL(), Toast.LENGTH_SHORT).show();

                Intent myIntent = new Intent(Main3Activity.this, Main4Activity.class);

                myIntent.putExtra("Name", thisSpacecraft.getName());
                myIntent.putExtra("Uri", thisSpacecraft.getImageURL());

                myIntent.putExtra("Mobile", thisSpacecraft.getMobile());
                myIntent.putExtra("Lvl", thisSpacecraft.getlvl());

                myIntent.putExtra("Description", thisSpacecraft.getDescription());

                myIntent.putExtra("About", thisSpacecraft.getAbout());

                myIntent.putExtra("Verify", thisSpacecraft.getVerify());

                myIntent.putExtra("User_ID", thisSpacecraft.getId());

                myIntent.putExtra("Username", thisSpacecraft.getusername());

                myIntent.putExtra("Password", thisSpacecraft.getpassword());

                myIntent.putExtra("Username_me", Username_me);

                startActivity(myIntent);

                update();
            }
        });

        return view;
    }
}

  private ListViewAdapter adapter;
private ListView mListView;
ProgressBar myProgressBar;
private int mImageResource;

private void populateListView(List<Spacecraft> spacecraftList) {
    mListView = findViewById(R.id.mListView);

    adapter = new ListViewAdapter(this,spacecraftList);
    mListView.setAdapter(adapter);
}

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

           final ProgressBar myProgressBar= findViewById(R.id.myProgressBar);
    myProgressBar.setIndeterminate(true);
    myProgressBar.setVisibility(View.VISIBLE);

    /*Create handle for the RetrofitInstance interface*/
    MyAPIService myAPIService = RetrofitClientInstance.getRetrofitInstance().create(MyAPIService.class);

    Call<List<Spacecraft>> call = myAPIService.getSpacecrafts();
    call.enqueue(new Callback<List<Spacecraft>>() {

           @Override
        public void onResponse(Call<List<Spacecraft>> call, Response<List<Spacecraft>> response) {
            myProgressBar.setVisibility(View.GONE);
            populateListView(response.body());
        }
        @Override
        public void onFailure(Call<List<Spacecraft>> call, Throwable throwable) {
            myProgressBar.setVisibility(View.GONE);
            //  Toast.makeText(Main3Activity.this, throwable.getMessage(), Toast.LENGTH_LONG).show();
            Toast.makeText(Main3Activity.this, "Check Your Internet Connection", Toast.LENGTH_LONG).show();
        }
    });
}

}


答:
Here is one approach using the tidyverse</p>

```<code>library(tidyverse)

df_example %>%
  group_by(Mouse) %>%
  mutate(max_day = max(Day),
         max_vol = if_else(Day == max(Day),vol,NA_real_)) %>%
  fill(max_vol,.direction = "downup")
</code>```

Title: R/Plyr function for outputting column value based on the maximum value in another column, by group

Body:
I have a data frame with three columns (Mouse, Day, vol). I am trying to use dplyr to create a new dataframe to extract the last "Day"  value for each mouse and the corresponding "vol" for that mouse. I am able to use the max function to get the right "Day" but am having trouble grabbing the matching "vol". Any help is appreciated. Below is my dataframe dput and the code I am trying to assemble.

final_meas <- ddply(df, "Mouse", summarise,
               final_day = max(Day),
               final_vol =
)

If there is a better way to do this please let me know.

Data frame dput()

structure(list(Mouse = c("CF1", "CF2", "CG1", "CG2", "CG3", "CO1",
"CO2", "CU1", "CY1", "CF1", "CF2", "CG1", "CG2", "CG3", "CO1",
"CO2", "CU1", "CY1", "CF1", "CF2", "CG1", "CG2", "CG3", "CO1",
"CO2", "CU1", "CY1", "CF1", "CF2", "CG1", "CG2", "CG3", "CO1",
"CO2", "CF2", "CG1", "CG2", "CG3", "CO1", "CF2", "CG1", "CG2",
"CG3", "CO1", "CF2", "CG1", "CG2", "CG3", "CO1", "CF2", "CG1",
"CG2", "CG3", "CO1", "CF2", "CG1", "CG2", "CG3", "CO1", "CF2",
"CG1", "CG2", "CG3", "CO1"), Day = c(11, 11, 11, 11, 11, 11,
11, 11, 11, 14, 14, 14, 14, 14, 14, 14, 14, 14, 16, 16, 16, 16,
16, 16, 16, 16, 16, 21, 21, 21, 21, 21, 21, 21, 26, 26, 26, 26,
26, 28, 28, 28, 28, 28, 30, 30, 30, 30, 30, 32, 32, 32, 32, 32,
35, 35, 35, 35, 35, 38, 38, 38, 38, 38), vol = c(45.9675, 36.1712655,
87.777976, 14.29754, 14.2842745, 22.989735, 19.3821875, 56.216752,
71.251488, 0.5, 44.6299425, 119.070536, 26.82875, 21.999132,
71.801216, 0.5, 255.874619, 137.720968, 0.5, 21.5552, 115.16616,
33.132848, 17.619264, 51.185368, 0.5, 212.1728, 340.5686, 0,
0.5, 75.154122, 76.0952875, 0.5, 107.208528, 0, 0.5, 63.5839875,
233.4784, 0.5, 74.6727445, 0.5, 55.7932375, 361.3029455, 0, 88.297668,
0.5, 38.0849105, 228.4934, 0.5, 136.778328, 0.5, 0.5, 186.7279545,
0.5, 178.4032435, 0.5, 0, 186.7279545, 0.5, 89.4645, 0.5, 0,
186.7279545, 0.5, 169.296399)), row.names = c(NA, -64L), class = c("tbl_df",
"tbl", "data.frame"))

Body:
Here is one approach using the tidyverse

library(tidyverse)

df_example %>%
  group_by(Mouse) %>%
  mutate(max_day = max(Day),
         max_vol = if_else(Day == max(Day),vol,NA_real_)) %>%
  fill(max_vol,.direction = "downup")


问:
How to add warning text in Drupal comment form
I want a warning message displayed in the comment form when people try to add comments:

"Please write comments in correct
  grammatical English, otherwise they
  will not published"

How can I do it?

答:
Here is how you can do it by using hook_form_alter in your own module:</p>

```<code>function mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case "comment_form":
      $form['#prefix'] .= "<div><p>Show some text before the comment form.</p></div>";
    break;
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is how you can do it by using hook_form_alter in your own module:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case "comment_form":
      $form['#prefix'] .= "<div><p>Show some text before the comment form.</p></div>";
    break;
  }
}


问:
Check Internet Connection vb.net
I am trying to run some vb.net code that indicates if i'm connected to the internet

```<code>If My.Computer.Network.IsAvailable Then
    MsgBox("Computer is connected.")
Else
    MsgBox("Computer is not connected.")
End If
</code>```

This works fine if I'm connecting to a WiFi signal that doesn't require a login. If I connect to a public WiFi signal that I'm required to login/pay and I execute the code before completing this step it still tells me I'm connected (in theory yes but without paying/logging in I'm not)

Any ideas how set this up?

Thanks

答:
```<code>    Try
        Dim client = New Net.WebClient
        client.OpenRead("http://www.google.com")
        Label21.Text = "Internet : Connected"
    Catch
        Label21.Text = "Internet : Disconnected"
    End Try
</code>```

Use this code in vb.net 100% solved, you can use this code form loading.

Title: Check Internet Connection vb.net

Body:
I am trying to run some vb.net code that indicates if i'm connected to the internet

If My.Computer.Network.IsAvailable Then
    MsgBox("Computer is connected.")
Else
    MsgBox("Computer is not connected.")
End If

This works fine if I'm connecting to a WiFi signal that doesn't require a login. If I connect to a public WiFi signal that I'm required to login/pay and I execute the code before completing this step it still tells me I'm connected (in theory yes but without paying/logging in I'm not)

Any ideas how set this up?

Thanks

Body:
    Try
        Dim client = New Net.WebClient
        client.OpenRead("http://www.google.com")
        Label21.Text = "Internet : Connected"
    Catch
        Label21.Text = "Internet : Disconnected"
    End Try

Use this code in vb.net 100% solved, you can use this code form loading.


问:
Hide/unhide rows in an array based on if an entire is blank or zero in the array
I think I found what I need but I do not know what I am missing. I'm getting Runtime code 91 and cant find the object that needs to be defined.

```<code>Sub Hide_UnhideBlanks()

Dim ws As Worksheet
Dim primaryarray As Range
Dim crit1 As Range
Dim cell As Range

Set ws = ThisWorkbook.Sheets("Experience Rating Sheet")
Set primaryarray = ws.Range("B10:M137")
Set crit1 = ws.Range("B10:B137,M10:M137")

Application.ScreenUpdating = False

' unhide all rows before we begin
primaryarray.EntireRow.Hidden = False

For Each cell In primaryarray
    If crit1 Is Nothing Or 0 Then cell.EntireRow.Hidden = True
Next cell

Application.ScreenUpdating = True
End Sub
</code>```

The purpose of this is if crit1 has either 0 or "" to hide all of the rows within primaryarray that have met the criteria described for crit1

Essentially my goal is for the macro to automatically hide the entire row if the array's row is completely empty using crit1 as determining if the row is empty.

答:
Not sure I'm clear what you want but this might be a starting point:</p>

```<code>Sub Hide_UnhideBlanks()

    Dim ws As Worksheet
    Dim primaryarray As Range
    Dim rw As Range

    Set ws = ThisWorkbook.Sheets("Experience Rating Sheet")
    Set primaryarray = ws.Range("B10:M137")

    Application.ScreenUpdating = False

    ' unhide all rows before we begin
    primaryarray.EntireRow.Hidden = False

    For Each rw In primaryarray.Rows
        'not sure if you want Or/And here?
        rw.EntireRow.Hidden = ( BlankOrZero(rw.Cells(1)) Or _
                                BlankOrZero(rw.Cells(12)) )
    Next rw

    Application.ScreenUpdating = True

End Sub

'is cell empty or zero?
Function BlankOrZero(c As Range)
    BlankOrZero = len(c.value)=0 or c.value=0
End function
</code>```

Body:
I think I found what I need but I do not know what I am missing. I'm getting Runtime code 91 and cant find the object that needs to be defined.

Sub Hide_UnhideBlanks()

Dim ws As Worksheet
Dim primaryarray As Range
Dim crit1 As Range
Dim cell As Range

Set ws = ThisWorkbook.Sheets("Experience Rating Sheet")
Set primaryarray = ws.Range("B10:M137")
Set crit1 = ws.Range("B10:B137,M10:M137")

Application.ScreenUpdating = False

' unhide all rows before we begin
primaryarray.EntireRow.Hidden = False

For Each cell In primaryarray
    If crit1 Is Nothing Or 0 Then cell.EntireRow.Hidden = True
Next cell

Application.ScreenUpdating = True
End Sub

The purpose of this is if crit1 has either 0 or "" to hide all of the rows within primaryarray that have met the criteria described for crit1

Essentially my goal is for the macro to automatically hide the entire row if the array's row is completely empty using crit1 as determining if the row is empty.

Body:
Not sure I'm clear what you want but this might be a starting point:

Sub Hide_UnhideBlanks()

    Dim ws As Worksheet
    Dim primaryarray As Range
    Dim rw As Range

    Set ws = ThisWorkbook.Sheets("Experience Rating Sheet")
    Set primaryarray = ws.Range("B10:M137")

    Application.ScreenUpdating = False

    ' unhide all rows before we begin
    primaryarray.EntireRow.Hidden = False

    For Each rw In primaryarray.Rows
        'not sure if you want Or/And here?
        rw.EntireRow.Hidden = ( BlankOrZero(rw.Cells(1)) Or _
                                BlankOrZero(rw.Cells(12)) )
    Next rw

    Application.ScreenUpdating = True

End Sub

'is cell empty or zero?
Function BlankOrZero(c As Range)
    BlankOrZero = len(c.value)=0 or c.value=0
End function


问:
Melting in pandas loses index
I have the following dataframe:

```<code>        Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
Year
2010    9.8 9.8 9.9 9.9 9.6 9.4 9.4 9.5 9.5 9.4 9.8 9.3
2011    9.1 9.0 9.0 9.1 9.0 9.1 9.0 9.0 9.0 8.8 8.6 8.5
2012    8.3 8.3 8.2 8.2 8.2 8.2 8.2 8.1 7.8 7.8 7.7 7.9
</code>```

I want to achieve the following result:

```<code>      Month Values
Year
2010  Jan    9.8
2010  Feb    9.8
2010  Mar    9.9
etc......
</code>```

I tried the method proposed here:
pandas, melt, unmelt preserve index:

```<code>df = pd.melt(df.reset_index(), id_vars='index',value_vars=months)
</code>```

"Months" is a list I created from by getting a list of column names for the months:

```<code>months = df.columns.values.tolist()[1:]
</code>```

However, the result was:

```<code>       index variable  value
   0    NaN   Jan      9.8
   1    NaN   Jan      9.1
   2    NaN   Jan      8.3
   3    NaN   Jan      8.0
   4    NaN   Jan      6.6
</code>```

So, I want to retain the year value as the index. How can I do this?
Thanks.

答:
If you have a good index like that, you can stack:

df.rename_axis('Month', axis='columns').stack().to_frame('Values')
```

The rename_axis method is just some sugar to get the index labels nice.

Title: Melting in pandas loses index

Body:
I have the following dataframe:

        Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
Year
2010    9.8 9.8 9.9 9.9 9.6 9.4 9.4 9.5 9.5 9.4 9.8 9.3
2011    9.1 9.0 9.0 9.1 9.0 9.1 9.0 9.0 9.0 8.8 8.6 8.5
2012    8.3 8.3 8.2 8.2 8.2 8.2 8.2 8.1 7.8 7.8 7.7 7.9

I want to achieve the following result:

      Month Values
Year
2010  Jan    9.8
2010  Feb    9.8
2010  Mar    9.9
etc......

I tried the method proposed here:
pandas, melt, unmelt preserve index:

df = pd.melt(df.reset_index(), id_vars='index',value_vars=months)

"Months" is a list I created from by getting a list of column names for the months:

months = df.columns.values.tolist()[1:]

However, the result was:

       index variable  value
   0    NaN   Jan      9.8
   1    NaN   Jan      9.1
   2    NaN   Jan      8.3
   3    NaN   Jan      8.0
   4    NaN   Jan      6.6

So, I want to retain the year value as the index. How can I do this?
Thanks.

Body:
If you have a good index like that, you can stack:

df.rename_axis('Month', axis='columns').stack().to_frame('Values')

The rename_axis method is just some sugar to get the index labels nice.


问:
Boolean dynamic memory allocation cannot be delete
```<code>include <iostream>
int main()
{
    bool a=new bool;
    delete a;
    return 0;
}
</code>```

I try to delete the boolean malloc, but so far it keeps giving me the error that bool type expression cant be deleted

答:
You can't perform delete on bool, you should delete the pointer instead.

```<code>bool* a=new bool;
delete a;
</code>```

In your code, a is a variable with type bool, it's initialized from the pointer created by new bool, which could convert to bool implicitly; false for null pointer, true for non-null pointer.

Body:
include <iostream>
int main()
{
    bool a=new bool;
    delete a;
    return 0;
}

I try to delete the boolean malloc, but so far it keeps giving me the error that bool type expression cant be deleted

Body:
You can't perform delete on bool, you should delete the pointer instead.

bool* a=new bool;
delete a;

In your code, a is a variable with type bool, it's initialized from the pointer created by new bool, which could convert to bool implicitly; false for null pointer, true for non-null pointer.


问:
Get all first element of tuples from list of lists of tuples in Python
```<code>Input:
orders = [[('Fries', 9)], [('Burger', 6), ('Milkshake', 2), ('Cola', 2)], [('Cola', 2), ('Nuggets', 3), ('Onion Rings', 5)], [('Fries', 9)], [('Big Burger', 7), ('Nuggets', 3)]]

Expected Output:
orders = [['Fries'], ['Burger', 'Milkshare', 'Cola'], ['Cola', 'Nuggets', 'Onion Rings'], ['Fries'], ['Big Burger', 'Nuggets']]
</code>```

My attempt:

```<code> for i, order in enumerate(orders):
        for j,item in enumerate(order):
            orders[i][j] = item[0]
</code>```

Works ok. But are there any more intuitive/one-liner/faster/cooler way to do this?

答:
Here you go:

output = [[item[0] for item in order] for order in orders]
```

Body:
Input:
orders = [[('Fries', 9)], [('Burger', 6), ('Milkshake', 2), ('Cola', 2)], [('Cola', 2), ('Nuggets', 3), ('Onion Rings', 5)], [('Fries', 9)], [('Big Burger', 7), ('Nuggets', 3)]]

Expected Output:
orders = [['Fries'], ['Burger', 'Milkshare', 'Cola'], ['Cola', 'Nuggets', 'Onion Rings'], ['Fries'], ['Big Burger', 'Nuggets']]

My attempt:

 for i, order in enumerate(orders):
        for j,item in enumerate(order):
            orders[i][j] = item[0]

Works ok. But are there any more intuitive/one-liner/faster/cooler way to do this?


问:
Fill down formula till last row in column
I have a formula (I2-J2) in cell K2 and I want Excel to Copy that down till the last row of my data set. So take the formula in K2 and copy it to K3, K4, K5 and so on. Which row is the last row changes dynamically each month based on the data set so I cant use fixed values.

I already tried the other solution in a similar thread: Fill formula down till last row in column but that unfortunately did not work.

```<code>Sub Autofill()
Dim LastRow As Long
LastRow = Range("K" & Rows.Count).End(xlUp).Row
Range("K2:K" & LastRow).Formula = I2 - J2
End Sub
</code>```

The macro already stops in cell K2, which is not the end of my data set and even the formula gives out the wrong result 0 instead of value in I2 minus value in J2

What did I do wrong here?

Many thanks!

答:
This should be what you need:

```<code>Sub AutoPhill()
    Dim N As Long
    N = Cells(Rows.Count, "J").End(xlUp).Row
    Range("K2:K" & N).Formula = "=I2-J2"
End Sub
</code>```

Note the the formula addresses adjust for each row.

Body:
I have a formula (I2-J2) in cell K2 and I want Excel to Copy that down till the last row of my data set. So take the formula in K2 and copy it to K3, K4, K5 and so on. Which row is the last row changes dynamically each month based on the data set so I cant use fixed values.

I already tried the other solution in a similar thread: Fill formula down till last row in column but that unfortunately did not work.

Sub Autofill()
Dim LastRow As Long
LastRow = Range("K" & Rows.Count).End(xlUp).Row
Range("K2:K" & LastRow).Formula = I2 - J2
End Sub

The macro already stops in cell K2, which is not the end of my data set and even the formula gives out the wrong result 0 instead of value in I2 minus value in J2

What did I do wrong here?

Many thanks!

Body:
This should be what you need:

Sub AutoPhill()
    Dim N As Long
    N = Cells(Rows.Count, "J").End(xlUp).Row
    Range("K2:K" & N).Formula = "=I2-J2"
End Sub

Note the the formula addresses adjust for each row.


问:
.NET Regex: Get all matched groups
I've stuck with regex problem using .NET. For example, I have next regex pattern: (?'group1'A|C)|(?'group2'B|C)|(?'group3'A|B|C)

When I do match of "AXYZ" I receive match object which contains Value and Groups; if I go to Groups I'll see that only one group has success in true - group1 (group3 is in false). If I do match of "BXYZ" I'll receive only group2 with success in true (group3 is in false).

How could I receive in match not only one group but all groups satisfying the match?

For example above it should be: group1 & group3 in "AXYZ" and group2 & group3 in "BXYZ".

All above is only example in real system there are different patterns (3+ letters each) and more complicated input text (1000+ words).

答:
The regex engine is eager, which means it will always return the left-most match and stop matching once a match is found. To demonstrate, consider this sample:

```<code>string input = "Hello World";
string pattern = "Hello|Hello World";
Console.WriteLine(Regex.Match(input, pattern).Value);
pattern = "Hello World|Hello";
Console.WriteLine(Regex.Match(input, pattern).Value);
</code>```

In your case group1 is matched first, so all other groups will not match and return false. Also, you claim that "BXYZ" returns group2, but this can't be right. Both "AXYZ" and "BXYZ" get matched by group1: (?'group1'A|B). If you have a need to test each group you'll need to do so using a separate regex.

Title: .NET Regex: Get all matched groups

Body:
The regex engine is eager, which means it will always return the left-most match and stop matching once a match is found. To demonstrate, consider this sample:

string input = "Hello World";
string pattern = "Hello|Hello World";
Console.WriteLine(Regex.Match(input, pattern).Value);
pattern = "Hello World|Hello";
Console.WriteLine(Regex.Match(input, pattern).Value);

In your case group1 is matched first, so all other groups will not match and return false. Also, you claim that "BXYZ" returns group2, but this can't be right. Both "AXYZ" and "BXYZ" get matched by group1: (?'group1'A|B). If you have a need to test each group you'll need to do so using a separate regex.


问:
Vue js cannot splice item from nested v-for
I'm starting with Vue.js and I read about splice() according to item id/index. It works fine if I try to splice() an item in "tours" v-for:

```<code>data:{
   tours: null,
},
methods: {
  deleteTour: function (id) {
    if (confirm('Are you sure?')) {
        const index = this.tours.findIndex(item => item.id === id);
      if (~index) {
         axios.post('deleteTour.php', { "token": token, "tourID": id }).then((response) => {
           this.deleted = response;
           console.log(this.deleted);

           // splice tour
           this.tours.splice(index, 1);
         }).catch((error) => {
           this.errored = error;
           console.log(this.errored);
         });
       }
    }
  },
}
</code>```

html

```<code><div id="app" class="row mb-50">
   <div v-for="(item, index) in tours" v-bind:key="item.id" id="tours" class="col-md-12 mb-30">
      <ul class="pics-list">
         <li v-for="(image, index) in item.images" ref="deleteItem" :class="{marginRightOpen: editingTour}">
            <span :hidden="editingTour !== item.id" class="badge" @click="deleteImage(image.imageID, item.id, index)">
            <i class="fa fa-fw fa-times-circle"></i>
            </span>
            <div class="pics-list-image-container img-fluid cursor-pointer" v-bind:style="{'background-image': 'url(http://localhost/tours/'+image.image + ')' }" @click="openModal = true, showModal(image.image)">
            </div>
         </li>
         <li v-if="urls && editingTour == item.id" v-for="(url, key) in urls" :key="key">
            <div id="preview" :ref="'url'" class="pics-list-image-container img-fluid">
            </div>
         </li>
      </ul>
   </div>
</div>
</code>```

But I'm not able to splice() a list item within a nested v-for. I tried using ref in many ways but it didn't work.

```<code>deleteImage: function (id, tourID, index) {
   if (confirm('Are you sure?')) {

      // it could be done here
      this.$refs.deleteItem.splice(index, 1);

      axios.post('deleteImage.php', { "token": token, "tourID": tourID, "imageID": id })
           .then((response) => {
               console.log(response);

               // or here
               this.$refs.deleteItem.splice(index, 1);
        }).catch((error) => {
               this.errored = error;
               console.log(this.errored);
        });
      }
},
</code>```

I want to remove the whole first list item that contains the badge icon. Is it possible to do that?

答:
If we use different variable names for the v-for indexes in the template, we can reference these difference indexes in deleteImage:

```<code><div id="app" class="row mb-50">
   <div v-for="(item, indexItem) in tours" v-bind:key="item.id" id="tours" class="col-md-12 mb-30">
      <ul class="pics-list">
         <li v-for="(image, indexImage) in item.images" ref="deleteItem" :class="{marginRightOpen: editingTour}">
            <span :hidden="editingTour !== item.id" class="badge" @click="deleteImage(image.imageID, item.id, indexItem, indexImage)">
            <i class="fa fa-fw fa-times-circle"></i>
            </span>
            <div class="pics-list-image-container img-fluid cursor-pointer" v-bind:style="{'background-image': 'url(http://localhost/tours/'+image.image + ')' }" @click="openModal = true, showModal(image.image)">
            </div>
         </li>
         <li v-if="urls && editingTour == item.id" v-for="(url, key) in urls" :key="key">
            <div id="preview" :ref="'url'" class="pics-list-image-container img-fluid">
            </div>
         </li>
      </ul>
   </div>
</div>
</code>```

Then in deleteImage:

```<code>deleteImage: function (id, tourID, indexItem, indexImage) {
   if (confirm('Are you sure?')) {

      // it could be done here
      // this.$refs.deleteItem.splice(index, 1);
      this.tours[indexItem].images.splice(indexImage,1)

      axios.post('deleteImage.php', { "token": token, "tourID": tourID, "imageID": id })
           .then((response) => {
               console.log(response);

               // or here
               this.$refs.deleteItem.splice(index, 1);
        }).catch((error) => {
               this.errored = error;
               console.log(this.errored);
        });
      }
},
</code>```

In general, $refs are not an ideal solution as per the Vue documentation:

$refs are only populated after the component has been rendered, and they are not reactive. It is only meant as an escape hatch for direct child manipulation - you should avoid accessing $refs from within templates or computed properties.

Body:
I'm starting with Vue.js and I read about splice() according to item id/index. It works fine if I try to splice() an item in "tours" v-for:

data:{
   tours: null,
},
methods: {
  deleteTour: function (id) {
    if (confirm('Are you sure?')) {
        const index = this.tours.findIndex(item => item.id === id);
      if (~index) {
         axios.post('deleteTour.php', { "token": token, "tourID": id }).then((response) => {
           this.deleted = response;
           console.log(this.deleted);

           // splice tour
           this.tours.splice(index, 1);
         }).catch((error) => {
           this.errored = error;
           console.log(this.errored);
         });
       }
    }
  },
}

html

But I'm not able to splice() a list item within a nested v-for. I tried using ref in many ways but it didn't work.

deleteImage: function (id, tourID, index) {
   if (confirm('Are you sure?')) {

      // it could be done here
      this.$refs.deleteItem.splice(index, 1);

      axios.post('deleteImage.php', { "token": token, "tourID": tourID, "imageID": id })
           .then((response) => {
               console.log(response);

               // or here
               this.$refs.deleteItem.splice(index, 1);
        }).catch((error) => {
               this.errored = error;
               console.log(this.errored);
        });
      }
},

I want to remove the whole first list item that contains the badge icon. Is it possible to do that?

Body:
If we use different variable names for the v-for indexes in the template, we can reference these difference indexes in deleteImage:

<div id="app" class="row mb-50">
   <div v-for="(item, indexItem) in tours" v-bind:key="item.id" id="tours" class="col-md-12 mb-30">
      <ul class="pics-list">
         <li v-for="(image, indexImage) in item.images" ref="deleteItem" :class="{marginRightOpen: editingTour}">
            <span :hidden="editingTour !== item.id" class="badge" @click="deleteImage(image.imageID, item.id, indexItem, indexImage)">
            <i class="fa fa-fw fa-times-circle"></i>
            </span>
            <div class="pics-list-image-container img-fluid cursor-pointer" v-bind:style="{'background-image': 'url(http://localhost/tours/'+image.image + ')' }" @click="openModal = true, showModal(image.image)">
            </div>
         </li>
         <li v-if="urls && editingTour == item.id" v-for="(url, key) in urls" :key="key">
            <div id="preview" :ref="'url'" class="pics-list-image-container img-fluid">
            </div>
         </li>
      </ul>
   </div>
</div>

Then in deleteImage:

deleteImage: function (id, tourID, indexItem, indexImage) {
   if (confirm('Are you sure?')) {

      // it could be done here
      // this.$refs.deleteItem.splice(index, 1);
      this.tours[indexItem].images.splice(indexImage,1)

      axios.post('deleteImage.php', { "token": token, "tourID": tourID, "imageID": id })
           .then((response) => {
               console.log(response);

               // or here
               this.$refs.deleteItem.splice(index, 1);
        }).catch((error) => {
               this.errored = error;
               console.log(this.errored);
        });
      }
},

In general, $refs are not an ideal solution as per the Vue documentation:

$refs are only populated after the component has been rendered, and they are not reactive. It is only meant as an escape hatch for direct child manipulation - you should avoid accessing $refs from within templates or computed properties.


问:
spring-context and spring-web 4.2.4.RELEASE
Why I need to include spring-context in my new spring boot project to work ?

I have this in my pom.xml

```<code> <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
  </dependency>
  <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
  </dependency>
</code>```

I can see inside spring-web dependency, the dependency spring-context

if I remove spring-context from my pom.xml, the application does not run.

Below is the error I get :

```<code>Exception encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'nameOfController'
</code>```

答:
When we go through the compile dependencies of spring-web , then spring-context is not included in the latest-version.

https://frontbackend.com/maven/artifact/org.springframework/spring-web/5.2.6.RELEASE

Though it was present in the previous versions.

https://frontbackend.com/maven/artifact/org.springframework/spring-web/4.3.20.RELEASE

Since, I cannot see the specific version that you'r adding to your pom.xml file, I am assuming it is getting the latest version, where the dependency of spring-context is not included in spring-web.

Also, the error stack trace that you have provided is very less and generic in nature, so it becomes difficult to debug your problem further, though I think it is a problem with version.

You can give the specific version in this way :

```<code><dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>5.2.6.RELEASE</version>
</dependency>
</code>```

Body:
Why I need to include spring-context in my new spring boot project to work ?

I have this in my pom.xml

 <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
  </dependency>
  <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
  </dependency>

I can see inside spring-web dependency, the dependency spring-context

if I remove spring-context from my pom.xml, the application does not run.

Below is the error I get :

Exception encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'nameOfController'

Body:
When we go through the compile dependencies of spring-web , then spring-context is not included in the latest-version.

https://frontbackend.com/maven/artifact/org.springframework/spring-web/5.2.6.RELEASE

Though it was present in the previous versions.

https://frontbackend.com/maven/artifact/org.springframework/spring-web/4.3.20.RELEASE

Since, I cannot see the specific version that you'r adding to your pom.xml file, I am assuming it is getting the latest version, where the dependency of spring-context is not included in spring-web.

Also, the error stack trace that you have provided is very less and generic in nature, so it becomes difficult to debug your problem further, though I think it is a problem with version.

You can give the specific version in this way :

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>5.2.6.RELEASE</version>
</dependency>


问:
Create a sub-cube in SSAS Tabular
I have an SSAS Tabular Cube, which I refresh daily. It's big and not efficient for some use-cases. I want to create a sub-cube with filtered data and deploy it as a separate cube. How should I do it?

One idea I have is to extract a sub-cube with MDX and store it in a new cube (and automate in SSIS Package). Is it possible? Can someone explain how to do it?

答:
Ok, that's a tricky spot.  Cubes aren't really designed to work so that you could create a subset out from another one. I mean, you can do that, but that's not what they are there for. You'd just have to create some DAX or MDX queries, which provides the data you need OR you can use M Query language to get the data.

If you'd like to use DAX, you can use SSIS Analysis Services Connector and Execute SQL -task for that purpose. If you don't have experience with DAX, you can use tools like Excel and import the data to a Power Pivot table. There you can drag and drop the fields you want and then get the underline DAX query with SQL Profiler (set up a pofiler session and click refresh in Excel to get the query).

For M Queries, it might be best to use Excel or Power BI Desktop and it's Power Query editor for designing the the output and then copy the M Query made by the editor. Then you can use the query and SSIS Power Query Source to get the data.

If you have an Enterprise edition SQL Server, you might consider partitions to speed up the processing of the cube.

Another way would be to limit the amount of data to secondary cubes (only the current quarter / one country / one department / etc). I'm a fan of one cube one - one data area -type design. So I'd still suggest that you take a copy / multiple copies of your current cube project and make them be more specific to one specific area (for example in finance-cube, we might not need HR data).

Title: Create a sub-cube in SSAS Tabular


问:
Error: "TypeError: hidden_tag() missing 1 required positional argument: 'self' " in Flask, python
I've been creating a forum based learning system, similar to stack overflow for an assessed project.  I'm fairly new to flask, however I believe i have a decent understanding of python.  I have been following Corey Schafer's Flask tutorials and adapting them to my project.  Whenever I try to access the page called 'adduser', a webpage with a form for adding users, I get the error:

"TypeError: hidden_tag() missing 1 required positional argument: 'self'".

I have no idea what this means or how to even attempt to fix it.
I assumed that I might find the fix in the HTML for the 'adduser' page, and after removing the '{{ form.hidden_tag() }}' tag, I got a different error, which leads me to believe that the error is has something to do with the 'forms.py' file and the 'addUser.html' file.

forms.py

```<code>from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField
from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError
from itroom.models import User

class LoginForm(FlaskForm):
    email = StringField('Email',validators=[DataRequired(), Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    remember = BooleanField('Remember Me')
    submit = SubmitField('Login')

class AddUserForm(FlaskForm):
    email = StringField('Email',validators=[DataRequired(), Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    submit = SubmitField('Add User')

    def validate_email(self,email):
        user = User.query.filter_by(userEmail=email.data).first()
        if user:
            raise ValidationError('Email already exists in database.')
</code>```

addUser.html

```<code>{% extends "template.html" %}
{% block content %}

  <div class="center2" style="border-color: white;">
  <h2 align="center" style="padding: 2.5%;"></h2>
    <h1>Add a User</h1>
      <form method="POST" action="">
         {{ form.hidden_tag() }}
        <div class="form-group">
          {{form.email.label}}
          {% if form.email.errors %}
          {{form.email(size=30, class="form-control is-invalid")}}
        <div class="invalid-feedback">
          {% for error in form.email.errors %}
          <span>{{ error }}</span>
          {% endfor %}
        </div>
          {% else %}
          {{form.email(size=30, class="form-control")}}
          {% endif %}
        </div>
          {{form.password.label}} <br>
          {{form.password(size=30)}}

          {{form.submit(class="btn btn-outline-info")}} <br>

      </form>
      </div>
{% endblock content %}
</code>```

I also thought the routes file may be helpful aswell.

routes.py

```<code>from flask import Flask, render_template, url_for, flash, redirect
from itroom import app, db, bcrypt
from itroom.forms import LoginForm, AddUserForm
from itroom.models import User, Post
from flask_login import login_user

@app.route("/")
@app.route("/home")     #defines the HTML loaded for /home
def home():
    return render_template('home.html', title='Home')

@app.route("/login", methods=['GET', 'POST'])       #defines the HTML loaded for /login
def login():
    form = LoginForm('')
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.userEmail.data).first()
        if user and bcrypt.check_password_hash(user.userPassword, form.password):
            login_user(user, remember=form.remember.data)
            return redirect(url_for('home'))
        else:
            flash('Login Unsucessful, Please check email and password')
    return render_template('login.html',form=form, title='Login')

@app.route("/adduser", methods=['GET', 'POST'])       #defines the HTML loaded for /adduser
def addUser():
    form = AddUserForm('/login')
    if form.validate_on_submit():
        hashed_password = bcrypt.generate_password_hash(form.password.data).decode ('utf-8')
        user = User(userEmail=form.email.data, userPassword = hashed_password)
        db.session.add(user)
        db.session.commit()
        temptext = ("Account created for '", form.email.data, "'." )
        flash(temptext)

    else:
        flash('Account not created')
    return render_template('addUser.html', title='Admin', form=AddUserForm)
</code>```

Thank you in advance for anyone who tries to help!

答:
You forgot to call the form at the end of your last return statement.

current code

```<code>else:
    flash('Account not created')
return render_template('addUser.html', title='Admin', form=AddUserForm)
</code>```

fixed code

```<code>else:
    flash('Account not created')
return render_template('addUser.html', title='Admin', form=AddUserForm())
</code>```

or since you already specified that

```<code>form = AddUserForm('/login')
</code>```

just specify it at the end like you did in other routes

```<code>return render_template('addUser.html', title='Admin', form=form)
</code>```

Body:
I've been creating a forum based learning system, similar to stack overflow for an assessed project.  I'm fairly new to flask, however I believe i have a decent understanding of python.  I have been following Corey Schafer's Flask tutorials and adapting them to my project.  Whenever I try to access the page called 'adduser', a webpage with a form for adding users, I get the error:

"TypeError: hidden_tag() missing 1 required positional argument: 'self'".

I have no idea what this means or how to even attempt to fix it.
I assumed that I might find the fix in the HTML for the 'adduser' page, and after removing the '{{ form.hidden_tag() }}' tag, I got a different error, which leads me to believe that the error is has something to do with the 'forms.py' file and the 'addUser.html' file.

forms.py

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField
from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError
from itroom.models import User

class LoginForm(FlaskForm):
    email = StringField('Email',validators=[DataRequired(), Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    remember = BooleanField('Remember Me')
    submit = SubmitField('Login')

class AddUserForm(FlaskForm):
    email = StringField('Email',validators=[DataRequired(), Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    submit = SubmitField('Add User')

    def validate_email(self,email):
        user = User.query.filter_by(userEmail=email.data).first()
        if user:
            raise ValidationError('Email already exists in database.')

addUser.html

{% extends "template.html" %}
{% block content %}

Add a User

      <form method="POST" action="">
         {{ form.hidden_tag() }}

          {{form.email.label}}
          {% if form.email.errors %}
          {{form.email(size=30, class="form-control is-invalid")}}

          {% for error in form.email.errors %}
          {{ error }}
          {% endfor %}

          {% else %}
          {{form.email(size=30, class="form-control")}}
          {% endif %}

          {{form.password.label}}

          {{form.password(size=30)}}

          {{form.submit(class="btn btn-outline-info")}}

      </form>

{% endblock content %}

I also thought the routes file may be helpful aswell.

routes.py

from flask import Flask, render_template, url_for, flash, redirect
from itroom import app, db, bcrypt
from itroom.forms import LoginForm, AddUserForm
from itroom.models import User, Post
from flask_login import login_user

@app.route("/")
@app.route("/home")     #defines the HTML loaded for /home
def home():
    return render_template('home.html', title='Home')

@app.route("/login", methods=['GET', 'POST'])       #defines the HTML loaded for /login
def login():
    form = LoginForm('')
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.userEmail.data).first()
        if user and bcrypt.check_password_hash(user.userPassword, form.password):
            login_user(user, remember=form.remember.data)
            return redirect(url_for('home'))
        else:
            flash('Login Unsucessful, Please check email and password')
    return render_template('login.html',form=form, title='Login')

@app.route("/adduser", methods=['GET', 'POST'])       #defines the HTML loaded for /adduser
def addUser():
    form = AddUserForm('/login')
    if form.validate_on_submit():
        hashed_password = bcrypt.generate_password_hash(form.password.data).decode ('utf-8')
        user = User(userEmail=form.email.data, userPassword = hashed_password)
        db.session.add(user)
        db.session.commit()
        temptext = ("Account created for '", form.email.data, "'." )
        flash(temptext)

    else:
        flash('Account not created')
    return render_template('addUser.html', title='Admin', form=AddUserForm)

Thank you in advance for anyone who tries to help!

Body:
You forgot to call the form at the end of your last return statement.

current code

else:
    flash('Account not created')
return render_template('addUser.html', title='Admin', form=AddUserForm)

fixed code

else:
    flash('Account not created')
return render_template('addUser.html', title='Admin', form=AddUserForm())

or since you already specified that

form = AddUserForm('/login')

just specify it at the end like you did in other routes

return render_template('addUser.html', title='Admin', form=form)


问:
Trying to list intune devices through deviceCompliancePolicySettingStateSummaries
I am trying to retrieve a list of enrolled devices using the microsoft graph api. The authenticated GET request to https://graph.microsoft.com/v1.0/deviceManagement/deviceCompliancePolicySettingStateSummaries

```<code>{
  "error": {
    "code": "UnknownError",
    "message": "{\"ErrorCode\":\"Forbidden\",\"Message\":\"{\\r\\n  \\\"_version\\\": 3,\\r\\n  \\\"Message\\\": \\\"An error has occurred - Operation ID (for customer support): 00000000-0000-0000-0000-000000000000 - Activity ID: dd0e2f48-90b3-49e0-bb9a-b3b02e4b9482 - Url: https://fef.msua08.manage.microsoft.com/DeviceConfiguration_2005/StatelessDeviceConfigurationFEService/deviceManagement/deviceCompliancePolicySettingStateSummaries?api-version=2020-02-21\\\",\\r\\n  \\\"CustomApiErrorPhrase\\\": \\\"\\\",\\r\\n  \\\"RetryAfter\\\": null,\\r\\n  \\\"ErrorSourceService\\\": \\\"\\\",\\r\\n  \\\"HttpHeaders\\\": \\\"{\\\\\\\"WWW-Authenticate\\\\\\\":\\\\\\\"Bearer realm=\\\\\\\\\\\\\\\"urn:intune:service,bb7003b9-cb7f-44b2-b534-54f84f2f0d63,f0f3c450-59bf-4f0d-b1b2-0ef84ddfe3c7\\\\\\\\\\\\\\\"\\\\\\\"}\\\"\\r\\n}\",\"Target\":null,\"Details\":null,\"InnerError\":null,\"InstanceAnnotations\":[]}",
    "innerError": {
      "request-id": "dd0e2f48-90b3-49e0-bb9a-b3b02e4b9482",
      "date": "2020-05-28T11:34:16"
    }
  }
}
</code>```

I am following the documentation here.

答: We just needed to add these resource permissions DeviceManagementConfiguration.ReadWrite.All and DeviceManagementConfiguration.Read.All in Azure AD permissions.

Body:
I am trying to retrieve a list of enrolled devices using the microsoft graph api. The authenticated GET request to https://graph.microsoft.com/v1.0/deviceManagement/deviceCompliancePolicySettingStateSummaries

{
  "error": {
    "code": "UnknownError",
    "message": "{\"ErrorCode\":\"Forbidden\",\"Message\":\"{\\r\\n  \\\"_version\\\": 3,\\r\\n  \\\"Message\\\": \\\"An error has occurred - Operation ID (for customer support): 00000000-0000-0000-0000-000000000000 - Activity ID: dd0e2f48-90b3-49e0-bb9a-b3b02e4b9482 - Url: https://fef.msua08.manage.microsoft.com/DeviceConfiguration_2005/StatelessDeviceConfigurationFEService/deviceManagement/deviceCompliancePolicySettingStateSummaries?api-version=2020-02-21\\\",\\r\\n  \\\"CustomApiErrorPhrase\\\": \\\"\\\",\\r\\n  \\\"RetryAfter\\\": null,\\r\\n  \\\"ErrorSourceService\\\": \\\"\\\",\\r\\n  \\\"HttpHeaders\\\": \\\"{\\\\\\\"WWW-Authenticate\\\\\\\":\\\\\\\"Bearer realm=\\\\\\\\\\\\\\\"urn:intune:service,bb7003b9-cb7f-44b2-b534-54f84f2f0d63,f0f3c450-59bf-4f0d-b1b2-0ef84ddfe3c7\\\\\\\\\\\\\\\"\\\\\\\"}\\\"\\r\\n}\",\"Target\":null,\"Details\":null,\"InnerError\":null,\"InstanceAnnotations\":[]}",
    "innerError": {
      "request-id": "dd0e2f48-90b3-49e0-bb9a-b3b02e4b9482",
      "date": "2020-05-28T11:34:16"
    }
  }
}

I am following the documentation here.


问:
How to model and create a custom deck of cards in rails?
I'm trying to model a card game in order to learn Rails. This is different than a standard deck of playing cards in that there can be multiple copies of a card in the deck. I'm running into problems while trying to initialize the deck. So far I've got a basic Card model with various attributes (such as copies_in_deck) but no associations. A DeckCard model which represents the cards in the deck (this is due to having multiples of the same card in the deck):

```<code>class DeckCard < ActiveRecord::Base
  belongs_to :card
  belongs_to :deck
end
</code>```

These DeckCards will eventually have attributes reflecting position; such as in discard pile, in draw pile, etc.

A Deck model with

```<code>belongs_to :game
has_many :deck_cards
</code>```

I'm trying to inialize the deck and am having various problems. I'm trying the following in Deck

```<code>def initialize
  @cards = Card.find(:all)
  @cards.each do |card|
    # eventually another loop here on copies_in_deck
      @deck_cards.build(card)
  end
end
</code>```

When I do Deck.new I get an error on nil.build.  Why is @deck_cards nil?

I'm using InstantRails2, which has rails 2.0.2. I found this article  about creating multiple models in one action, so I tried using Deck.create! instead, and got an error about the wrong number of arguments.

Any suggestions?

答:
Don't use #initialize on objects that inherit from ActiveRecord::Base.  It'll break all sorts of internal Rails magic.  Instead, use the #after_initialize callback documented here: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

Note that after_initialize is called after finds as well as on newly created objects, so you'll want to wrap your initialization code to make sure that the object hasn't been saved previously (use #new_record?):

```<code>def after_initialize
  if new_record?
    # initialize deck_cards here.
  end
end
</code>```

In the past, I've taken this alternate approach with a nicer syntax, but be warned that it doesn't kick in until you try to save or validate the record.

```<code>before_validation :build_default_associations, :if => :new_record?

def build_default_associations
  # initialize default associations here.
end
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to model a card game in order to learn Rails. This is different than a standard deck of playing cards in that there can be multiple copies of a card in the deck. I'm running into problems while trying to initialize the deck. So far I've got a basic Card model with various attributes (such as copies_in_deck) but no associations. A DeckCard model which represents the cards in the deck (this is due to having multiples of the same card in the deck):

class DeckCard < ActiveRecord::Base
  belongs_to :card
  belongs_to :deck
end

These DeckCards will eventually have attributes reflecting position; such as in discard pile, in draw pile, etc.

A Deck model with

belongs_to :game
has_many :deck_cards

I'm trying to inialize the deck and am having various problems. I'm trying the following in Deck

def initialize
  @cards = Card.find(:all)
  @cards.each do |card|
    # eventually another loop here on copies_in_deck
      @deck_cards.build(card)
  end
end

When I do Deck.new I get an error on nil.build.  Why is @deck_cards nil?

I'm using InstantRails2, which has rails 2.0.2. I found this article  about creating multiple models in one action, so I tried using Deck.create! instead, and got an error about the wrong number of arguments.

Any suggestions?

Body:
Don't use #initialize on objects that inherit from ActiveRecord::Base.  It'll break all sorts of internal Rails magic.  Instead, use the #after_initialize callback documented here: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

Note that after_initialize is called after finds as well as on newly created objects, so you'll want to wrap your initialization code to make sure that the object hasn't been saved previously (use #new_record?):

def after_initialize
  if new_record?
    # initialize deck_cards here.
  end
end

In the past, I've taken this alternate approach with a nicer syntax, but be warned that it doesn't kick in until you try to save or validate the record.

before_validation :build_default_associations, :if => :new_record?

def build_default_associations
  # initialize default associations here.
end


问:
Regex to replace %variables%
I've been yanking clumps of hair out for 30 minutes doing this one...

I have a dictionary, like so:

```<code>{'search': 'replace',
 'foo':    'bar'}
</code>```

And a string like this:

```<code>Foo bar %foo% % search %.
</code>```

I'd like to replace each variable with it's equivalent text from the dictionary:

```<code>Foo bar bar replace.
</code>```

My current regex fails, so here it is (key and value are from dictionary.items()):

```<code> re.sub(r'%\d+' + key + '[^%]\d+%', value, text)
</code>```

Any help would be appreciated, as this regex stuff is driving me nuts...

答:
If you want it in one statement, you could do the following (assuming s is the string and d is the dictionary):

```<code>re.sub(r"[%]\s*[^%]+\s*[%]",lambda k:d.get(k[1,-1].strip(),k),s)
</code>```

This uses a function in the replacement part to get each value from the dictionary, and ignores if it is not in the dictionary.

Edit: fixed bug with unwanted whitespace appearing in lookup key

Title: Regex to replace %variables%

Body:
I've been yanking clumps of hair out for 30 minutes doing this one...

I have a dictionary, like so:

{'search': 'replace',
 'foo':    'bar'}

And a string like this:

Foo bar %foo% % search %.

I'd like to replace each variable with it's equivalent text from the dictionary:

Foo bar bar replace.

My current regex fails, so here it is (key and value are from dictionary.items()):

 re.sub(r'%\d+' + key + '[^%]\d+%', value, text)

Any help would be appreciated, as this regex stuff is driving me nuts...

Body:
If you want it in one statement, you could do the following (assuming s is the string and d is the dictionary):

re.sub(r"[%]\s*[^%]+\s*[%]",lambda k:d.get(k[1,-1].strip(),k),s)

This uses a function in the replacement part to get each value from the dictionary, and ignores if it is not in the dictionary.

Edit: fixed bug with unwanted whitespace appearing in lookup key


问:
Copy vector of shared_ptr to derived classes of abstract base
I'm trying to copy the object instances of derived classes from a vector<shared_ptr<base>> to a new vector<shared_ptr<base>> where the base class is abstract. I want the new vector to contain shared_ptr to copies of the objects, not the original objects.

I've tried this:

class base
{
public:
    base(){}
    virtual void method() = 0;
};

class derived1 : public base
{
public:
    derived1() : base() { };
    void method() {};
};

class derived2 : public base
{
public:
    derived2() : base() { };
    void method() {};
};

int main()
{
    std::vector<std::shared_ptr<base>> vector1 =
    {
        std::make_shared<derived1>(),
        std::make_shared<derived2>()
    };

    std::vector<std::shared_ptr<base>> vector2;
    vector2.reserve(vector1.size());
    for (const auto& e : vector1)
    {
        vector2.push_back(std::make_shared<base>(*e));
    }
}
```

This is not working, since I'm not able to instantiate the base class. How can I do this properly?

答:
One way to solve this is to make a pure virtual clone method on the base class which returns a pointer - subclasses override this to allocate a copy of themselves.</p>

```<code>class base
{
public:
    virtual std::shared_ptr<base> clone() const = 0;
};

class derived1 : public base
{
public:
    virtual std::shared_ptr<base> clone() const override
    {
        return std::shared_ptr<base>(new derived1(*this));
    }
};
</code>```

Body:
I'm trying to copy the object instances of derived classes from a vector<shared_ptr<base>> to a new vector<shared_ptr<base>> where the base class is abstract. I want the new vector to contain shared_ptr to copies of the objects, not the original objects.

I've tried this:

class base
{
public:
    base(){}
    virtual void method() = 0;
};

class derived1 : public base
{
public:
    derived1() : base() { };
    void method() {};
};

class derived2 : public base
{
public:
    derived2() : base() { };
    void method() {};
};

int main()
{
    std::vector<std::shared_ptr<base>> vector1 =
    {
        std::make_shared<derived1>(),
        std::make_shared<derived2>()
    };

    std::vector<std::shared_ptr<base>> vector2;
    vector2.reserve(vector1.size());
    for (const auto& e : vector1)
    {
        vector2.push_back(std::make_shared<base>(*e));
    }
}

This is not working, since I'm not able to instantiate the base class. How can I do this properly?

Body:
One way to solve this is to make a pure virtual clone method on the base class which returns a pointer - subclasses override this to allocate a copy of themselves.

class base
{
public:
    virtual std::shared_ptr<base> clone() const = 0;
};

class derived1 : public base
{
public:
    virtual std::shared_ptr<base> clone() const override
    {
        return std::shared_ptr<base>(new derived1(*this));
    }
};


问:
Set a timeout for database connection with Doctrine
Is it somehow possible to set a connection timeout in Doctrine (for MySQL)?

I would like to set a 5 sec. timeout for my connections.

答:
You'll need to specify the driver option for connection timeouts in your services.yaml configuration for doctrine dbal (seeing your symfony tag).

If you're using mysqli extension:

doctrine:
  dbal:
    ...
    options:
        0: 5 // '0' is the value of 'MYSQLI_OPT_CONNECT_TIMEOUT'
```

<p>For PDO-based drivers:</p>

<pre class="lang-yaml prettyprint-override"><code>doctrine:
  dbal:
    ...
    options:
        2: 5 // '2' is the value of 'PDO::ATTR_TIMEOUT'
</code>```

References:

https://symfony.com/doc/master/reference/configuration/doctrine.html#doctrine-dbal-configuration

https://www.doctrine-project.org/projects/doctrine-dbal/en/2.10/reference/configuration.html

https://www.php.net/manual/en/mysqli.options.php

https://www.php.net/manual/en/pdo.constants.php#pdo.constants.attr-timeout

Body:
You'll need to specify the driver option for connection timeouts in your services.yaml configuration for doctrine dbal (seeing your symfony tag).

If you're using mysqli extension:

doctrine:
  dbal:
    ...
    options:
        0: 5 // '0' is the value of 'MYSQLI_OPT_CONNECT_TIMEOUT'

For PDO-based drivers:

doctrine:
  dbal:
    ...
    options:
        2: 5 // '2' is the value of 'PDO::ATTR_TIMEOUT'

References:

https://symfony.com/doc/master/reference/configuration/doctrine.html#doctrine-dbal-configuration

https://www.doctrine-project.org/projects/doctrine-dbal/en/2.10/reference/configuration.html

https://www.php.net/manual/en/mysqli.options.php

https://www.php.net/manual/en/pdo.constants.php#pdo.constants.attr-timeout


问:
Indexing error in plot for pandas version >= 0.20
I want to use the code from this answer, as it does exactly what I want. I paste it here for the completeness of my question:

```<code>out = pd.cut(s, bins=[0, 0.35, 0.7, 1], include_lowest=True)
out_norm = out.value_counts(sort=False, normalize=True).mul(100)
ax = out_norm.plot.bar(rot=0, color="b", figsize=(6,4))
ax.set_xticklabels([c[1:-1].replace(","," to") for c in out.cat.categories])
plt.ylabel("pct")
plt.show()
</code>```

I get an error pointing at the ax.set_xticklabels line, stating that:

```<code>TypeError: 'pandas._libs.interval.Interval' object is not subscriptable.
</code>```

I understand this has been changed after pandas version 0.20. How can I modify that line to do the same thing but avoid the error?

答:
You can make the Interval object subscriptable by calling str() on it:

```<code>ax.set_xticklabels([str(c)[1:-1].replace(","," to") for c in out.cat.categories])
</code>```

Body:
I want to use the code from this answer, as it does exactly what I want. I paste it here for the completeness of my question:

out = pd.cut(s, bins=[0, 0.35, 0.7, 1], include_lowest=True)
out_norm = out.value_counts(sort=False, normalize=True).mul(100)
ax = out_norm.plot.bar(rot=0, color="b", figsize=(6,4))
ax.set_xticklabels([c[1:-1].replace(","," to") for c in out.cat.categories])
plt.ylabel("pct")
plt.show()

I get an error pointing at the ax.set_xticklabels line, stating that:

TypeError: 'pandas._libs.interval.Interval' object is not subscriptable.

I understand this has been changed after pandas version 0.20. How can I modify that line to do the same thing but avoid the error?

Body:
You can make the Interval object subscriptable by calling str() on it:

ax.set_xticklabels([str(c)[1:-1].replace(","," to") for c in out.cat.categories])


问:
Recover blobs which are falsely line-ending converted with git
I have a history in git, where in a commit A we have a .gitattributes files with

```<code>* text eol=lf
</code>```

which is clearly wrong because it will convert all paths to LF even binaries before checkin.
So that happend and I am wondering if a binary file/blob F in the history is corrupt (because of crlf got converted to lf) can be restored such that the conversion is undone.

If that procedure is applicable I would apply it in a git filter-branch somehow...

PS: I made a new history with a corrected .gitattribute file everywhere on master

```<code>* text=auto eol=lf
</code>```

made a new orphan branch new-master and rebased the whole master onto it. But that does not solve the problem, the file/blobs are left of course corrupt...

答:
If the data stored in the Git repository are not the data you meant to store, no Git command is going to be able to find the data that you did mean to store.

In other words: no, there is no way to get the correct data from the wrong data.  If you have the correct data somewhere, that's where you get the correct data.

All that git filter-branch (or the new and improved git filter-repo) can do is copy each original commit with some set of filters applied as it goes.  The existing original commit, with its original snapshot, remains in the repository for a while; the new commit, with its new snapshot, is the one that you'll find when using the updated branch name(s) to find commits.

Body:
I have a history in git, where in a commit A we have a .gitattributes files with

* text eol=lf

which is clearly wrong because it will convert all paths to LF even binaries before checkin.
So that happend and I am wondering if a binary file/blob F in the history is corrupt (because of crlf got converted to lf) can be restored such that the conversion is undone.

If that procedure is applicable I would apply it in a git filter-branch somehow...

PS: I made a new history with a corrected .gitattribute file everywhere on master

* text=auto eol=lf

made a new orphan branch new-master and rebased the whole master onto it. But that does not solve the problem, the file/blobs are left of course corrupt...


问:
How to change text color of cmd with windows batch script every 1 second
The color command has to do with changing color of windows command promt background/text

color 0A - where 0 is the background color and A is the text color

I want to change these color of text every 1 second in windows batch script using an array with 1,2,3,4,5,6,7,8,9,A,B,C,D,E,F witch are the color codes.

```<code>0 = Black       8 = Gray
1 = Blue        9 = Light Blue
2 = Green       A = Light Green
3 = Aqua        B = Light Aqua
4 = Red         C = Light Red
5 = Purple      D = Light Purple
6 = Yellow      E = Light Yellow
7 = White       F = Bright White
</code>```

the command should be go every second like this

```<code>color 01
color 02
color 03
....
color 0E
color 0F
</code>```

and for these i found some little script but im not sure how to make it work to change the color for every 1 second!

```<code>for /L %%i in (1,1,%n%) do echo !array[%%i]!
</code>```

or this

```<code>@echo off CLS
for /l %%a in (15,-1,1) do (
color 0A
cls
)
pause
</code>```

or this

```<code>SET COUNTDOWN=15
:COUNTDOWNLOOP
IF %COUNTDOWN%==0 GOTO END
color 0A && %R1%
CLS
SET /A COUNTDOWN -=1
GOTO COUNTDOWNLOOP
:END
</code>```

答:
Try this command:

```<code>@echo off
cls
:loop
echo RAINBOW
color 0
echo RAINBOW
color 1
echo RAINBOW
color 2
echo RAINBOW
color 3
echo RAINBOW
color 4
echo RAINBOW
color 5
echo RAINBOW
color 6
echo RAINBOW
color 8
echo RAINBOW
color 9
echo RAINBOW
color A
echo RAINBOW
color B
echo RAINBOW
color C
echo RAINBOW
color D
echo RAINBOW
color E
echo RAINBOW
goto loop
</code>```

This should create color changing text go in a loop.

Edit: You can change the words rainbow to whatever you want.

Body:
The color command has to do with changing color of windows command promt background/text

color 0A - where 0 is the background color and A is the text color

I want to change these color of text every 1 second in windows batch script using an array with 1,2,3,4,5,6,7,8,9,A,B,C,D,E,F witch are the color codes.

0 = Black       8 = Gray
1 = Blue        9 = Light Blue
2 = Green       A = Light Green
3 = Aqua        B = Light Aqua
4 = Red         C = Light Red
5 = Purple      D = Light Purple
6 = Yellow      E = Light Yellow
7 = White       F = Bright White

the command should be go every second like this

color 01
color 02
color 03
....
color 0E
color 0F

and for these i found some little script but im not sure how to make it work to change the color for every 1 second!

for /L %%i in (1,1,%n%) do echo !array[%%i]!

or this

@echo off CLS
for /l %%a in (15,-1,1) do (
color 0A
cls
)
pause

or this

SET COUNTDOWN=15
:COUNTDOWNLOOP
IF %COUNTDOWN%==0 GOTO END
color 0A && %R1%
CLS
SET /A COUNTDOWN -=1
GOTO COUNTDOWNLOOP
:END

Body:
Try this command:

@echo off
cls
:loop
echo RAINBOW
color 0
echo RAINBOW
color 1
echo RAINBOW
color 2
echo RAINBOW
color 3
echo RAINBOW
color 4
echo RAINBOW
color 5
echo RAINBOW
color 6
echo RAINBOW
color 8
echo RAINBOW
color 9
echo RAINBOW
color A
echo RAINBOW
color B
echo RAINBOW
color C
echo RAINBOW
color D
echo RAINBOW
color E
echo RAINBOW
goto loop

This should create color changing text go in a loop.

Edit: You can change the words rainbow to whatever you want.


问:
SwiftUI: how to create custom UIDatePicker?
I succeeded to create UIDatePicker inside SwifUI, but when I change the date wheel in picker the date value not update, here is my code:

```<code>struct DatePicker: UIViewRepresentable {
    @Binding var date: Date

    func makeUIView(context: Context) -> UIDatePicker {
        let view = UIDatePicker()
        view.datePickerMode = .date
        return view
    }
    func updateUIView(_ uiView: UIDatePicker, context: Context) {
        uiView.date = date
    }
}
</code>```

Then I call it from the view like this:

```<code>struct SwiftUIView: View {
  @State var date = Date()
    var body: some View {
      DatePicker(date: self.$date)
  }
}
</code>```

答:
An extended DatePicker approach with optional parameters (based on @Asperi answer).

```<code>struct DatePickerUIKit: UIViewRepresentable {
    @Binding private var selection: Date

    private let range: ClosedRange<Date>?

    private var minimumDate: Date? {
         range?.lowerBound
    }

    private var maximumDate: Date? {
        range?.upperBound
    }

    private var minuteInterval: Int

    private let datePicker = UIDatePicker()

    init(selection: Binding<Date>, in range: ClosedRange<Date>?, minuteInterval: Int = 1) {
        self._selection = selection
        self.range = range
        self.minuteInterval = minuteInterval
    }

    func makeUIView(context: Context) -> UIDatePicker {
        datePicker.datePickerMode = .dateAndTime
        datePicker.minuteInterval = minuteInterval
        datePicker.minimumDate = minimumDate
        datePicker.maximumDate = maximumDate
        datePicker.addTarget(context.coordinator, action: #selector(Coordinator.changed(_:)), for: .valueChanged)
        return datePicker
    }

    func updateUIView(_ uiView: UIDatePicker, context: Context) {
        datePicker.date = selection

    }

    func makeCoordinator() -> DatePickerUIKit.Coordinator {
        Coordinator(selection: $selection, in: range, minuteInterval: minuteInterval)
    }

    class Coordinator: NSObject {
        private let selection: Binding<Date>
        private let range: ClosedRange<Date>?
        private let minuteInterval: Int

        init(selection: Binding<Date>, in range: ClosedRange<Date>? = nil, minuteInterval: Int = 1) {
            self.selection = selection
            self.range = range
            self.minuteInterval = minuteInterval
        }

        @objc func changed(_ sender: UIDatePicker) {
            self.selection.wrappedValue = sender.date
        }
    }
}
</code>```

For example to set the minute interval, that is not supported by SwiftUI yet:

```<code>@State var dateFrom = Date()

let minMaxRange = Date().dateAtStartOf(.day)...Date().dateAtEndOf(.day) + 3.days

DatePickerUIKit(selection: $dateFrom,
             range: minMaxRange, minuteInterval: 30)
</code>```

Body:
I succeeded to create UIDatePicker inside SwifUI, but when I change the date wheel in picker the date value not update, here is my code:

struct DatePicker: UIViewRepresentable {
    @Binding var date: Date

    func makeUIView(context: Context) -> UIDatePicker {
        let view = UIDatePicker()
        view.datePickerMode = .date
        return view
    }
    func updateUIView(_ uiView: UIDatePicker, context: Context) {
        uiView.date = date
    }
}

Then I call it from the view like this:

struct SwiftUIView: View {
  @State var date = Date()
    var body: some View {
      DatePicker(date: self.$date)
  }
}

Body:
An extended DatePicker approach with optional parameters (based on @Asperi answer).

struct DatePickerUIKit: UIViewRepresentable {
    @Binding private var selection: Date

    private let range: ClosedRange<Date>?

    private var minimumDate: Date? {
         range?.lowerBound
    }

    private var maximumDate: Date? {
        range?.upperBound
    }

    private var minuteInterval: Int

    private let datePicker = UIDatePicker()

    init(selection: Binding<Date>, in range: ClosedRange<Date>?, minuteInterval: Int = 1) {
        self._selection = selection
        self.range = range
        self.minuteInterval = minuteInterval
    }

    func makeUIView(context: Context) -> UIDatePicker {
        datePicker.datePickerMode = .dateAndTime
        datePicker.minuteInterval = minuteInterval
        datePicker.minimumDate = minimumDate
        datePicker.maximumDate = maximumDate
        datePicker.addTarget(context.coordinator, action: #selector(Coordinator.changed(_:)), for: .valueChanged)
        return datePicker
    }

    func updateUIView(_ uiView: UIDatePicker, context: Context) {
        datePicker.date = selection

    }

    func makeCoordinator() -> DatePickerUIKit.Coordinator {
        Coordinator(selection: $selection, in: range, minuteInterval: minuteInterval)
    }

    class Coordinator: NSObject {
        private let selection: Binding<Date>
        private let range: ClosedRange<Date>?
        private let minuteInterval: Int

        init(selection: Binding<Date>, in range: ClosedRange<Date>? = nil, minuteInterval: Int = 1) {
            self.selection = selection
            self.range = range
            self.minuteInterval = minuteInterval
        }

        @objc func changed(_ sender: UIDatePicker) {
            self.selection.wrappedValue = sender.date
        }
    }
}

For example to set the minute interval, that is not supported by SwiftUI yet:

@State var dateFrom = Date()

let minMaxRange = Date().dateAtStartOf(.day)...Date().dateAtEndOf(.day) + 3.days

DatePickerUIKit(selection: $dateFrom,
             range: minMaxRange, minuteInterval: 30)


问:
what is this syntax error? I don't even know what the error is. I m just beginning
```<code>number = input("Please enter your number:")
number = int(number)
if number % 10 == 0 :
   print("Yes the number is a multiple of 10.")
elif :
    print("No the number is not a multiple of 10.")
else :
    print("Invalid number!")
</code>```

<p>this code gives the following output:  </p>

```<code>  File "multiple_10.py", line 5
elif :
     ^
SyntaxError: invalid syntax
</code>```

答: elif need a condition, add a condition or use else

Body:
number = input("Please enter your number:")
number = int(number)
if number % 10 == 0 :
   print("Yes the number is a multiple of 10.")
elif :
    print("No the number is not a multiple of 10.")
else :
    print("Invalid number!")

this code gives the following output:

  File "multiple_10.py", line 5
elif :
     ^
SyntaxError: invalid syntax


问:
System.ArgumentNullException: 'Value canot be null.'
I receive the System.ArgumentNullException: 'Value cannot be null.' error when implementing search in Asp.net MVC.

```<code>public static Collection<Video> vList = VideoRepository.GetCollection();
List<Video> listofvideos = new List<Video>
public ActionResult Index(string item)
{
  foreach (Video movie in vList)
  {
    if (movie.Title.ToLower().Contains(item))
    {
     listofvideos.add(movie);
    }
  }
 return view(listofvideos);
}
</code>```

答:
probably it happen when vList is null

check that not be null

```<code>    public static Collection<Video> vList = VideoRepository.GetCollection();
List<Video> listofvideos = new List<Video>
public ActionResult Index(string item)
{
//add check
if(vList ==null)
{
   return Content("no thing!!")
}
foreach (Video movie in vList)
{
if (movie.Title.ToLower().Contains(item))
{
listofvideos.add(movie);
}
}
return view(listofvideos);
}
</code>```

Body:
I receive the System.ArgumentNullException: 'Value cannot be null.' error when implementing search in Asp.net MVC.

public static Collection<Video> vList = VideoRepository.GetCollection();
List<Video> listofvideos = new List<Video>
public ActionResult Index(string item)
{
  foreach (Video movie in vList)
  {
    if (movie.Title.ToLower().Contains(item))
    {
     listofvideos.add(movie);
    }
  }
 return view(listofvideos);
}

Body:
probably it happen when vList is null

check that not be null

    public static Collection<Video> vList = VideoRepository.GetCollection();
List<Video> listofvideos = new List<Video>
public ActionResult Index(string item)
{
//add check
if(vList ==null)
{
   return Content("no thing!!")
}
foreach (Video movie in vList)
{
if (movie.Title.ToLower().Contains(item))
{
listofvideos.add(movie);
}
}
return view(listofvideos);
}


答: You need to provide a condition when you use elif--otherwise just use else. Check out the python docs here: https://docs.python.org/3/tutorial/controlflow.html?highlight=elif.</p>

Title: what is this syntax error? I don't even know what the error is. I m just beginning