text:
Q: problem pagination with this error java.lang.IllegalArgumentException:Limit must be a positive integer I have a problem with my code please help me to correct my code please it does not work I am new to android programming
PostAdapter
package com.developer.fireone.fingaoffice.Adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.developer.fireone.fingaoffice.CommentsActivity;
import com.developer.fireone.fingaoffice.FollowersActivity;
import com.developer.fireone.fingaoffice.Fragment.PostDetailFragment;
import com.developer.fireone.fingaoffice.Fragment.ProfileFragment;
import com.developer.fireone.fingaoffice.Model.ForAllUser;
import com.developer.fireone.fingaoffice.Model.Post;
import com.developer.fireone.fingaoffice.Model.User;
import com.developer.fireone.fingaoffice.Notifications.Data;
import com.developer.fireone.fingaoffice.Notifications.Sender;
import com.developer.fireone.fingaoffice.Notifications.Token;
import com.developer.fireone.fingaoffice.R;
import com.developer.fireone.fingaoffice.VideoActivity;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.gson.Gson;
import com.tylersuehr.socialtextview.SocialTextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.security.AccessController.getContext;

public class PostAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final int VIEW_TYPE_ITEM = 0;
    private final int VIEW_TYPE_LOADING = 1;

    public Context mContext;
    public List<Post> mPost;
    public Activity activity;
    public FirebaseUser firebaseUser;
    public RequestQueue requestQueue;
    public boolean notify = false;

    public PostAdapter(Context mContext, List<Post> mPost, Activity activity) {

        this.mContext = mContext;
        this.mPost = mPost;
        this.activity = activity;

    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == VIEW_TYPE_ITEM) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_item, parent, false);
            return new ItemViewHolder(view);
        } else {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_loading, parent, false);
            return new LoadingViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {

        if (viewHolder instanceof ItemViewHolder) {

            populateItemRows((ItemViewHolder) viewHolder, position);
        } else if (viewHolder instanceof LoadingViewHolder) {
            showLoadingView((LoadingViewHolder) viewHolder, position);
        }

    }

    @Override
    public int getItemCount() {
        return mPost == null ? 0 : mPost.size();
    }

    /**
     * The following method decides the type of ViewHolder to display in the RecyclerView
     *
     * @param position
     * @return
     */
    @Override
    public int getItemViewType(int position) {
        return mPost.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
    }

    private class ItemViewHolder extends RecyclerView.ViewHolder {

        public ImageView btn_play,image_profile, post_image, like, comment, save, more,certification_finga,share;
        public TextView username, fullname, likes, publisher, comments, txt_time, txt_date, finga_android;
        public SocialTextView description;
        public ImageView post_video;
        public ProgressBar progressBar;

        public ItemViewHolder(@NonNull View itemView) {
            super(itemView);

            certification_finga=itemView.findViewById(R.id.certifier_finga);
            finga_android=itemView.findViewById(R.id.finga_android);
            progressBar=itemView.findViewById(R.id.progress);
            image_profile=itemView.findViewById(R.id.image_profile);
            share=itemView.findViewById(R.id.share);
            btn_play=itemView.findViewById(R.id.btn_play);
            post_image=itemView.findViewById(R.id.post_image);
            post_video=itemView.findViewById(R.id.post_video);
            like=itemView.findViewById(R.id.like);
            comment=itemView.findViewById(R.id.comment);
            save=itemView.findViewById(R.id.save);
            username=itemView.findViewById(R.id.username);
            fullname=itemView.findViewById(R.id.fullname);
            likes=itemView.findViewById(R.id.likes);
            publisher=itemView.findViewById(R.id.publisher);
            description=itemView.findViewById(R.id.description);
            comments=itemView.findViewById(R.id.comments);
            more=itemView.findViewById(R.id.more);
            txt_date=itemView.findViewById(R.id.txt_date);
            txt_time=itemView.findViewById(R.id.txt_time);

        }
    }

    private class LoadingViewHolder extends RecyclerView.ViewHolder {

        ProgressBar progressBar;

        public LoadingViewHolder(@NonNull View itemView) {
            super(itemView);
            progressBar = itemView.findViewById(R.id.progressBar_loading);
        }
    }

    private void showLoadingView(LoadingViewHolder viewHolder, int position) {
        //ProgressBar would be displayed

    }

    private void populateItemRows(ItemViewHolder viewHolder, int position) {

       //...

    }

    //send Notification like...
    private void sendNotificaion(String receiver, final String username, final String msg) {

        DatabaseReference tokens = FirebaseDatabase.getInstance().getReference("Tokens");
        requestQueue= Volley.newRequestQueue(mContext);
        Query query = tokens.orderByKey().equalTo(receiver);
        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for(DataSnapshot snapshot : dataSnapshot.getChildren()){
                    Token token = snapshot.getValue(Token.class);
                    Data dataComment = new Data(
                            firebaseUser.getUid(),
                            R.mipmap.logo4,
                            username+": "+msg,
                            "Le Yamo de xa ! ",
                            ""+receiver,
                            "LikeNotification");

                    Sender senderComment = new Sender(dataComment, token.getToken());
                    try {
                        JSONObject senderJsonObj = new JSONObject(new Gson().toJson(senderComment));
                        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("https://fcm.googleapis.com/fcm/send", senderJsonObj,
                                new Response.Listener<JSONObject>() {
                                    @Override
                                    public void onResponse(JSONObject response) {
                                        Log.d("JSON_RESPONSE", "onResponse: "+response.toString());

                                    }
                                }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                Log.d("JSON_RESPONSE", "onResponse: "+error.toString());
                            }
                        }){
                            @Override
                            public Map<String, String> getHeaders() throws AuthFailureError {
                                Map<String,String> headers=new HashMap<>();
                                headers.put("Content-Type","application/json");
                                headers.put("Authorization","key=AAAAST1mR1g:APA91bFEgcbD3UGgdhByr7gEP2Zrc1o6Lg2yqAZfhsPKtY1jPaGmc5MKblGLn6kT0atmVlPo95xaGTpxxTn997Bm_X9mlJQ6gwlY7wGl-Z7HV9RuJA6CP2JgSd52jRLycDoL8l_ONklX");
                                return headers;
                            }
                        };

                        requestQueue.add(jsonObjectRequest);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

    }

    private void shareTextOnly(String description) {

        String shareBody = description+"\n"+"\n"+ "Ce post ete partager depuis 'Finga' le reseau Social Afro telechargeable ici: " +
                "https://play.google.com/store/apps/details?id=com.developer.fireone.finga";

        Intent sIntent = new Intent(Intent.ACTION_SEND);
        sIntent.setType("text/plain");
        sIntent.putExtra(Intent.EXTRA_SUBJECT,"Finga>> Subject Here");
        sIntent.putExtra(Intent.EXTRA_TEXT,shareBody);
        mContext.startActivity(Intent.createChooser(sIntent,"Finga>> Share Via"));

    }

    private void ShareImageAndText(String description, Bitmap bitmap) {

        String shareBody = description +"\n"+ "\n"+"Ce post ete partager depuis 'Finga' le reseau Social Afro telechargeable ici: " +
                "https://play.google.com/store/apps/details?id=com.developer.fireone.finga";
        Uri uri = saveImageToShare(bitmap);

        Intent sIntent = new Intent(Intent.ACTION_SEND);
        sIntent.putExtra(Intent.EXTRA_STREAM,uri);
        sIntent.putExtra(Intent.EXTRA_TEXT,shareBody);
        sIntent.putExtra(Intent.EXTRA_SUBJECT,"Finga>> Subject Here");
        sIntent.setType("image/png");
        mContext.startActivity(Intent.createChooser(sIntent,"Finga>> Share Via"));

    }

    private Uri saveImageToShare(Bitmap bitmap) {

        File imageFolder = new File(mContext.getCacheDir(),"images");
        Uri uri = null;

        try {
            imageFolder.mkdirs();
            File file = new File(imageFolder,"shared_image.png");

            FileOutputStream stream =new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 90,stream);
            stream.flush();
            stream.close();
            uri= FileProvider.getUriForFile(mContext,"com.developer.fireone.finga.fileprovider",file);

        }catch (Exception e){
            Toast.makeText(mContext, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
        }

        return uri;
    }

    private void getComments(String postid, final TextView comments ){

        DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Comments").child(postid);

        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                comments.setText(mContext.getString(R.string.viewAll)+" "+dataSnapshot.getChildrenCount()+" "+mContext.getString(R.string.comments1));

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

    }

    // isliked
    private void isLiked(String postid, final ImageView imageView){

        final FirebaseUser firebaseUser= FirebaseAuth.getInstance().getCurrentUser();

        DatabaseReference reference=FirebaseDatabase.getInstance().getReference()
                .child("Likes")
                .child(postid);

        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                try{
                    if(dataSnapshot.child(firebaseUser.getUid()).exists()){
                        imageView.setImageResource(R.drawable.ic_liked);
                        imageView.setTag("liked");
                    }else {
                        imageView.setImageResource(R.drawable.ic_like);
                        imageView.setTag("like");
                    }
                }catch (Exception e){
                    Toast.makeText(mContext, "wait a moment please...", Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

    }

    private void addNotifications(String userid, String postid){
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Notifications").child(userid);

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("userid", firebaseUser.getUid());
        hashMap.put("text", mContext.getString(R.string.strlikePost));
        hashMap.put("postid", postid);
        hashMap.put("ispost", true);
        hashMap.put("isseen", false);
        reference.push().setValue(hashMap);
    }

    private  void nrLikes(final TextView likes, String postid){
        DatabaseReference reference=FirebaseDatabase.getInstance().getReference().child("Likes")
                .child(postid);
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                likes.setText(dataSnapshot.getChildrenCount()+" yamo.");

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

    }

    private void  publisherInfo(final ImageView image_profile,final ImageView certification_finga, final TextView username, final TextView fullname, final TextView publisher, final String userid){

        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users").child(userid);

        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                final User user= dataSnapshot.getValue(User.class);
                if(user.getCertifier()!=null && user.getCertifier().equals("certified")){

                    certification_finga.setVisibility(View.VISIBLE);

                }else{
                    certification_finga.setVisibility(View.GONE);
                }
                Glide.with(mContext.getApplicationContext()).load(user.getImageurl()).into(image_profile);
                username.setText(user.getUsername());
                fullname.setText(user.getFullname());
                publisher.setText(user.getUsername());

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

    }

    private void isSave(final String postid, final ImageView imageView){
        FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();

        DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Saves")
                .child(firebaseUser.getUid());

        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                if(dataSnapshot.child(postid).exists()){
                    imageView.setImageResource(R.drawable.ic_saved);
                    imageView.setTag("saved");
                }else{
                    imageView.setImageResource(R.drawable.ic_save_black);
                    imageView.setTag("save");
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

    }

    private void editPost(final String postid){

        final AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
        alertDialog.setTitle(R.string.strEditPost);

        final EditText editText = new EditText(mContext);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT
        );
        editText.setLayoutParams(lp);
        alertDialog.setView(editText);

        getText(postid, editText);
        alertDialog.setPositiveButton(R.string.strEdit, (dialogInterface, i) -> {

            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("description", editText.getText().toString());

            FirebaseDatabase.getInstance().getReference("Posts")
                    .child(postid).updateChildren(hashMap);

        });
        alertDialog.setNegativeButton(R.string.strCancel, (dialogInterface, i) -> dialogInterface.dismiss());

        alertDialog.show();

    }

    private void getText(String postid, final EditText editText) {

        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts")
                .child(postid);

        reference.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                editText.setText(dataSnapshot.getValue(Post.class).getDescription());

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

MainFragment
 private void initScrollListener() {
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();

                if (!isLoading) {
                    if (linearLayoutManager != null && linearLayoutManager.findLastCompletelyVisibleItemPosition() == postList.size() - 1) {
                        //bottom of list!
                        loadMore();
                        isLoading = true;
                    }
                }
            }
        });

    }

    private void loadMore() {

        postList.add(null);
        postAdapter.notifyItemInserted(postList.size() - 1);

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                postList.remove(postList.size() - 1);
                int scrollPosition = postList.size();
                postAdapter.notifyItemRemoved(scrollPosition);
                currentSize = scrollPosition;
                DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
                reference.keepSynced(true);

                Query postQuery = reference.startAt(oldestPostId).limitToLast(currentSize*10);

                postQuery.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {

                        postList.clear();

                        for(DataSnapshot snapshot:dataSnapshot.getChildren()){

                            Post post = snapshot.getValue(Post.class);
                            for(String id:followingList){
                                oldestPostId = dataSnapshot.getKey();
                                snapshot.getChildrenCount();

                                if(post.getPublisher()!=null && post.getPublisher().equals(id)){

                                    postList.add(post);
                                    indication.stopShimmer();
                                    indication.setVisibility(View.GONE);
                                    currentSize++;

                                }

                            }

                            if(post.getPublisher()!=null && post.getPublisher().equals(firebaseUser.getUid())){
                                postList.add(post);
                                //stop shimmer
                                indication.setVisibility(View.GONE);
                                indication.stopShimmer();

                            }

                        }

//                postAdapter.notifyItemRemoved(postList.size());
//                postAdapter.notifyItemChanged(postList.size());
                        postAdapter.notifyDataSetChanged();
                        isLoading=false;

                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

                postAdapter.notifyDataSetChanged();
                isLoading = false;
            }
        }, 2000);

    }

    }

    private void readsposts(){

            DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");
            reference.keepSynced(true);

             Query postQuery = reference.limitToLast(10);

            postQuery.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                         postList.clear();

                    for(DataSnapshot snapshot:dataSnapshot.getChildren()){

                        Post post = snapshot.getValue(Post.class);
                        for(String id:followingList){

                            if(post.getPublisher()!=null && post.getPublisher().equals(id)){

                                postList.add(post);
                                indication.stopShimmer();
                                indication.setVisibility(View.GONE);

                            }

                        }

                        if(post.getPublisher()!=null && post.getPublisher().equals(firebaseUser.getUid())){
                            postList.add(post);
                            //stop shimmer
                            indication.setVisibility(View.GONE);
                            indication.stopShimmer();

                             }

                        }

//                postAdapter.notifyItemRemoved(postList.size());
//                postAdapter.notifyItemChanged(postList.size());
                postAdapter.notifyDataSetChanged();

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

    }

A: The limitToLast(...) function in the line Query postQuery = reference.startAt(oldestPostId).limitToLast(currentSize*10); in your loadMore() function needs to be a positive integer as the exception says. So if your currentSize is 0, this exception is thrown.
So instead of currentSize = scrollPosition; you should replace it with:
currentSize = scrollPosition == 0 ? 1 : scrollPosition;


text:
Q: Routing(?) in Vanilla JS I need my webite to display info in a certain language, based on a query in my webite's URL (e.g. www.website.com/index.php?country=FR). How can I do that with vanilla JS and not React/Angular?
My approach:
1) JS recognizes a query in the URL (in this case- 'country=FR') and then appends a js file, which has neccessary french words in it defined by variables.
2) JS in my script tag that's in the HTML file, appends the main page markup text with template literals in it.
3)
I don't know, whether the browser fails to either fetch the language file itself or its variables. At the moment it does not render anything.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

=========================
Main.js

var domain = window.location.href;
var FRString = domain.includes("country=FR");
var ESString = domain.includes("country=ES");

if (FRString) {
  $('head').append(`<script src="./Language_files/FRENCHwords.js" />`)
}

if (ESString) {
  $('head').append(`<script src="./Language_files/SPANISHwords.js" />`)
}

=========================
FRENCHwords.js

const goodmorning = 'Bonjour';
const goodevening = 'Bonsoir';
const mynameis = 'Mon nom est';

=========================
SPANISHwords.js

const goodmorning = 'Buenos dias';
const goodevening = 'Buenas tardes';
const mynameis = 'Mi nombre es';

No errors displayed, the page is just not rendering...

A: In Your main.js file, you are using domain.includes, it only returns the domain name but not the entire URL. You can use window.location.href.includes for this.
Instead of:  domain.includes("country=FR");
Try: window.location.href.includes("country=FR");

redpajama_set_name: RedPajamaStackExchange


text:
Q: How make reference to keys in dictionary in Python Let's say, I have a dictionary like below
dik = {
    "dir1": {},
}

I am interested to traverse through the dictionary recursively from value of one key to value of another.
# assume `dik` as global variable

def travel():
   curr = dik
   for i in ["dir1", "dir2"]:
       if i in curr:
          curr = curr[i]
       else:
          curr[i] = {}

I want the travel function to make the dik as
dik = {
    "dir1": {
        "dir2": {}
    },
}

A: Just doing some quick testing this is what I got. (The behavior should be what you have described I believe)
>>> dik = {
...     "dir1": {},
...     "dir2": {
...         "dir3": {},
...         "dir4": {
...             "dir5": {}
...         }
...     }
... }
>>> t = dik['dir2']
>>> t
{'dir3': {}, 'dir4': {'dir5': {}}}
>>> t['dir3'] = {'here' : 5}
>>> t
{'dir3': {'here': 5}, 'dir4': {'dir5': {}}}
>>> dik
{'dir2': {'dir3': {'here': 5}, 'dir4': {'dir5': {}}}, 'dir1': {}}

A: This works fine, even with a function, due to the mutability of dictionaries.
>>> dik = {
        "dir1": {},
        "dir2": {
            "dir3": {},
            "dir4": {
                "dir5": {}
                    }
                }
          }
>>> print dik
{'dir2': {'dir3': {}, 'dir4': {'dir5': {}}}, 'dir1': {}}

>>> def change(d, key, val):
        d[key] = val

This function takes any dictionary and sets or creates key with the value 'val'. You can pass nested dictionaries and it can access them fine, and it will be reflected in the global dik.
>>> change(dik['dir2']['dir3'], "file", "Some text")
>>> print dik
{'dir2': {'dir3': {'file': 'Some text'}, 'dir4': {'dir5': {}}}, 'dir1': {}}

Note it also still works if you use a reference in the function, like your curr = dik, because that just tells Python to treat them as the same thing, it doesn't actually make a separate copy.


text:
Q: ios9 Safari miscalculating sum I have some code that calculates the sum of key/values in a hash in a loop.  It appears to be calculating the sum in a different manner on ios9 Safari compared with anywhere else.  Although I can find a way to fix this individual use case, we use this type of syntax throughout our large code base, so I am looking for some understanding of

*

*why this is happening in ios9

*if there is a way to globally fix it that would be applicable to all objects that might have a Vue __ob__ object on them.

Try the code out here: https://liveweave.com/kKo88G. I also pasted it below:
// Define a hash
var totalItems, sum, type, value
totalItems = {}
totalItems['0'] = 3

// This definition of __ob__ is done dynamically by Vue,
// but I include it here by way of example of what breaks in ios9
totalItems.__ob__ = new Object()
Object.defineProperty(totalItems, '__ob__', {
    enumerable: false,
    writable: true,
   configurable: true
  });

// Loop through the hash
sum = 0
for (type in totalItems) {
  value = totalItems[type];
  sum += value;
}

// sum is 6 in ios9 Safari -- it loops through the '0' key twice
// sum is 3 in all other browsers and newer ios versions!

UPDATE:
After investigating further, this appears to be a bug in Safari on ios9 devices.  It applies both to hashes with the key '0' in them and to arrays.  It only seems to be an issue with for-in loops.  .forEach, .reduce, etc. work fine. https://liveweave.com/znUFU2 showcases this. Refresh the page a couple of times if liveweave is slow to load at first.  js fiddle/codepen/etc. don't work on ios9 at the moment. I have reported this to Apple.

A: Usually using for ... in is not a good idea. I believe your issue is related to that.
You can use for ... of ** or do a regular **for loop.
See a detailed explanation of what happens with for ... in here


text:
Q: Materials blocking UV-C radiation What type of materials can block UV-C type radiation? Such radiation is used in germicidal chambers. Do these materials actually block all of the radiation?

A: In a transparent medium (such as glass) the light transparency depends on the wavelength. At low wavelengths the band gap of the glass become smaller than the photon energy and hence light is absorbed. This absorption is really high except for the wavelengths very close to band gap.
Usually the glasses are designed to transmit very low quantities (<1%) in the unwanted wavelength range.
There are several materials such as acrylic, Polystyrene that block the UV, whereas other additives such as $\mathrm{CeO_2 }$, $\mathrm{TiO_2}$ etc. are used to mixed with the glass to block the UV. You can see few such transmission curves here.

Ref: https://www.gsoptics.com/transmission-curves/
Your concern is justified.You should always check this and ask for the test certificate or perform some test. But if the glasses are properly made they will absorb UV. Also they will not saturate as the absorbed UV light is re-emitted in the form of visible/IR radiation (that is not harmful).


text:
Q: A Long double variable results in a negative number when a value is assigned The issue I am having is that when I define a variable n as long double and set the value to 5 when i run it to print the value of n it prints -0.0000. I'm trying to achieve a larger range of numbers so i decided to switch from double to long double.
OS: windows 10
IDE: Code blocks
compiler: mingw32-gcc.exe
long double n;
n=5;
printf("n= %Lf\n",n);


text:
Q: ng-options with multiple select/Checkbox Is it possible to select multiple options from ng-options or have ng-options values as check boxes? If possible can someone give me an example please?

A: To create a multiple select just add multiple to your select tag

<!DOCTYPE html>

Choose:

            <select name="choose" ng-model="choose" multiple>
                <option ng-repeat="x in values" value="{{x.value}}">{{x.text}}</option>
            </select>


text:
Q: Asp.net Core code based policy needs access to Authorize attribute In my multitenant application user permissions (read Roles if you are more comfortable with that) are set per tenant so we are adding claims to each user with value TenantName:Permission.
We are using policy based authorization with custom code using the following code
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class PermissionAuthorizeAttribute : AuthorizeAttribute
{
    public Permission[] AcceptedPermissions { get; set; }

    public PermissionAuthorizeAttribute()
    {

    }

    public PermissionAuthorizeAttribute(params Permission[] acceptedPermissions)
    {
        AcceptedPermissions = acceptedPermissions;
        Policy = "RequirePermission";
    }
}

public enum Permission
{
    Login = 1,
    AddUser = 2,
    EditOtherUser = 3,
    EditBaseData = 6,
    EditSettings = 7,
}

With the above code we decorate Controller actions
[PermissionAuthorize(Permission.EditSettings)]
public IActionResult Index()

In startup.cs we have
services.AddAuthorization(options =>
    {
        options.AddPolicy("RequirePermission", policy => policy.Requirements.Add(new PermissionRequirement()));
    });

The AuthorizationHandler would in this case need access to the PermissionAuthorizeAttribute so we can check what permissions were specified on the action. At the moment we can get the attribute with the below code, but I think there must be an easier way, since there is a lot of casting an iterating there.
public class PermissionRequirement : AuthorizationHandler<PermissionRequirement>, IAuthorizationRequirement
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
    {

        var filters = ((FilterContext)context.Resource).Filters;

        PermissionAuthorizeAttribute permissionRequirement = null;
        foreach (var filter in filters)
        {
            var authorizeFilter = filter as AuthorizeFilter;
            if (authorizeFilter == null || authorizeFilter.AuthorizeData == null)
                continue;

            foreach (var item in authorizeFilter.AuthorizeData)
            {
                permissionRequirement = item as PermissionAuthorizeAttribute;
                if (permissionRequirement != null)
                    break;
            }

            if (permissionRequirement != null)
                break;
        }

        //TODO Check that the user has the required claims

        context.Succeed(requirement);
        return Task.CompletedTask;
    }
}

All the examples I have found are like this, where some hardwired policy is specified in startup.cs.
    services.AddAuthorization(options =>
    {
        options.AddPolicy("Over21",
                          policy => policy.Requirements.Add(new MinimumAgeRequirement(21)));
    }
Here you decorate you controller or action with
[Authorize(Policy="Over21")]
public class AlcoholPurchaseRequirementsController : Controller

I think the above example would be better if you could specify the age in the controller/action, like this
[Authorize(Policy="OverAge", Age=21)]
public class AlcoholPurchaseRequirementsController : Controller

Now you need to add a different policy for every minimum age.
Any ideas on how to make this efficient?

A: Although i would use Resource Based Authorization as i commented, there is a way to achieve your goal:
First create a custom attribute:
public class AgeAuthorizeAttribute : Attribute
{
    public int Age{ get; set; }
    public AgeAuthorizeAttribute(int age)
    {
        Age = age;
    }
}

Then write a filter provider:
public class CustomFilterProvider : IFilterProvider
{
    public int Order
    {
        get
        {
            return 0;
        }
    }

    public void OnProvidersExecuted(FilterProviderContext context)
    {
    }

    public void OnProvidersExecuting(FilterProviderContext context)
    {
        var ctrl = context.ActionContext.ActionDescriptor as ControllerActionDescriptor;
        var ageAttr = ctrl.MethodInfo.GetCustomAttribute<AgeAuthorizeAttribute>();
        if (ageAttr == null)
        {
             ageAttr = ctrl.ControllerTypeInfo.GetCustomAttribute<AgeAuthorizeAttribute>();
        }
        if (ageAttr != null)
        {
            var policy = new AuthorizationPolicyBuilder()
                   .AddRequirements(new MinimumAgeRequirement(ageAttr.Age))
                   .Build();

            var filter = new AuthorizeFilter(policy);
            context.Results.Add(new FilterItem(new FilterDescriptor(filter, FilterScope.Action), filter));
        }
    }
}

Finally register filter provider:
services.TryAddEnumerable(ServiceDescriptor.Singleton<IFilterProvider, CustomFilterProvider>());

And use it
[AgeAuthorize(21)]
public IActionResult SomeAction()

... or
[AgeAuthorize(21)]
public class AlcoholPurchaseRequirementsController : Controller

ps: not tested


text:
Q: How to click a button in one component and trigger an event in another component in Svelte? I'm quite new to Svelte and still learning, but I'm kind of stuck at something that seems quite simple. I'm using Svelte and Svelte Material UI to create an app with a Material design look and feel.
I've started with a simple app bar and a slide-out menu. The problem I'm running in to is that in the Svelte Material UI docs, the button that causes the menu to slide in and out, is part of the same menu component:
https://github.com/hperrin/svelte-material-ui/blob/master/site/src/routes/demo/menu.svelte
In my case, I would like the button to be part of my App-bar component and when I click that, the menu component should trigger to slide out (or in).
I've seen examples of how to pass properties (data) from one component to the other, but not how to trigger an event from one component to the other.
What I've tried:

*

*exporting a function (seems to need the script to be a module, as described here)

*exporting a boolean, and changing it from the outside (gives me an error I don't remember exactly what it was)

My code is as follows (using the "exporting a function" method):
App.svelte

<TopAppBar variant="static" {prominent} {dense} color={secondaryColor ? 'secondary' : 'primary'}>
  <Row>

      <IconButton class="material-icons" on:click={Toggle}>menu</IconButton>
      <Title>Test app</Title>

      <IconButton class="material-icons" aria-label="Print this page">account_circle</IconButton>
      <IconButton class="material-icons" aria-label="Bookmark this page">home</IconButton>

  </Row>
</TopAppBar>
<AppMenu></AppMenu>

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque tellus libero, semper at lobortis at, congue sit amet lorem. Aliquam porttitor varius sagittis. In non lorem lorem. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Pellentesque fringilla et nulla et tempus. Vestibulum pharetra tristique neque, non sodales massa dignissim vulputate. Sed eget leo tellus. Phasellus egestas gravida ante.

Appmenu.svelte

      <Button on:click={() => menu.setOpen(true)}>Open Menu</Button>
      <Menu bind:this={menu}>
        <List>
          <Item on:SMUI:action={() => clicked = 'Cut'}><Text>Cut</Text></Item>
          <Item on:SMUI:action={() => clicked = 'Copy'}><Text>Copy</Text></Item>
          <Item on:SMUI:action={() => clicked = 'Paste'}><Text>Paste</Text></Item>
          <Separator />
          <Item on:SMUI:action={() => clicked = 'Delete'}><Text>Delete</Text></Item>
        </List>
      </Menu>

Any help is appreciated

A: While using the context="module" approach would work, in your case you can easily just propagate the toggle function further up.
Let have MenuApp export the toggle function
In App use the bind syntax to bind your AppMenu to something (appMenu ?)
Call toggle on the object from your button
<IconButton class="material-icons" on:click={appMenu.toggle}>menu</IconButton>

A: Your example should work. Here is a very simple example of exporting a function:
//C.svelte

// App.svelte

click me

I think you should learn this kind of things with a very simple examples and later combine them to more complicated programs. I also recommend to leave external libraries away and first learn things with native elements, because those libraries hide things, change behaviors and even contains errors.


text:
Q: convergence of infimum I have a question that I encountered during my internship:
Consider a convergent sequence of continuous, convex functions $\{f_n(x)\}_n$ defined in $\mathbb{R}^M$. These functions are uniformly Lipschitz continuous, that is, $\exists C\in\mathbb{R}$ such that:
$$\forall x,y \in \mathbb{R^M},\forall n\ge1\quad |f_n(x)-f_n(y)|\le C|x-y|.$$
Furthermore, each function $f_n(x)$ has a minimizer. The properties of simple convergence and uniform Lipschitz continuity allow us to prove that the convergence is uniform in any compact of $\Bbb R^M$.
My question is:
Can we demonstrate  that $\inf_{\Bbb R^M}f_n(x)$ converges to $\inf_{\Bbb R^M}f_{\infty}(x)$ as $n\rightarrow\infty$,
where $f_{\infty}(x)$ is the limit of $f_n(x)$ and it is supposed that $\inf_{\mathbb{R^M}}f(x)$ is finite?
Thanks a lot!

A: No. Take the sequence
$$
f_n : x\in \mathbb R \to \frac 1 n \lvert x - n \rvert -1 \in \mathbb R
$$
We have
$$
\lim_n f_n(x) = 0 \quad\forall x\in \mathbb R\\
\inf_{\mathbb R} f_n(x) = f_n(n) = -1\\
\lvert f_n(x) - f_n(y) \rvert = \frac 1 n \big\lvert \lvert x - n \rvert - \lvert y - n\rvert \big\rvert \leq \frac 1 n \lvert x - y\rvert \leq \lvert x -y \rvert
$$
the functions $f_n$ converge punctually to $f_\infty = 0$, they are convex and uniformly Lipschitz continuous but
$$
\lim_n \left(\inf_{\mathbb R} f_n(x) \right) = -1 \neq \inf_{\mathbb R} f_\infty(x) = 0
$$


text:
Q: mousePressEvent() is not called until mouse is released or moved in Qt4.8, Embedded linux I am writing Ui application for an embedded device running on Embedded Linux. Each widget has QSS styles for "focused" cases. But widget that has focus does not get styled immediately after I press it.
While debugging I realized that mousePressEvent() is not called when I press, but it is called right before mouseReleaseEvent() or mouseMoveEvent(). In other words, mousePressEvent() is not called until I release or make the first move of mouse (my finger in this case).
I overloaded mousePressEvent(), mouseMoveEvent() and mouseReleaseEvent() to print debug messages. Here are the differences between expected and real logs:
// Expected
// (my action) debug message
(I touch the screen) "mouse pressed"
(I release)          "mouse released"

// Real case
(I touch)                     // nothing is printed
(I release) "mouse pressed"
            "mouse released"

In the desktop application, with actual mouse everything works as expected.
Problem is in the target device.
It is my first project with Embedded Linux and target device.
I do not know what to do. What I should check, compare, install/remove. In which direction I should go/do research. What is going on here?


text:
Q: Error(66,3): PLS-00201: identifier must be declared I have 1 procedure in with the user CC_DEVICE .
In this procedure I have this statement calling a procedure of another user.
of_device.p_msg.parse_csd_session(p_message);

But I got this error when compiling the package:
Error(66,3): PLS-00201: identifier 'OF_DEVICE.P_MSG' must be declared

A: you should be granted to use that procedure with :
SQL> conn of_device/pwd1
SQL> grant execute on p_msg to cc_device
SQL> conn cc_device/pwd0

now you can use it from cc_device...


text:
Q: Trying to scrape an HTML span value by class, but returns error def getDOW():
    DowURL = ["https://finance.yahoo.com/quote/%5EDJI?p=^DJI"]
    # requests data on the website(s) above
    page = requests.get(DowURL, headers=headers)

    # parses HTML text from website
    soup = BeautifulSoup(page.content, "html.parser")

    # title = soup.find(class_="D(ib) Fz(18px)").get_text()
    name = soup.find(class_= "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)").get_text()
    print (name)

Returns the error:
raise InvalidSchema("No connection adapters were found for '%s' % url")
requests.exceptions.InvalidSchema: No connection adapters were found for '['https://finance.yahoo.com/quote/%5EDJI?p=^DJI']'

I'm sorry if this was already asked before, but I'm new to BeautifulSoup so I wasn't sure what was going on. If anybody could help me, or advise me, that would be much appreciated. I am trying to scrape values from several sites, failed to do so using a list, so made separate functions (I know how redundant this is) and ran into this error.

A: When you look at the HTML source of the page, you will find, that the object you are interested in, is not present. The reason likely is, that the content is loaded only once you load the page in a browser. You can use Selenium and Chrome driver to do this. However, it is not very efficient to load the data like this. I did this in the past and it was not a good solution.
Since you seem to be interested in stock prices, you could use this approach:
import yfinance as yf
import datetime

start = datetime.datetime(2019,11,15)
end = datetime.datetime(2019,11,16)
data = yf.download('^DJI', start=start, end=end)
print(data)

Result:
[*********************100%***********************]  1 of 1 downloaded
                Open      High       Low     Close  Adj Close     Volume
Date
2019-11-14  27757.20  27800.71  27676.97  27781.96   27781.96  303970000
2019-11-15  27843.54  28004.89  27843.54  28004.89   28004.89  283720000

A: I would do it like this.
import datetime
import pandas as pd
import numpy as np
import pylab as pl
import datetime
from sklearn.cluster import AffinityPropagation
from sklearn import metrics
from matplotlib.collections import LineCollection
from pandas_datareader import data as wb
from sklearn import cluster, covariance, manifold

start = '2019-02-01'
end = '2020-02-01'

tickers = ['DJIA']

thelen = len(tickers)

price_data = []
for ticker in tickers:
    prices = wb.DataReader(ticker, start = start, end = end, data_source='yahoo')[['Open','Adj Close']]
    price_data.append(prices.assign(ticker=ticker)[['ticker', 'Open', 'Adj Close']])

#names = np.reshape(price_data, (len(price_data), 1))

names = pd.concat(price_data)
names.reset_index()

Result:
          Date ticker          Open     Adj Close
0   2019-02-01   DJIA  25025.310547  25063.890625
1   2019-02-04   DJIA  25062.119141  25239.369141
2   2019-02-05   DJIA  25287.929688  25411.519531
3   2019-02-06   DJIA  25371.570312  25390.300781
4   2019-02-07   DJIA  25265.810547  25169.529297
..         ...    ...           ...           ...
247 2020-01-27   DJIA  28542.490234  28535.800781
248 2020-01-28   DJIA  28594.279297  28722.849609
249 2020-01-29   DJIA  28820.529297  28734.449219
250 2020-01-30   DJIA  28640.160156  28859.439453
251 2020-01-31   DJIA  28813.039062  28256.029297

[252 rows x 4 columns]

Note: you can pass in any tickers you want, so change this line:
tickers = ['DJIA']

To this:
tickers = ['MMM',
'ABT',
'ABBV',
'ABMD',
'ACN',
'ATVI']

And you will get data for multiple tickers, like this.
Result:
           Date ticker        Open   Adj Close
0    2019-02-01    MMM  201.490005  190.939163
1    2019-02-04    MMM  199.009995  191.945831
2    2019-02-05    MMM  200.720001  192.818268
3    2019-02-06    MMM  201.220001  194.208420
4    2019-02-07    MMM  201.020004  191.591080
        ...    ...         ...         ...
1507 2020-01-27   ATVI   58.189999   58.320000
1508 2020-01-28   ATVI   58.790001   60.029999
1509 2020-01-29   ATVI   60.490002   60.400002
1510 2020-01-30   ATVI   59.919998   60.889999
1511 2020-01-31   ATVI   60.200001   58.480000

[1512 rows x 4 columns]


text:
Q: What's true in $\mathbb{R}^4$, false in $\mathbb{R}^3$ and uninteresting in $\mathbb{R}^5$? What are some interesting and easy-to-understand (for non-differential geometers) facts about subobjects of $\mathbb{R}^4$ that are not only false in $\mathbb{R}^3$, but also specific to the structure of $\mathbb{R}^4$ and maybe do not easily or naturally generalize to higher dimensions?

A: Only for $n=4$ does there exist an open set $U\subseteq\mathbb{R}^n$ that is homeomorphic to $\mathbb{R}^n$ but not diffeomorphic to $\mathbb{R}^n$ (a small exotic $\mathbb{R}^4$).  What this means is not too difficult to explain (no need to explain what a manifold is, only what a homeomorphism and a diffeomorphism are between open subsets of $\mathbb{R}^n$).  I don't think it qualifies as "uninteresting for $\mathbb{R}^5$", though (it's definitely not a triviality in any dimension other than $1$), but you seemed to say "false" was also OK.

A: Due to the theory of quaternions, due to Hamilton, $\bf R^4$ has a structure of a  of non commutative field. The only dimension for which $\bf R^n$ is a field are $n=1,2, 4$ . As an application, the special orthogonal group in dimension 4 is not simple : it is the quotient of $U\times U$ by it center $Z/2Z$ where $U$ is the unitary group in complex dimension 2, or the set of quaternions of norm 1. In other dimension (other than 2) the special orthogonal group modulo its center is simple.

A: Lets bump knot theory up a dimension.   In general, an $n$-sphere can be non-trivially knotted in $\mathbb{R}^{n+2}$.  Obviously, an $n$-sphere can be embedded in $\mathbb{R}^{n+1}$, where it is usually defined, but no knotting can occur.  In $\mathbb{R}^{n+3}$, we can use the extra dimension and unknot every $n$-sphere.
So, for $n=2$, we have that a $2$-sphere can be knotted in $\mathbb{R}^{4}$, cannot be knotted in $\mathbb{R}^{3}$, and is uninteresting in $\mathbb{R}^{5}$, since there is only one knot type.
If you want to look into this more, you should look at any number of great books: Rolfsen, Adams, and more that I am just not thinking of at the moment.
Edit: As per Mike's comment, we should be assuming PL or locally flat here.


text:
Q: latitude and longitude not saved google maps api I'm trying to get the latitude and longitude from an address with google maps api and I don't get it how. The map is working by getting the address but there is a way for that address to take the lat and lon? The following code is working:
 <ng-map default-style="false" zoom="16" center="{{ '{{ getAddress() }}' }}" style="width: 100%; height: 430px;">
                <marker centered="true" position="{{ '{{ getMarkerPosition() }}' }}" draggable="true" on-dragend="onMarkerDragEnd($event)"></marker>
                <shape ng-if="showRegions" ng-repeat="shape in regions"
                        (...)
                </shape>
 </ng-map>

And the js:
 $scope.getMarkerPosition = function () {
            if (!$scope.address.mapPinLocationLatitude || !$scope.address.mapPinLocationLongitude) {
                return $scope.getObjectiveAddress();
            }

            return [$scope.address.mapPinLocationLatitude, $scope.address.mapPinLocationLongitude]
        };

The problem is that mapPinLocationLatitude and long are always null, in database are not salved and don't know why..
   $scope.getAddress = function () {
            var address = "..."; (here just concatenate the string with the address values(street, number, etc and it returned)

            return streetString + ', ' + address;
        };

     $scope.onMarkerDragEnd = function ($event) {
            $scope.address.mapPinLocationLatitude = $event.latLng.lat();
            $scope.address.mapPinLocationLongitude = $event.latLng.lng();
            $scope.updateRegions();
        };

So, my question is, any idea how to get the latitude and long and for example if I write: the map to be displayed correctly?
 <marker centered="true" position="{{ '{{ [address.mapPinLocationLatitude, address.mapPinLocationLongitude]}}' }}" draggable="true" on-dragend="onMarkerDragEnd($event)"></marker>

A: Use geocoding service
Example
$.getJSON( {
url  : 'https://maps.googleapis.com/maps/api/geocode/json',
data : {
    sensor  : false,
    address : address
},
success : function( data, textStatus ) {
    console.log( textStatus, data );
}

} );
Similar question on stack here


text:
Q: git push not working after using CloudFlare reverse proxy I recently started using CloudFlare (reverse proxy) with my DigitalOcean Droplet (root access server) where I had set up git push deployment.
Of course, git push no longer works and returns this error:
ssh: connect to host example.com port 22: Operation timed out
This is most likely because git is trying to access a repo on CloudFlare's servers instead of my DigitalOcean server.
What is the best way to restore git push functionality?

A: You'll need to update your remote's URL to either use the raw IP, or add a DNS A record in the CloudFlare panel like raw.example.com with the CloudFlare orange cloud thing disabled (so it resolves directly to your host).  Then update your git remote setting:
git remote set-url origin git@127.0.0.1:foo/bar.git

or
git remote set-url origin git@raw.example.com:foo/bar.git

A: Solved.
I noticed I could ssh without a problem into my digitalocean server and realized I was accessing like so:
root@35.25.234.243  (fake IP)
so I changed my git config to use my server's IP address instead of the domain name and it works fine now.

A: Cloudflare is good; it hides your public IP.
Just put an entry in /etc/hosts file or add it manually to the local DNS server.


text:
Q: At underscore js, Can I get multiple columns with pluck method after input where method as linq select projection var people = [
    {firstName : "Thein", city : "ny", qty : 5},
    {firstName : "Michael", city : "ny", qty : 3},
    {firstName : "Bloom", city : "nj", qty : 10}
];

var results=_.pluck(_.where(people, {city : "ny"}), 'firstName');

For example : I need firstName and qty.

A: To project to multiple properties, you need map, not pluck:
var results = _.map(
    _.where(people, {city : "ny"}),
    function(person) {
        return { firstName: person.firstName, qty: person.qty };
    }
);

[{"firstName":"Thein","qty":5},{"firstName":"Michael","qty":3}]

(Fiddle)
Note that, if you wanted to, you could create a helper method "pluckMany" that does the same thing as pluck with variable arguments:
// first argument is the source array, followed by one or more property names
var pluckMany = function() {
    // get the property names to pluck
    var source = arguments[0];
    var propertiesToPluck = _.rest(arguments, 1);
    return _.map(source, function(item) {
        var obj = {};
        _.each(propertiesToPluck, function(property) {
            obj[property] = item[property];
        });
        return obj;
    });
};

You can use the _.mixin function to add a "pluckMany" function to the _ namespace.  Using this you can write simply:
var results = _.chain(people).where({city : "ny"}).pluckMany( "firstName", "qty").value();

(Fiddle)

A: Yep, I wish pluck had an option of passing an array, but in the meantime, you could do:
const pluckFields = (arr, fields) => _.map(arr, item => _.pick(item, fields))

A: My understanding is the author of the question wants to take an array of objects with many properties and strip each object down to a small list of properties.
There are myriad ways of doing so with _ , but I like this way best.  Pass in an empty result object which will be "this" inside the function.  Iterate with _each , and _pick the fields you want:
var myObjects = [
    { "first" : "eric",
      "last" : "gumbo",
      "code" : "x482"
    },
    { "first" : "john",
      "last" : "dinkman",
      "code" : "y9283"
    }
];

var result = [];
_.each( myObjects, function(itm) { this.push(_.pick(itm,"first","code")) }, result );

console.log(result);

A: TL;DR Use :
var results = _.chain(people)
    .where({ city: "ny" })
    .map(_.partialRight(_.pick, 'firstName', 'qty'))
    .value();

But please read on for explanations as I feel the process of finding this solution is more interesting than the actual answer.

The general pattern would be (it works with lodash too) :
_.map(array, function(obj) { return _.pick(obj, 'x', 'y', 'z'); });
Given this general map function which transforms each element of a collection, there are multiple ways to adapt this to your particular situation (that vouch for the flexibility of map, which is a very basic building block of functional programs).
Let me present below several ways to implement our solution :
var _ = require('lodash'); // @lodash 2.4.1 at the time of writing
// use underscore if you want to, but please see http://stackoverflow.com/questions/13789618/differences-between-lodash-and-underscore

/* la data */
var people = [{
    firstName: "Thein",
    city: "ny",
    qty: 5
}, {
    firstName: "Michael",
    city: "ny",
    qty: 3
}, {
    firstName: "Bloom",
    city: "nj",
    qty: 10
}];

/* OPTION1 : mixin' with _ */
_.mixin({
    pluckMany: function() {
        var array = arguments[0],
            propertiesToPluck = _.rest(arguments, 1);

        return _.map(array, function(item) {

            /* Alternative implementation 1.1
             * ------------------------------
             * Taken from @mMcGarnagle answer
             * _each is easy to understand here,
             * but has to modify the variable `obj` from a closure
             * I try to avoid that for trivial cases like this one.
             */
            var obj = {};
            _.each(propertiesToPluck, function(property) {
                obj[property] = item[property];
            });
            return obj;

            /* Alternative implementation 1.2
             * ------------------------------
             * Rewrite the previous code,
             * by passing the accumulator (previously`obj`, but really it is an object that accumulates the result being constructed) across function calls.
             * This construction is typical of the `reduce` function, closer to a functionnal programming style.
             */
            return _.reduce(propertiesToPluck, function(obj, property) {
                obj[property] = item[property];
                return obj;
            }, {});

            /* Alternative implementation 1.3
             * ------------------------------
             * If we are already using lodash/underscore,
             * then let's use the `pick` function ! I also included an example of `flatten` here
             */
            return _.pick(item, _.flatten(propertiesToPluck, true));

            /* Alternative implementation 1.4
             * ------------------------------
             * But really flatten is not needed.
             */
            return _.partial(_.pick, item).apply(null, propertiesToPluck);
        });
    }
});

/* Let's use our mixed function !
 * Since we call several _ functions on the same object
 * it is more readable to chain the calls.
 */
var results = _.chain(people)
    .where({
        city: "ny"
    })
    .pluckMany('firstName', 'qty')
    .value();

/* OPTION 2 : without mixing our code with lodash/underscore */
var results = _.chain(people)
    .where({
        city: "ny"
    })
    .map(_.partialRight(_.pick, 'firstName', 'qty'))
    .value();

console.log(results);

If you like this way of writing code with underscore or lodash, I highly suggest that you have a look at functional programming, as this style of writing as well as many functions (map, reduce amongst many others) come from there.
Note : This is apparently a common question in underscore :
https://github.com/jashkenas/underscore/issues/1104
This is apparently no accident if these are left out of underscore/lodash : "composability is better than features". You could also say do one thing and do it well. This is also why _.mixin exists.

A: YAAUu-Yep Another Answer Using underscore...

// use a proper browser to run this code snippet, a browser that is es6-compliant
let people = [{
    firstName: "Thein",
    city: "ny",
    qty: 5
  },
  {
    firstName: "Michael",
    city: "ny",
    qty: 3
  },
  {
    firstName: "Bloom",
    city: "nj",
    qty: 10
  }
];
// either you pick the properties you want
let picking = _.iteratee((person) => _(person).pick("firstName", "city"));
// either you omit the properties you do not want
let omitting = _.iteratee((person) => _(person).omit("qty"));
// create the filter by city
let living = (people, city) => _(people).where({
  "city": city
});
// put the "filter by city" into a mixin (as I assume it would be used again & again)
_.mixin({
  living: living
});
// do the thing (twice),
// these chaining methods could be done into a mixin as well
console.log("results by picking properties:", _(people).chain().living("ny").map(picking).value());
console.log("results by omitting properties:", _(people).chain().living("ny").map(omitting).value());
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

A: That one linear might save some lines:
var results=_.pick(_.where(people, {city : "ny"}), 'firstName', 'qty');

A: We don't have to use pluck, omit do the trick as well.
var result = _.map(people, function(person) {
  return _.omit(person, 'city');
});


text:
Q: Return items within Date Range My array:
 urlArray =  dataArray.map(function(item){
              return {
               Id:                               item.Id,
               Title:                            item.Title,
               StartDate:                        new Date(item.Start_x0020_Date).toLocaleDateString("en-GB"),
               EndDate:                          new Date(item.End_x0020_Date).toLocaleDateString("en-GB"),
                };
          });

var nextYear   = '01/01/2019';

How can I return return all items that have a start date that begins in this year (2018)? This is the same as excluding all items which have a start date > next year (i.e. 2019).
urlArray returns each date format as so:
1/1/1970
whereas in browser tools the API returns a date format of:
"2018-12-26T08:00:00Z"

I have tried returning all items with a filter that have a start date less than next year but still not working. My attempt is below:
let filteredAZLista = urlArray.filter(c =>  c.StartDate < nextYear);

A: You should do your comparisons by using Date objects, not strings, and you could do your filter before you do your string conversions in your map function, that way you are mapping over already filtered data.
So something like this:
var nextYear = new Date('01/01/2019');

var filteredData = dataArray.filter(item => new Date(item.Start_x0020_Date) < nextYear);

urlArray =  filteredData.map(function(item){
    return {
     Id:                               item.Id,
     Title:                            item.Title,
     StartDate:                        new Date(item.Start_x0020_Date).toLocaleDateString("en-GB"),
     EndDate:                          new Date(item.End_x0020_Date).toLocaleDateString("en-GB"),
      };
});


text:
Q: How should I restrict the points considered in each hexagonal lattice to correctly count all unique near-coincident lattices? Background:
If a hexagonal lattice is defined by integers $i, j$ where $x = a_1 \left(i + \frac{1}{2} j\right)$ and $y = a_1 \frac{\sqrt{3}}{2} j$, the distance to the origin for each point $r(a_1, i, j)$ will be $a_1 \sqrt{i^2 + j^2 + ij}$. See this answer to my earlier question.
If I have a second hexagonal lattice with constant $a_2$ it will form a coincident if there's some supercell of one that matches a supercell of the other, and since both are periodic it's sufficient to show that these lengths are equal:
$$a_1^2 (i^2 + j^2 + ij) = a_2^2(k^2 + l^2 + kl)$$
The example in the plot below is for $(i, j), (k, l) = (5, 4), (2, 3)$ and $a_1=1$, which makes $a_2 = \sqrt{\frac{61}{19}}$
To visualize the coincidence it's necessary to rotate the second lattice by
$$\theta = \text{arctan2} \left(\frac{\sqrt{3}}{2}j, \ \ i+\frac{1}{2}j \right) - \text{arctan2} \left(\frac{\sqrt{3}}{2}l, \ \ k+\frac{1}{2}l \right)$$
or about -10.26°.
We can know by symmetry that the negative of this angle or +10.26° will generate a second coincident lattice, and in fact every $\theta$ such that $\mod(\theta, \ 30°) \ne 0$ will have a complementary lattice at $-\theta$. At integer multiples of 30 degrees the pair will be degenerate and we'll count it as only a single coincident lattice.
Question:
I am writing an algorithm to find near-coincident lattices, where the lengths differ by some small fraction $\delta$, perhaps 1 percent:
$$\left|\frac{a_1^2 (i^2 + j^2 + ij) }{ a_2^2(k^2 + l^2 + kl)} - 1\right| <= \delta$$
I want to count the number of unique near-coincident configurations. The algorithm will be used in a python script.
My problem is that I don't want to miss any near-coincidences and at the same time don't want to double-count.
Question: How should I restrict the points considered in each hexagonal lattice to correctly count all unique near-coincident lattices?
I know I should restrict my search to a pie-shaped segment of all points in each of the two lattices, perhaps a 30° slice of one against a 60° slice of the other, but I haven't been able to convince myself that this guess is mathematically sound.

Example of a proper coincident lattice: $(i, j), (k, l) = (5, 4), (2, 3)$ with $\frac{a_2}{a_1} = \sqrt{\frac{61}{19}}$

A: As long as the $a_1/a_2$ ratio is the square root of of a ratio of Loeschian numbers (A003136), then I have bad news: every single pair is coincident!  We can do this by simply selecting $i,j$ to give $i^2+ij+j^2 = a_2^2$ and $k,\ell$ to give $k^2+k\ell+\ell^2 = a_1^2$.
Even worse: since the Loeschian numbers include all the squares, and thus the square root of ratios includes all rational numbers, which are dense among the reals, every single positive real number provides a near-coincident pair of lattices!
Here's a series of increasingly good lattices for $a_1/a_2 = \pi$.
1 (1, 0), 7 (2, 1) 0.40994348586990825
1 (1, 0), 9 (3, 0) 0.09662271123215094
3 (1, 1), 28 (4, 2) 0.057457614402431245
3 (1, 1), 31 (5, 1) 0.04487699344296536
4 (2, 0), 39 (5, 2) 0.012267118060447002
13 (3, 1), 127 (7, 6) 0.010274466253241465
13 (3, 1), 129 (8, 5) 0.005388703766188607
21 (4, 1), 208 (12, 4) 0.0035495556592474165
25 (5, 0), 247 (11, 7) 0.0010521861245589292
49 (5, 3), 484 (22, 0) 0.0008045131128543437
52 (6, 2), 513 (21, 3) 0.0004277365626641494
67 (7, 2), 661 (20, 9) 0.00039863067017686937
84 (8, 2), 829 (20, 13) 5.641699819802781e-05

Here I illustrate $\pi \approx \sqrt{\frac{247}{25}}$.  The error is just over one part in 1000, which means that if I'd actually drawn the magenta point as two separate points, you wouldn't be able to tell at this scale.


text:
Q: jQuery autocomplete box to flow out of SharePoint modal dialog I have an asp:TextBox that has a jQuery autocomplete attached to it, they are contained within a SharePoint CommonModalDialog. When typing in the text box the autocomplete pops up but is bigger than the remaining space in the modal dialog

How can I get the autocomplete to always be on top and show outside of the modal dialog?

</asp:Label>

            <asp:TextBox ID="tb" runat="server"></asp:TextBox>


text:
Q: Word very slow openig file from file server share Internet is full of useless advises on how to solve speed problem with Word.
My problem has some unique characteristics, I did some tests and I need a focused hint on what to try next.
Some users have an old version of Word (I cannot update due to missing licenses) and when they try to open small files (about 20 KB) on a network share (Windows 2016 server) it takes more than 3 minutes.
They don't experience the same delay opening local files or files on other shares.
Users with a newer release of Word can open files on the above mentioned Windows 2016 server ion a reasonable amount of time.
I cannot understand why the old Word doesn't like that particular file share. Apparently it has nothing special. How can I investigate further ?
Update
It seems that Word makes very numerous read operations of few bytes to Windows 2016 server. Copying the same file to a different share the read operations are reduced drastically (they become bigger). If this behavior is confirmed by other tests it can explain the great delay, anyway I don't know what to check on the file servers.
Thanks
Filippo


text:
Q: Pom.xml gives me NPE I have the POM.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>CucumberNG</groupId>
    <artifactId>CucumberNG</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>CucumberNG</name>
    <description>How to use Cucumber and TestNG</description>
    <build>
        <!-- To define the plugin version in your parent POM -->
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-source-plugin</artifactId>
                    <version>3.0.1</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-javadoc-plugin</artifactId>
                    <version>2.10.4</version>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.6.1</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
    <dependencies>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-java8</artifactId>
            <version>1.2.5</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-testng</artifactId>
            <version>1.2.5</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.testng/testng -->
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.11</version>
            <scope>test</scope>
        </dependency>

    </dependencies>
</project>

When I inserted at the end the dependency for Selenium
   <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.4.0</version>
    </dependency>

I got NPE.
See my attachment.

I am using Eclipse IDE for Java Developers
Version: Neon.3 Release (4.6.3)
Build id: 20170314-1500
here is my log:
    java.lang.NullPointerException
at java.util.zip.ZipFile.getZipEntry(ZipFile.java:566)
at java.util.zip.ZipFile.access$900(ZipFile.java:60)
at java.util.zip.ZipFile$ZipEntryIterator.next(ZipFile.java:524)
at java.util.zip.ZipFile$ZipEntryIterator.nextElement(ZipFile.java:499)
at java.util.zip.ZipFile$ZipEntryIterator.nextElement(ZipFile.java:480)
at  org.eclipse.m2e.jdt.internal.BuildPathManager.getJavaDocPathInArchive             (BuildPathManager.java:692)
at org.eclipse.m2e.jdt.internal.BuildPathManager.getJavaDocUrl(BuildPathManager.java:677)
at org.eclipse.m2e.jdt.internal.BuildPathManager.getJavaDocUrl(BuildPathManager.java:670)
at org.eclipse.m2e.jdt.internal.BuildPathManager.configureAttchedSourcesAndJavadoc(BuildPathManager.java:306)
at org.eclipse.m2e.jdt.internal.BuildPathManager.getClasspath(BuildPathManager.java:255)
at org.eclipse.m2e.jdt.internal.BuildPathManager.getClasspath(BuildPathManager.java:363)
at org.eclipse.m2e.jdt.internal.BuildPathManager.getClasspath(BuildPathManager.java:343)
at org.eclipse.m2e.jdt.internal.BuildPathManager.getClasspath(BuildPathManager.java:371)
at org.eclipse.m2e.jdt.internal.BuildPathManager.updateClasspath(BuildPathManager.java:191)
at org.eclipse.m2e.jdt.internal.BuildPathManager.mavenProjectChanged(BuildPathManager.java:180)
at org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager.notifyProjectChangeListeners(ProjectRegistryManager.java:783)
at org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager.applyMutableProjectRegistry(ProjectRegistryManager.java:930)
at org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager.refresh(ProjectRegistryManager.java:300)
at org.eclipse.m2e.core.internal.builder.MavenBuilder$BuildMethod.getProjectFacade(MavenBuilder.java:154)
at org.eclipse.m2e.core.internal.builder.MavenBuilder$BuildMethod$1.call(MavenBuilder.java:89)
at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.executeBare(MavenExecutionContext.java:176)
at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.execute(MavenExecutionContext.java:151)
at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.execute(MavenExecutionContext.java:99)
at org.eclipse.m2e.core.internal.builder.MavenBuilder$BuildMethod.execute(MavenBuilder.java:86)
at org.eclipse.m2e.core.internal.builder.MavenBuilder.build(MavenBuilder.java:200)
at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:735)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:206)
at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:246)
at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:301)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:304)
at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:360)
at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:383)
at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:144)
at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:235)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)


text:
Q: Non-recursive Quicksort in Scala I am trying to work on a non-recursive version of quicksort in scala but whenever I try to implement it, I get stuck and end up using tail recursion. Is there any simple way to implement Quicksort without the use of recursion in Scala?
All help is appreciated. Thank you!
EDIT: The recursive solution has been added. In this solution the sortingHelper method is tail-recursive.
def quickSortRecursive(values: Array[Int]) {
  // Swap the elements so that they aren't impacting recursion performance.
  // This swap helps the pivot get the correct position.
  def swap(i: Int, j: Int) {
    val t = values(i);
    values(i) = values(j);
    values(j) = t
  }

  // A method that takes in lower and upper bounds then sorts them.
  def sortRange(lowerBound: Int, upperBound: Int): (Int, Int) = {
    // Establish the pivot for use in sorting the bounds
    val pivot = values((lowerBound + upperBound) / 2)
    var i = lowerBound
    var j = upperBound

    // Sort the bounds using the pivot
    while (i <= j) {
      while (values(i) < pivot) {
        i += 1
      }
      while (values(j) > pivot) {
        j -= 1
      }
      if (i <= j) {
        swap(i, j)
        i += 1
        j -= 1
      }
    }

    // After the swaps, return the segments as lower and upper bounds
    (i, j)
  }

  @tailrec
  def sortingHelper(segments: List[(Int, Int)]) {
    // Take in the tuples from sortRange and sort them using tail-recursion
    segments.head match {
      case (l, r) =>
        var newSegments = segments.tail

        sortRange(l, r) match {
          case (i, j) =>
            if (l < j) {
              newSegments = (l, j) :: newSegments
            }
            if (i < r) {
              newSegments = (i, r) :: newSegments
            }
        }
        if (newSegments.nonEmpty) {
          sortingHelper(newSegments)
        }
    }
  }

  sortingHelper(List((0, values.length - 1)))
}

A: While the implementation itself needs huge improvements and I hope that will come as you improve with Scala. I will assume that everything else is perfect and just focus on conversion from tail-recursive.
To convert tail-recursive code to loop-based, you just have to capture the recursion-termination condition and make it the loop termination condition,
def sortingHelper2(segments: List[(Int, Int)]): Unit = {
  var newSegments = segments
  while (newSegments.nonEmpty) {
    val (l, r) = newSegments.head
    newSegments = newSegments.tail
    sortRange(l, r) match {
      case (i, j) =>
        if (l < j) {
          newSegments = (l, j) :: newSegments
        }
        if (i < r) {
          newSegments = (i, r) :: newSegments
        }
    }
  }
}

To better explain, lets look at one of the simplest tail-recursive functions,
def sumUpToN(n: Int): Long = {
  @tailrec
  def _sumUpToN(acc: Long, m: Int): Long = {
    if (m > 0)
      _sumUpToN(acc + m, m - 1)
    else
      acc
  }

  _sumUpToN(0, n)
}

To convert it to a loop based one, you just have to move this termination/continuation condition to your while loop,
def sumUpToN(n: Int): Long = {
  var acc = 0
  var m = n

  while (m > 0) {
    acc = acc + m
    m = m - 1
  }

  acc
}


text:
Q: RIDE - some Library/Resource are RED Some Library/Resource in my Robot Framework script are RED as shown below:
 bad script with red marks
While other one (which I copied from) is looks OK:
 good script
My working environment (tree) looks like this:
 working environment/tree
What I don't understand is why in one script everything looks good and in the other one (which looks almost the same) some Library/Resource are RED.
The main reason I ask is because my python script (stability_tests.py) is not getting the parameters I send (stability_args, see below).
my robot framework script
*** Settings ***
Force Tags        Critical    template    Conf=3    isTor=0    isSanity=0

headless    rcmd
Library           BeAm.beacon.tests.BeaconTesting    WITH NAME
BeaconTesting
Library           Collections
Library           BeAm.beacon.stability_tests
Library           BeAm.beacon.tests
Resource          ../../BeAm/beacon/settings.txt
Resource          ../../BeAm/settings.txt
Resource          ../../BeAm/local_settings.txt

*** Test Cases ***
Create Test Object
    [Tags]    must
    ${TEST} =    BeaconTesting.Get Beacon Test    3
    Set Suite Variable    ${TEST}    ${TEST}

Prepare Beacon Server
    [Tags]    prpr
    BeaconTesting.Change Mss Value    ${None}
    BeaconTesting.Prepare Server    ${TEST}

Beacon Stability
    [Tags]    stability
    ${stability_args} =    Create Dictionary
    Set To Dictionary    ${stability_args}    RANDOM_BEACON_TYPES    False
    Set To Dictionary    ${stability_args}    TIME_GAP    0.3
    Set To Dictionary    ${stability_args}    STRESS_TEST_NUM_OF_REQ    20
    Set To Dictionary    ${stability_args}    WORKERS    2
    stability workers    ${TEST}    &{stability_args}

BTW, the python script include stability_workers function.
def stability_workers(RANDOM_BEACON_TYPES=True, TIME_GAP=60, STRESS_TEST_NUM_OF_REQ=100000, WORKERS=25):
    s = NewStressTest(RANDOM_BEACON_TYPES, float(TIME_GAP), int(WORKERS), int(STRESS_TEST_NUM_OF_REQ)])

A: You can try below approach
1)Give absolute path in environment variable till BeAm.beacon
2) If 1 is not successfull,Create a environment variable PYTHONPATH and provide the absolute path till BeAm.beacon
This should solve your issue


text:
Q: Is there a way to validate time using Moment JS? Is there a way to validate if the String passed as time is valid using Moment JS?
The operations moment("2014-12-13 asdasd","YYYY-MM-DD LT").isValid() or moment("asdasd","LT").isValid() equate to true which ideally shouldn't happen.
My application uses multiple languages and it is really not possible for me to come up with a RegEx pattern to validate the string. For example, if I get the time string as "午前12時12分0秒", Moment JS should be able to validate this. I checked the source and found that time checking is not that strict in the library. I might have missed something. Please help.

A:

const allPossibleFormats = [
  'D MMMM YYYY',
  'D MMMM YYYY HH:mm',
  'DD-MM-YY',
  'DD-MM-YYYY',
  'DD.MM.YYYY',
  'DD.MM.YYYY HH:mm',
  'DD/MM/YY',
  'DD/MM/YYYY',
  'DD/MM/YYYY HH:mm:ss',
  'HH:mm:ss',
  'M/D/YYYY',
  'D/M/YYYY',
  'MM-DD-YY',
  'MM-DD-YYYY',
  'MM-DD-YYYY HH:mm:ss',
  'MM/DD/YY',
  'MM/DD/YYYY',
  'MM/DD/YYYY HH:mm:ss',
  'MMM D YYYY',
  'MMM D YYYY LT',
  'MMMM Do YYYY',
  'MMMM Do YYYY LT',
  'YYYY-DD-MM HH:mm:ss',
  'YYYY-MM',
  'YYYY-MM-DD',
  'YYYY-MM-DD HH:mm',
  'YYYY-MM-DD HH:mm:ss',
  'YYYY-MM-DD LT',
  'YYYY-MM-DD h:mm:ss A',
  'YYYY-MM-DDTHH:mm:ssZ',
  'ddd, MMM D YYYY LT',
  'dddd D MMMM YYYY HH:mm',
  'dddd, MMMM Do YYYY LT'
];

moment('Chicago Illinois 46702', allPossibleFormats, true).isValid(); // false
moment('18/01/1944', allPossibleFormats, true).isValid(); // true
moment('22-10-2020', allPossibleFormats, true).isValid(); // true
moment('1944-01-18 12:00:00', allPossibleFormats, true).isValid(); // true
moment('2001-01-01 00:00:00', allPossibleFormats, true).isValid(); // true
moment('2001-01', allPossibleFormats, true).isValid(); // true
<script src="https://momentjs.com/downloads/moment.js"></script>

A: As described in the documentation, as of moment 2.3.0, you can pass a third parameter true which turns on "strict parsing" mode.
moment("2014-12-13 asdasd","YYYY-MM-DD LT", true).isValid()   // false

moment("2014-12-13 12:34 PM","YYYY-MM-DD LT", true).isValid()   // true

The down side is that it must match the locale's format (i.e. the one supplied as the second argument) exactly.  Since LT is equivalent to h:mm A in English, it will only accept 12-hour time without seconds.  If you pass 24 hour time, or pass seconds, then it will fail.
moment("2014-12-13 12:34:00 PM","YYYY-MM-DD LT", true).isValid()   // false
moment("2014-12-13 15:00","YYYY-MM-DD LT", true).isValid()         // false

A better solution might be to pass multiple formats with strict parsing:
var formats = ["YYYY-MM-DD LT","YYYY-MM-DD h:mm:ss A","YYYY-MM-DD HH:mm:ss","YYYY-MM-DD HH:mm"];
moment("2014-12-13 12:34 PM", formats, true).isValid()     // true
moment("2014-12-13 15:00", formats, true).isValid()        // true
moment("2014-12-13 12:34:00 PM", formats, true).isValid()  // true


text:
Q: Random freezes at bootup, plus issues with power management on an Asus X556UJ (F556U series) I just bought a new Asus F556U series laptop that dmidecode identifies as X556UJ.
System Information
        Manufacturer: ASUSTeK COMPUTER INC.
        Product Name: X556UJ
        Version: 1.0
        Wake-up Type: Power Switch
        SKU Number: ASUS-NotebookSKU
        Family: X

On this laptop I transferred the Ubuntu 16.04 installation I had on the previous (now broken) laptop.
Bootup freezes
At boot up very often I get random freezes: basically, after the usual Ubuntu splash screen, X won't start and the screen will stay blank.
Power management issues
Suspending to ram freezes the system too. Moreover, the battery indicator never shows when the laptop is being charged with the power cord, it always assumes it's running off the battery even when it's not.

I don't know whether it's related to the issue, but this is what I found in `/var/log/kern.log
[   41.430855] ------------[ cut here ]------------
[   41.430871] WARNING: CPU: 2 PID: 214 at /build/linux-kEu4j9/linux-4.4.0/drivers/gpu/drm/drm_irq.c:1317 drm_wait_one_vblank+0x17b/0x1c0 [drm]()
[   41.430872] vblank not available on crtc 0, ret=-22
[   41.430890] Modules linked in: pci_stub vboxpci(OE) vboxnetadp(OE) vboxnetflt(OE) vboxdrv(OE) binfmt_misc rtsx_usb_ms memstick nvidia_uvm(POE) nvidia_mod
eset(POE) nvidia(POE) uvcvideo videobuf2_vmalloc videobuf2_memops videobuf2_v4l2 videobuf2_core v4l2_common videodev media btusb btrtl snd_soc_skl arc4 snd_soc_skl_ipc rtl8723be snd_hda_ext_core btc
oexist rtl8723_common snd_soc_sst_ipc snd_soc_sst_dsp snd_soc_core intel_rapl rtl_pci rtlwifi snd_hda_codec_hdmi x86_pkg_temp_thermal intel_powerclamp snd_compress ac97_bus coretemp snd_pcm_dmaengin
e snd_hda_codec_realtek dw_dmac_core snd_hda_codec_generic crct10dif_pclmul snd_hda_intel snd_hda_codec crc32_pclmul snd_hda_core joydev mac80211 aesni_intel asus_nb_wmi asus_wmi sparse_keymap mxm_w
mi snd_hwdep cfg80211 aes_x86_64 i2c_designware_platform i2c_designware_core snd_pcm snd_seq_midi snd_seq_midi_event lrw gf128mul glue_helper snd_rawmidi ablk_helper snd_seq wmi cryptd snd_seq_devic
e snd_timer elan_i2c snd input_leds serio_raw kvm_intel kvm intel_lpss_acpi irqbypass int3403_thermal processor_thermal_device idma64 virt_dma hci_uart btbcm btqca int3402_thermal btintel mei_me blu
etooth soundcore acpi_pad intel_lpss_pci intel_lpss mei shpchp int3400_thermal int340x_thermal_zone acpi_thermal_rel tpm_crb intel_soc_dts_iosf mac_hid cuse parport_pc ppdev nfsd lp auth_rpcgss nfs_
acl lockd grace sunrpc parport autofs4 hid_generic usbhid rtsx_usb_sdmmc rtsx_usb uas usb_storage i915_bpo intel_ips i2c_algo_bit drm_kms_helper syscopyarea sysfillrect sysimgblt fb_sys_fops r8169 d
rm mii ahci libahci i2c_hid hid pinctrl_sunrisepoint pinctrl_intel video fjes
[   41.430910] CPU: 2 PID: 214 Comm: plymouthd Tainted: P           OE   4.4.0-25-generic #44-Ubuntu
[   41.430911] Hardware name: ASUSTeK COMPUTER INC. X556UJ/X556UJ, BIOS X556UJ.404 05/09/2016
[   41.430913]  0000000000000286 00000000764b65d7 ffff880035a3b710 ffffffff813eb103
[   41.430913]  ffff880035a3b758 ffffffffc00b6ae8 ffff880035a3b748 ffffffff81081102
[   41.430914]  ffff8800359e5000 0000000000000000 ffff88003542d800 ffff8800359e5368
[   41.430914] Call Trace:
[   41.430918]  [<ffffffff813eb103>] dump_stack+0x63/0x90
[   41.430920]  [<ffffffff81081102>] warn_slowpath_common+0x82/0xc0
[   41.430921]  [<ffffffff8108119c>] warn_slowpath_fmt+0x5c/0x80
[   41.430928]  [<ffffffffc0087054>] ? drm_vblank_get+0x74/0xc0 [drm]
[   41.430933]  [<ffffffffc00872ab>] drm_wait_one_vblank+0x17b/0x1c0 [drm]
[   41.430956]  [<ffffffffc01c7720>] ? gen9_write16+0x380/0x380 [i915_bpo]
[   41.430968]  [<ffffffffc01c7720>] ? gen9_write16+0x380/0x380 [i915_bpo]
[   41.430977]  [<ffffffffc0179b6a>] skl_update_wm+0x4ba/0x5f0 [i915_bpo]
[   41.430986]  [<ffffffffc017d55e>] intel_update_watermarks+0x1e/0x30 [i915_bpo]
[   41.431000]  [<ffffffffc01e9571>] haswell_crtc_enable+0x321/0x8c0 [i915_bpo]
[   41.431013]  [<ffffffffc01e5f28>] intel_atomic_commit+0x5f8/0xdc0 [i915_bpo]
[   41.431023]  [<ffffffffc00a07de>] ? drm_atomic_check_only+0x18e/0x590 [drm]
[   41.431031]  [<ffffffffc00a0c17>] drm_atomic_commit+0x37/0x60 [drm]
[   41.431037]  [<ffffffffc01376ff>] restore_fbdev_mode+0x22f/0x260 [drm_kms_helper]
[   41.431046]  [<ffffffffc009f4aa>] ? drm_modeset_lock_all_ctx+0x9a/0xb0 [drm]
[   41.431050]  [<ffffffffc01398d3>] drm_fb_helper_restore_fbdev_mode_unlocked+0x33/0x80 [drm_kms_helper]
[   41.431053]  [<ffffffffc013994d>] drm_fb_helper_set_par+0x2d/0x50 [drm_kms_helper]
[   41.431066]  [<ffffffffc01fbafa>] intel_fbdev_set_par+0x1a/0x60 [i915_bpo]
[   41.431068]  [<ffffffff8146e416>] fb_set_var+0x236/0x460
[   41.431071]  [<ffffffff810b341a>] ? select_idle_sibling+0x2a/0x120
[   41.431072]  [<ffffffff810b8b34>] ? enqueue_task_fair+0xa4/0x8b0
[   41.431073]  [<ffffffff810b3b35>] ? select_task_rq_fair+0x625/0x700
[   41.431075]  [<ffffffff813b71a3>] ? __blk_run_queue+0x33/0x40
[   41.431076]  [<ffffffff8146470f>] fbcon_blank+0x30f/0x350
[   41.431078]  [<ffffffff814fb833>] do_unblank_screen+0xd3/0x1a0
[   41.431080]  [<ffffffff814f0e9a>] vt_ioctl+0x50a/0x12f0
[   41.431085]  [<ffffffffc0085779>] ? drm_ioctl+0x189/0x540 [drm]
[   41.431087]  [<ffffffff814e436f>] tty_ioctl+0x35f/0xc40
[   41.431089]  [<ffffffff818269f9>] ? schedule_hrtimeout_range_clock+0xb9/0x1b0
[   41.431091]  [<ffffffff8125615b>] ? ep_poll+0x37b/0x3d0
[   41.431093]  [<ffffffff81220acf>] do_vfs_ioctl+0x29f/0x490
[   41.431094]  [<ffffffff810ac010>] ? wake_up_q+0x70/0x70
[   41.431095]  [<ffffffff81220d39>] SyS_ioctl+0x79/0x90
[   41.431095]  [<ffffffff818275f2>] entry_SYSCALL_64_fastpath+0x16/0x71
[   41.431096] ---[ end trace ec72379fbbe6d3b1 ]---

And again:
[   41.446577] ------------[ cut here ]------------
[   41.446588] WARNING: CPU: 2 PID: 214 at /build/linux-kEu4j9/linux-4.4.0/ubuntu/i915/intel_pm.c:3586 skl_update_other_pipe_wm+0x16c/0x180 [i915_bpo]()
[   41.446589] WARN_ON(!wm_changed)
[   41.446600] Modules linked in: pci_stub vboxpci(OE) vboxnetadp(OE) vboxnetflt(OE) vboxdrv(OE) binfmt_misc rtsx_usb_ms memstick nvidia_uvm(POE) nvidia_modeset(POE) nvidia(POE) uvcvideo videobuf2_vmalloc videobuf2_memops videobuf2_v4l2 videobuf2_core v4l2_common videodev media btusb btrtl snd_soc_skl arc4 snd_soc_skl_ipc rtl8723be snd_hda_ext_core btcoexist rtl8723_common snd_soc_sst_ipc snd_soc_sst_dsp snd_soc_core intel_rapl rtl_pci rtlwifi snd_hda_codec_hdmi x86_pkg_temp_thermal intel_powerclamp snd_compress ac97_bus coretemp snd_pcm_dmaengine snd_hda_codec_realtek dw_dmac_core snd_hda_codec_generic crct10dif_pclmul snd_hda_intel snd_hda_codec crc32_pclmul snd_hda_core joydev mac80211 aesni_intel asus_nb_wmi asus_wmi sparse_keymap mxm_wmi snd_hwdep cfg80211 aes_x86_64 i2c_designware_platform i2c_designware_core snd_pcm snd_seq_midi snd_seq_midi_event lrw gf128mul glue_helper snd_rawmidi ablk_helper snd_seq wmi cryptd snd_seq_device snd_timer elan_i2c snd input_leds serio_raw kvm_intel kvm intel_lpss_acpi irqbypass int3403_thermal processor_thermal_device idma64 virt_dma hci_uart btbcm btqca int3402_thermal btintel mei_me bluetooth soundcore acpi_pad intel_lpss_pci intel_lpss mei shpchp int3400_thermal int340x_thermal_zone acpi_thermal_rel tpm_crb intel_soc_dts_iosf mac_hid cuse parport_pc ppdev nfsd lp auth_rpcgss nfs_acl lockd grace sunrpc parport autofs4 hid_generic usbhid rtsx_usb_sdmmc rtsx_usb uas usb_storage i915_bpo intel_ips i2c_algo_bit drm_kms_helper syscopyarea sysfillrect sysimgblt fb_sys_fops r8169 drm mii ahci libahci i2c_hid hid pinctrl_sunrisepoint pinctrl_intel video fjes
[   41.446614] CPU: 2 PID: 214 Comm: plymouthd Tainted: P        W  OE   4.4.0-25-generic #44-Ubuntu
[   41.446614] Hardware name: ASUSTeK COMPUTER INC. X556UJ/X556UJ, BIOS X556UJ.404 05/09/2016
[   41.446615]  0000000000000286 00000000764b65d7 ffff880035a3b690 ffffffff813eb103
[   41.446616]  ffff880035a3b6d8 ffffffffc0247c98 ffff880035a3b6c8 ffffffff81081102
[   41.446617]  ffff88006a530000 ffff8800355b9d9c ffff88006a531000 ffff8800359e5378
[   41.446617] Call Trace:
[   41.446619]  [<ffffffff813eb103>] dump_stack+0x63/0x90
[   41.446620]  [<ffffffff81081102>] warn_slowpath_common+0x82/0xc0
[   41.446621]  [<ffffffff8108119c>] warn_slowpath_fmt+0x5c/0x80
[   41.446630]  [<ffffffffc017969c>] skl_update_other_pipe_wm+0x16c/0x180 [i915_bpo]
[   41.446639]  [<ffffffffc0179836>] skl_update_wm+0x186/0x5f0 [i915_bpo]
[   41.446653]  [<ffffffffc02054ff>] ? intel_ddi_enable_transcoder_func+0x17f/0x260 [i915_bpo]
[   41.446662]  [<ffffffffc017d55e>] intel_update_watermarks+0x1e/0x30 [i915_bpo]
[   41.446675]  [<ffffffffc01e9571>] haswell_crtc_enable+0x321/0x8c0 [i915_bpo]
[   41.446688]  [<ffffffffc01d5bee>] ? intel_finish_crtc_commit+0xe/0x10 [i915_bpo]
[   41.446692]  [<ffffffffc0136434>] ? drm_atomic_helper_commit_planes_on_crtc+0x154/0x270 [drm_kms_helper]
[   41.446705]  [<ffffffffc01e5f28>] intel_atomic_commit+0x5f8/0xdc0 [i915_bpo]
[   41.446714]  [<ffffffffc00a07de>] ? drm_atomic_check_only+0x18e/0x590 [drm]
[   41.446722]  [<ffffffffc00a0c17>] drm_atomic_commit+0x37/0x60 [drm]
[   41.446727]  [<ffffffffc01376ff>] restore_fbdev_mode+0x22f/0x260 [drm_kms_helper]
[   41.446735]  [<ffffffffc009f4aa>] ? drm_modeset_lock_all_ctx+0x9a/0xb0 [drm]
[   41.446739]  [<ffffffffc01398d3>] drm_fb_helper_restore_fbdev_mode_unlocked+0x33/0x80 [drm_kms_helper]
[   41.446742]  [<ffffffffc013994d>] drm_fb_helper_set_par+0x2d/0x50 [drm_kms_helper]
[   41.446755]  [<ffffffffc01fbafa>] intel_fbdev_set_par+0x1a/0x60 [i915_bpo]
[   41.446756]  [<ffffffff8146e416>] fb_set_var+0x236/0x460
[   41.446758]  [<ffffffff810b341a>] ? select_idle_sibling+0x2a/0x120
[   41.446759]  [<ffffffff810b8b34>] ? enqueue_task_fair+0xa4/0x8b0
[   41.446760]  [<ffffffff810b3b35>] ? select_task_rq_fair+0x625/0x700
[   41.446761]  [<ffffffff813b71a3>] ? __blk_run_queue+0x33/0x40
[   41.446763]  [<ffffffff8146470f>] fbcon_blank+0x30f/0x350
[   41.446764]  [<ffffffff814fb833>] do_unblank_screen+0xd3/0x1a0
[   41.446765]  [<ffffffff814f0e9a>] vt_ioctl+0x50a/0x12f0
[   41.446771]  [<ffffffffc0085779>] ? drm_ioctl+0x189/0x540 [drm]
[   41.446772]  [<ffffffff814e436f>] tty_ioctl+0x35f/0xc40
[   41.446774]  [<ffffffff818269f9>] ? schedule_hrtimeout_range_clock+0xb9/0x1b0
[   41.446775]  [<ffffffff8125615b>] ? ep_poll+0x37b/0x3d0
[   41.446776]  [<ffffffff81220acf>] do_vfs_ioctl+0x29f/0x490
[   41.446776]  [<ffffffff810ac010>] ? wake_up_q+0x70/0x70
[   41.446777]  [<ffffffff81220d39>] SyS_ioctl+0x79/0x90
[   41.446778]  [<ffffffff818275f2>] entry_SYSCALL_64_fastpath+0x16/0x71
[   41.446779] ---[ end trace ec72379fbbe6d3b2 ]---

Then this gets printed:
[   42.991165] bbswitch: version 0.8
[   42.991171] bbswitch: Found integrated VGA device 0000:00:02.0: \_SB_.PCI0.GFX0
[   42.991175] bbswitch: Found discrete VGA device 0000:01:00.0: \_SB_.PCI0.RP01.PEGP
[   42.991183] ACPI Warning: \_SB_.PCI0.RP01.PEGP._DSM: Argument #4 type mismatch - Found [Buffer], ACPI requires [Package] (20150930/nsarguments-95)
[   42.991236] bbswitch: detected an Optimus _DSM function
[   42.991243] bbswitch: Succesfully loaded. Discrete card 0000:01:00.0 is on

Subsequently, the laptop either freezes or continues with booting.
I installed the proprietary Nvidia drivers provided with Ubuntu, but the very same issue presented itself also without them.
Notice I had to add the pci=noaer option to the kernel, or else there'd be  a flood of messages as described in bug report #1521173.


text:
Q: How would you implement this Java enum class in Ruby? I have the following code from a Java class:
enum TokenType {
  CHR("[a-z]"),
  INTEGER("[0-9]"),
  OP_EQUALS("\\="),
  OP_PLUS  ("\\+"),
  OP_MINUS("\\-"),
  OP_MULTIPLY("\\*"),
  OP_DIVIDE("\\/"),
  OP_LESS("\\<"),
  LOGIC_AND("and"),
  LOGIC_NOT("not"),
  LOGIC_TRUE("true"),
  LOGIC_FALSE("false"),
  PUNCT_LEFTPAREN("\\("),
  PUNCT_RIGHTPAREN("\\)"),
  PUNCT_SEMIC("\\;"),
  EOF("\\#"),
  ;

  private TokenType(String ch) {
    this.tokenClass = ch;
  }
  String tokenClass;

  public static TokenType parse(String in) {
    for (TokenType type : TokenType.values()) {
      if (in.matches(type.tokenClass)) {
        return type;
      }
    }
    return null;
  }

}

As a Ruby newbie, I am trying to figure out to implement this in Ruby. The more simple the better. I tried the following based on some posts here, but can't seem to get it finished. I want the class to have a parse() method which matches an input string with all the enum options and return a null if none of the patterns match. Here's what I've tried so far:
 class TokenType
  attr_accessor :tokenClass
  def initialize(str)
     @tokenClass = str
  end

    CHR = new("[a-z]")
    INTEGER = new("[0-9]"),
    OP_EQUALS = new("\\="),
    OP_PLUS = new("\\+"),
    OP_MINUS= new("\\-"),
    OP_MULTIPLY= new("\\*"),
    OP_DIVIDE = new("\\/"),
    OP_LESS = new("\\<"),
    LOGIC_AND = new("and"),
    LOGIC_NOT = new("not"),
    LOGIC_TRUE = new("true"),
    LOGIC_FALSE = new("false"),
    PUNCT_LEFTPAREN = new("\\("),
    PUNCT_RIGHTPAREN = new("\\)"),
    PUNCT_SEMIC = new("\\;"),
    EOF= new("\\#"),

    class << self
      private :new
    end

    def TokenType.parse(str_in)

    end
end

Any thoughts or ideas? Thanks.

A: You are trying to write java code with ruby syntax. I would do the following:
def parse str
  case str
  when 'a'..'z' then CHR
  when 0..9 then INTEGER
  …
  end
end

You may decide to define constants within your class or do whatever you want, but matching is done for you by built-in facilities of ruby case clause.


text:
Q: How to solve Firefox border bug without invalid CSS3 code Firefox on Ubuntu adds a dotted border on active elements like input submit if you set a custom border. For example:
<input style="border:1px solid black" type="submit"/>

I opened a bug here, but is there a temporary solution until they fix it without using following invalid css3 code?
input::-moz-focus-inner {
   border: 0;
}

A: If you're talking about this:

then it's expected behavior, that's been in Gecko since the beginning, and I'm not sure why you think it's a bug.
I'm pretty sure you can't disable it without overriding the default stylesheet like you did.


text:
Q: Spyder can't find Enthought packages I am new to python and want to use the Spyder IDE with Enthought's academic distribution. I can get Spyder to run but it can't find the packages such as pandas that comes with the Enthought distribution. I can import pandas when I run python from the shell outside of Spyder. I am using Enthought EPD 7.3 64bit on OSX 10.7.5 and any assistance would be appreciated.

A: To be able to import the packages that come with EDP you have to change your interpreter in
Tools > Preferences > Console > Advanced Settings > Python executable
to select the EPD interpreter, which should be located in
/Library/Frameworks/EPD64.framework/Versions/7.3/bin
However, right now the app has a bug that prevents importing modules of different interpreters.
I'll try to fix it as soon as possible.