Programs & Examples On #Bare

Angular (4, 5, 6, 7) - Simple example of slide in out animation on ngIf

First some code, then the explanaition. The official docs describing this are here.

import { trigger, transition, animate, style } from '@angular/animations'

@Component({
  ...
  animations: [
    trigger('slideInOut', [
      transition(':enter', [
        style({transform: 'translateY(-100%)'}),
        animate('200ms ease-in', style({transform: 'translateY(0%)'}))
      ]),
      transition(':leave', [
        animate('200ms ease-in', style({transform: 'translateY(-100%)'}))
      ])
    ])
  ]
})

In your template:

<div *ngIf="visible" [@slideInOut]>This element will slide up and down when the value of 'visible' changes from true to false and vice versa.</div>

I found the angular way a bit tricky to grasp, but once you understand it, it quite easy and powerful.

The animations part in human language:

  • We're naming this animation 'slideInOut'.
  • When the element is added (:enter), we do the following:
  • ->Immediately move the element 100% up (from itself), to appear off screen.
  • ->then animate the translateY value until we are at 0%, where the element would naturally be.

  • When the element is removed, animate the translateY value (currently 0), to -100% (off screen).

The easing function we're using is ease-in, in 200 milliseconds, you can change that to your liking.

Hope this helps!

How can I regenerate ios folder in React Native project?

It seems like react-native eject is no more available. The only way I could find for recreating the ios folder was to generate it from scratch.

Take a backup of your ios folder

mv /path_to_your_old_project/ios /path_to_your_backup_dir/ios_backup

Navigate to a temporary directory and create a new project with the same name as your current project

react-native init project_name
mv project_name/ios /path_to_your_old_project/ios

Install the pod dependencies inside the ios folder within your project

cd /path_to_your_old_project/ios
pod install

Simple Android RecyclerView example

Dependencies

compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.android.support:multidex:1.0.1'
compile 'com.android.support:cardview-v7:25.3.1'
compile 'com.android.support:support-v4:25.3.1'
compile 'com.lguipeng.bubbleview:library:1.0.0'
compile 'com.larswerkman:HoloColorPicker:1.5'
compile 'com.mcxiaoke.volley:library-aar:1.0.0'

One Class For Click Item

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
    private OnItemClickListener mListener;

    public interface OnItemClickListener {
        public void onItemClick(View view, int position);
    }

    GestureDetector mGestureDetector;

    public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
        mListener = listener;
        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }
        });
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
        View childView = view.findChildViewUnder(e.getX(), e.getY());
        if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
            mListener.onItemClick(childView, view.getChildPosition(childView));
            return true;
        }
        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }


}

Second Class RecyclerView

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;

public class SLByTopics extends Fragment {


    public static ArrayList<MByTopics> byTopicsMainArrayList=new ArrayList<>();


    TabRefreshReceiver tabRefreshReceiver;
    RecyclerView recyclerView;
    SAdpByTopics sAdpByTopics;
    public ArrayList<MByTopics> mByTopicsArrayList=new ArrayList<>();
    ProgressDialog progressDialog;

    public SLByTopics(){
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.sl_fragment_by_topics, container, false);

        progressDialog = new ProgressDialog(getActivity());
        if (IsOnline.isNetworkAvailable(getActivity())) {
            getCategoryTree();
        } else{
            IsOnline.showNoInterNetMessage(getActivity());
        }
        tabRefreshReceiver = new TabRefreshReceiver();
       LocalBroadcastManager.getInstance(getContext()).registerReceiver(tabRefreshReceiver, new IntentFilter("BY_TOPICS"));

        setUpView(view);
        return view;
    }

    private void setUpView(View view) {

        recyclerView=(RecyclerView)view.findViewById(R.id.by_topics_list_recyclerView);
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
    }

    @Override
    public void onResume() {
        super.onResume();

        recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, final int position) {

                if (mByTopicsArrayList.get(position).getChild().size()>0){
                    Intent intent = new Intent(getActivity(), SByTopicCategory.class);
                    intent.putExtra("selectedCategoryName",mByTopicsArrayList.get(position).getCatname());
                    intent.putExtra("jsonData",mByTopicsArrayList.get(position).getMainTopicJson());
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                }else {
                    Intent intent = new Intent(getActivity(), SByCategoryQuestionList.class);
                    intent.putExtra("selectedSubCategoryName",mByTopicsArrayList.get(position).getCatname());
                    intent.putExtra("catID",mByTopicsArrayList.get(position).getId());
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                }
            }
        }));

    }

    private class TabRefreshReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft.detach(SLByTopics.this).attach(SLByTopics.this).commit();
                LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(tabRefreshReceiver);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    private void getCategoryTree() {
        progressDialog.setMessage("Please Wait...");
        progressDialog.setCancelable(false);
        progressDialog.show();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, Const.HOSTNAME + Const.STUDENT_GET_CATEGORY_TREE,
                new Response.Listener<String>() {
                    @SuppressLint("LongLogTag")
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject object = new JSONObject(response);
                            String status = object.getString("status");
                            int i = Integer.parseInt(status);

                            switch (i) {

                                case 0:
                                    progressDialog.dismiss();
//                                    Toast.makeText(getActivity(), "getCategorySuccess", Toast.LENGTH_SHORT).show();
                                    Log.e("getCategoryTree Response", "getCategoryTree Response : " + response);

                                    try {    
                                        byTopicsMainArrayList.clear();
                                        JSONArray info = object.getJSONArray("info");
                                        if (info.length() > 0) {
                                            for (i = 0; i < info.length(); i++) {
                                                JSONObject data = info.getJSONObject(i);
                                                MByTopics mByTopics = new MByTopics();
                                                mByTopics.setId(data.getString("id"));
                                                mByTopics.setCatname(data.getString("catname"));
                                                mByTopics.setMainTopicJson(data.toString());

                                                JSONArray topicChildren = data.getJSONArray("children");
                                                ArrayList<SMByTopicCategory> byChildrenArrayList = new ArrayList<>();

                                                for (int j = 0; j < topicChildren.length(); j++) {
                                                    JSONObject topicChildrenData = topicChildren.getJSONObject(j);
                                                    SMByTopicCategory smByTopicCategory = new SMByTopicCategory();
                                                    smByTopicCategory.setId(topicChildrenData.getString("id"));
                                                    smByTopicCategory.setCatname(topicChildrenData.getString("catname"));
                                                    smByTopicCategory.setChildTopicJson(topicChildrenData.toString());

                                                    JSONArray topicChildrenQuestion = topicChildrenData.getJSONArray("children");
                                                    ArrayList<SMByTopicSubCategory> byChildrenSubArrayList = new ArrayList<>();

                                                    for (int k = 0; k < topicChildrenQuestion.length(); k++) {
                                                        JSONObject topicChildrenSubData = topicChildrenQuestion.getJSONObject(k);
                                                        SMByTopicSubCategory smByTopicSubCategory = new SMByTopicSubCategory();
                                                        smByTopicSubCategory.setId(topicChildrenSubData.getString("id"));
                                                        smByTopicSubCategory.setCatname(topicChildrenSubData.getString("catname"));
                                                        smByTopicSubCategory.setChildSubTopicJson(topicChildrenSubData.toString());

                                                        byChildrenSubArrayList.add(smByTopicSubCategory);
                                                    }

                                                    smByTopicCategory.setQuestions(byChildrenSubArrayList);

                                                    byChildrenArrayList.add(smByTopicCategory);
                                                }
                                                mByTopics.setChild(byChildrenArrayList);
                                                byTopicsMainArrayList.add(mByTopics);
                                            }


                                            mByTopicsArrayList.clear();
                                            mByTopicsArrayList=byTopicsMainArrayList;
                                            sAdpByTopics=new SAdpByTopics(mByTopicsArrayList,getActivity());
                                            recyclerView.setAdapter(sAdpByTopics);
                                            sAdpByTopics.notifyDataSetChanged();

                                        }

                                    }catch (Exception e){
                                        e.printStackTrace();
                                    }
                                    break;

                                default:
                                    progressDialog.dismiss();
//                                    Toast.makeText(getActivity(), "getCategoryError : " + response, Toast.LENGTH_SHORT).show();
                                    Log.e("getCategoryTree Not Response", "getCategoryTree Uploading Not Response : " + response);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        progressDialog.dismiss();
                        Log.e("getCategoryTree Error :","getCategoryTree Error :"+error.getMessage());
//                        Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_LONG).show();
                    }
                }){

        };/* {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                Map<String, String> map = new HashMap<String, String>();
//                map.put("uid", String.valueOf(ConfigManager.getUserId()));
                return map;
            }
        };*/

        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                0,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        requestQueue.add(stringRequest);
    }
}

Adapter Class For Recycler Item

import android.app.Activity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;

public class SAdpByTopics extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        ArrayList<MByTopics> topicsArrayList=new ArrayList<>();
        Activity activity;

     public SAdpByTopics(ArrayList<MByTopics> topicsArrayList,Activity activity){
        this.topicsArrayList=topicsArrayList;
        this.activity=activity;
     }

     @Override
     public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemeView= LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_by_topic_list,parent,false);
        RecyclerView.ViewHolder holder=new Holder(itemeView);
        holder.setIsRecyclable(false);
        return holder;
     }

     @Override
     public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
         final Holder classHolder = (Holder) holder;
         try{
             classHolder.txt_topic_name.setText(topicsArrayList.get(position).getCatname());
         }catch (Exception e){
             e.printStackTrace();
         }
     }

     @Override
     public int getItemCount() {
        return topicsArrayList.size();
     }


class Holder extends RecyclerView.ViewHolder implements View.OnClickListener {
    TextView txt_topic_name;

    public Holder(View itemView) {
        super(itemView);
        txt_topic_name = (TextView) itemView.findViewById(R.id.txt_topic_name);
    }

    @Override
    public void onClick(View v) {

    }
}
}

Module Class

public class MByTopics {

    String id;
    String topicName;
    String catname;
    String MainTopicJson;
    ArrayList<SMByTopicCategory> child;
    ArrayList<SMByTopicSubCategory> questions;

    public void setId(String id){
        this.id=id;
    }
    public String getId(){
        return  id;
    }

    public void setCatname(String catname) {
        this.catname = catname;
    }

    public String getCatname() {
        return catname;
    }

    public void setTopicName(String topicName) {
        this.topicName = topicName;
    }
    public String getTopicName() {
        return topicName;
    }

    public void setChild(ArrayList<SMByTopicCategory> child) {
        this.child = child;
    }

    public String getMainTopicJson() {
        return MainTopicJson;
    }

    public void setMainTopicJson(String mainTopicJson) {
        MainTopicJson = mainTopicJson;
    }

    public ArrayList<SMByTopicCategory> getChild() {
        return child;
    }

    public void setQuestions(ArrayList<SMByTopicSubCategory> questions) {
        this.questions = questions;
    }

    public ArrayList<SMByTopicSubCategory> getQuestions() {
        return questions;
    }

    public ArrayList<MByTopics> getByTopicList() {
        ArrayList<MByTopics> mByTopicsArrayList = new ArrayList<>();

        for (int i=0;i<11;i++){
            MByTopics mQuestionBankCategory=new MByTopics();

            if (i==1 || i== 5|| i==9){
                mQuestionBankCategory.setTopicName("Microeconomics");
            }else  if (i==2 || i== 10|| i==6) {
                mQuestionBankCategory.setTopicName("Macroeconomics");
            }else {
                mQuestionBankCategory.setTopicName("Current Isssues");
            }

            mByTopicsArrayList.add(mQuestionBankCategory);
        }

        return mByTopicsArrayList;
    }

}

Your configuration specifies to merge with the <branch name> from the remote, but no such ref was fetched.?

This is a more common error now as many projects are moving their master branch to another name like main, primary, default, root, reference, latest, etc, as discussed at Github plans to replace racially insensitive terms like ‘master’ and ‘whitelist’.

To fix it, first find out what the project is now using, which you can find via their github, gitlab or other git server.

Then do this to capture the current configuration:

$ git branch -vv
...
* master  968695b [origin/master] Track which contest a ballot was sampled for (#629)
...

Find the line describing the master branch, and note whether the remote repo is called origin, upstream or whatever.

Then using that information, change the branch name to the new one, e.g. if it says you're currently tracking origin/master, substitute main:

git branch master --set-upstream-to origin/main

You can also rename your own branch to avoid future confusion:

git branch -m main

How do I create a master branch in a bare Git repository?

A bare repository is pretty much something you only push to and fetch from. You cannot do much directly "in it": you cannot check stuff out, create references (branches, tags), run git status, etc.

If you want to create a new branch in a bare Git repository, you can push a branch from a clone to your bare repo:

# initialize your bare repo
$ git init --bare test-repo.git

# clone it and cd to the clone's root directory
$ git clone test-repo.git/ test-clone
Cloning into 'test-clone'...
warning: You appear to have cloned an empty repository.
done.
$ cd test-clone

# make an initial commit in the clone
$ touch README.md
$ git add . 
$ git commit -m "add README"
[master (root-commit) 65aab0e] add README
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 README.md

# push to origin (i.e. your bare repo)
$ git push origin master
Counting objects: 3, done.
Writing objects: 100% (3/3), 219 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To /Users/jubobs/test-repo.git/
 * [new branch]      master -> master

Nested Recycler view height doesn't wrap its content

This answer is based on the solution given by Denis Nek. It solves the problem of not taking decorations like dividers into account.

public class WrappingRecyclerViewLayoutManager extends LinearLayoutManager {

public WrappingRecyclerViewLayoutManager(Context context)    {
    super(context, VERTICAL, false);
}

public WrappingRecyclerViewLayoutManager(Context context, int orientation, boolean reverseLayout)    {
    super(context, orientation, reverseLayout);
}

private int[] mMeasuredDimension = new int[2];

@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
    final int widthMode = View.MeasureSpec.getMode(widthSpec);
    final int heightMode = View.MeasureSpec.getMode(heightSpec);
    final int widthSize = View.MeasureSpec.getSize(widthSpec);
    final int heightSize = View.MeasureSpec.getSize(heightSpec);
    int width = 0;
    int height = 0;
    for (int i = 0; i < getItemCount(); i++) {
        measureScrapChild(recycler, i,
                View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                mMeasuredDimension);
        if (getOrientation() == HORIZONTAL) {
            width = width + mMeasuredDimension[0];
            if (i == 0) {
                height = mMeasuredDimension[1];
            }
        } else {
            height = height + mMeasuredDimension[1];
            if (i == 0) {
                width = mMeasuredDimension[0];
            }
        }
    }
    switch (widthMode) {
        case View.MeasureSpec.EXACTLY:
            width = widthSize;
        case View.MeasureSpec.AT_MOST:
        case View.MeasureSpec.UNSPECIFIED:
    }

    switch (heightMode) {
        case View.MeasureSpec.EXACTLY:
            height = heightSize;
        case View.MeasureSpec.AT_MOST:
        case View.MeasureSpec.UNSPECIFIED:
    }

    setMeasuredDimension(width, height);
}

private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec, int heightSpec, int[] measuredDimension) {
    View view = recycler.getViewForPosition(position);
    if (view != null) {
        RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
        int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec, getPaddingLeft() + getPaddingRight(), p.width);
        int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec, getPaddingTop() + getPaddingBottom(), p.height);
        view.measure(childWidthSpec, childHeightSpec);
        Rect outRect = new Rect();
        calculateItemDecorationsForChild(view, outRect);
        measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
        measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin + outRect.bottom + outRect.top;
        recycler.recycleView(view);
    }
}

}

How can I inspect the file system of a failed `docker build`?

The top answer works in the case that you want to examine the state immediately prior to the failed command.

However, the question asks how to examine the state of the failed container itself. In my situation, the failed command is a build that takes several hours, so rewinding prior to the failed command and running it again takes a long time and is not very helpful.

The solution here is to find the container that failed:

$ docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                          PORTS               NAMES
6934ada98de6        42e0228751b3        "/bin/sh -c './utils/"   24 minutes ago      Exited (1) About a minute ago                       sleepy_bell

Commit it to an image:

$ docker commit 6934ada98de6
sha256:7015687976a478e0e94b60fa496d319cdf4ec847bcd612aecf869a72336e6b83

And then run the image [if necessary, running bash]:

$ docker run -it 7015687976a4 [bash -il]

Now you are actually looking at the state of the build at the time that it failed, instead of at the time before running the command that caused the failure.

Changing Placeholder Text Color with Swift

This code is working in Swift3:

yourTextFieldName .setValue(UIColor.init(colorLiteralRed: 80/255, green: 80/255, blue: 80/255, alpha: 1.0), forKeyPath: "_placeholderLabel.textColor")

let me know if you have any issue.

Bootstrap 3, 4 and 5 .container-fluid with grid adding unwanted padding

I think no one has given the correct answer to the question. My working solution is : 1. Just declare another class along with container-fluid class example(.maxx):

_x000D_
_x000D_
 <div class="container-fluid maxx">_x000D_
   <div class="row">_x000D_
     <div class="col-sm-12">_x000D_
     <p>Hello</p>_x000D_
     </div>_x000D_
   </div>_x000D_
  </div>
_x000D_
_x000D_
_x000D_

  1. Then using specificity in the css part do this:

_x000D_
_x000D_
.container-fluid.maxx {_x000D_
  padding-left: 0px;_x000D_
  padding-right: 0px; }
_x000D_
_x000D_
_x000D_

This will work 100% and will remove the padding from left and right. I hope this helps.

git repo says it's up-to-date after pull but files are not updated

For me my forked branch was not in sync with the master branch. So I went to bitbucket and synced and merged my forked branch and then tried to take the pull. Then it worked fine.

Start redis-server with config file

I think that you should make the reference to your config file

26399:C 16 Jan 08:51:13.413 # Warning: no config file specified, using the default config. In order to specify a config file use ./redis-server /path/to/redis.conf

you can try to start your redis server like

./redis-server /path/to/redis-stable/redis.conf

Is Laravel really this slow?

I know this is a little old question, but things changed. Laravel isn't that slow. It's, as mentioned, synced folders are slow. However, on Windows 10 I wasn't able to use rsync. I tried both cygwin and minGW. It seems like rsync is incompatible with git for windows's version of ssh.

Here is what worked for me: NFS.

Vagrant docs says:

NFS folders do not work on Windows hosts. Vagrant will ignore your request for NFS synced folders on Windows.

This isn't true anymore. We can use vagrant-winnfsd plugin nowadays. It's really simple to install:

  1. Execute vagrant plugin install vagrant-winnfsd
  2. Change in your Vagrantfile: config.vm.synced_folder ".", "/vagrant", type: "nfs"
  3. Add to Vagrantfile: config.vm.network "private_network", type: "dhcp"

That's all I needed to make NFS work. Laravel response time decreased from 500ms to 100ms for me.

How to run Gulp tasks sequentially one after the other

Try this hack :-) Gulp v3.x Hack for Async bug

I tried all of the "official" ways in the Readme, they didn't work for me but this did. You can also upgrade to gulp 4.x but I highly recommend you don't, it breaks so much stuff. You could use a real js promise, but hey, this is quick, dirty, simple :-) Essentially you use:

var wait = 0; // flag to signal thread that task is done
if(wait == 0) setTimeout(... // sleep and let nodejs schedule other threads

Check out the post!

Application not picking up .css file (flask/python)

If any of the above method is not working and you code is perfect then try hard refreshing by pressing Ctrl + F5. It will clear all the chaces and then reload file. It worked for me.

Why not inherit from List<T>?

If your class users need all the methods and properties** List has, you should derive your class from it. If they don't need them, enclose the List and make wrappers for methods your class users actually need.

This is a strict rule, if you write a public API, or any other code that will be used by many people. You may ignore this rule if you have a tiny app and no more than 2 developers. This will save you some time.

For tiny apps, you may also consider choosing another, less strict language. Ruby, JavaScript - anything that allows you to write less code.

PLS-00103: Encountered the symbol "CREATE"

At line 5 there is a / missing.

There is a good answer on the differences between ; and / here.

Basically, when running a CREATE block via script, you need to use / to let SQLPlus know when the block ends, since a PL/SQL block can contain many instances of ;.

Cannot ignore .idea/workspace.xml - keeps popping up

I was facing the same issue, and it drove me up the wall. The issue ended up to be that the .idea folder was ALREADY commited into the repo previously, and so they were being tracked by git regardless of whether you ignored them or not. I would recommend the following, after closing RubyMine/IntelliJ or whatever IDE you are using:

mv .idea ../.idea_backup
rm .idea # in case you forgot to close your IDE
git rm -r .idea 
git commit -m "Remove .idea from repo"
mv ../.idea_backup .idea

After than make sure to ignore .idea in your .gitignore

Although it is sufficient to ignore it in the repository's .gitignore, I would suggest that you ignore your IDE's dotfiles globally.

Otherwise you will have to add it to every .gitgnore for every project you work on. Also, if you collaborate with other people, then its best practice not to pollute the project's .gitignore with private configuation that are not specific to the source-code of the project.

How to fix corrupted git repository?

Here's a script (bash) to automate the first solution by @CodeGnome to restore from a backup (run from the top level of the corrupted repo). The backup doesn't need to be complete, it only needs to have the missing objects.

git fsck 2>&1 | grep -e missing -e invalid | awk '{print $NF}' | sort -u |
    while read entry; do
        mkdir -p .git/objects/${entry:0:2}
        cp ${BACKUP}/objects/${entry:0:2}/${entry:2} .git/objects/${entry:0:2}/${entry:2}
    done

How to scale Docker containers in production

While we're big fans of Deis (deis.io) and are actively deploying to it, there are other Heroku like PaaS style deployment solutions out there, including:

Longshoreman from the Wayfinder folks:

https://github.com/longshoreman/longshoreman

Decker from the CloudCredo folks, using CloudFoundry:

http://www.cloudcredo.com/decker-docker-cloud-foundry/

As for straight up orchestration, NewRelic's opensource Centurion project seems quite promising:

https://github.com/newrelic/centurion

Git push results in "Authentication Failed"

For me, I forgot that I had changed the password on Github.com, and my keychain for shell authentication never updated to that new password. Deleting everything git from my keychain and then re-running the git request helped solve the issue, prompting me again for the new password.

How to POST the data from a modal form of Bootstrap?

You CAN include a modal within a form. In the Bootstrap documentation it recommends the modal to be a "top level" element, but it still works within a form.

You create a form, and then the modal "save" button will be a button of type="submit" to submit the form from within the modal.

<form asp-action="AddUsersToRole" method="POST" class="mb-3">

    @await Html.PartialAsync("~/Views/Users/_SelectList.cshtml", Model.Users)

    <div class="modal fade" id="role-select-modal" tabindex="-1" role="dialog" aria-labelledby="role-select-modal" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Select a Role</h5>
                </div>
                <div class="modal-body">
                    ...
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Add Users to Role</button>
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                </div>
            </div>
        </div>
    </div>

</form>

You can post (or GET) your form data to any URL. By default it is the serving page URL, but you can change it by setting the form action. You do not have to use ajax.

Mozilla documentation on form action

How to check if a json key exists?

you could JSONObject#has, providing the key as input and check if the method returns true or false. You could also

use optString instead of getString:

Returns the value mapped by name if it exists, coercing it if necessary. Returns the empty string if no such mapping exists

Error LNK2019: Unresolved External Symbol in Visual Studio

When you have everything #included, an unresolved external symbol is often a missing * or & in the declaration or definition of a function.

Embed Youtube video inside an Android app

It works like this:

String item = "http://www.youtube.com/embed/";

String ss = "your url";
ss = ss.substring(ss.indexOf("v=") + 2);
item += ss;
DisplayMetrics metrics = getResources().getDisplayMetrics();
int w1 = (int) (metrics.widthPixels / metrics.density), h1 = w1 * 3 / 5;
wv.getSettings().setJavaScriptEnabled(true);
wv.setWebChromeClient(chromeClient);
wv.getSettings().setPluginsEnabled(true);

try {
    wv.loadData(
    "<html><body><iframe class=\"youtube-player\" type=\"text/html5\" width=\""
    + (w1 - 20)
    + "\" height=\""
    + h1
    + "\" src=\""
    + item
    + "\" frameborder=\"0\"\"allowfullscreen\"></iframe></body></html>",
                            "text/html5", "utf-8");
} catch (Exception e) {
    e.printStackTrace();
}

private WebChromeClient chromeClient = new WebChromeClient() {

    @Override
    public void onShowCustomView(View view, CustomViewCallback callback) {
        super.onShowCustomView(view, callback);
        if (view instanceof FrameLayout) {
            FrameLayout frame = (FrameLayout) view;
            if (frame.getFocusedChild() instanceof VideoView) {
                VideoView video = (VideoView) frame.getFocusedChild();
                frame.removeView(video);
                video.start();
            }
        }

    }
};

OnClickListener in Android Studio

This worked for me:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_newarea);

    btnSave = (Button)findViewById(R.id.btnSave);

    OnClickListener btnListener = new OnClickListener() {
        @Override
        public void onClick(android.view.View view) {
            finish();
        }
    };
    btnSave.setOnClickListener(btnListener);

}

Colorplot of 2D array matplotlib

I'm afraid your posted example is not working, since X and Y aren't defined. So instead of pcolormesh let's use imshow:

import numpy as np
import matplotlib.pyplot as plt

H = np.array([[1, 2, 3, 4],
              [5, 6, 7, 8],
              [9, 10, 11, 12],
              [13, 14, 15, 16]])  # added some commas and array creation code

fig = plt.figure(figsize=(6, 3.2))

ax = fig.add_subplot(111)
ax.set_title('colorMap')
plt.imshow(H)
ax.set_aspect('equal')

cax = fig.add_axes([0.12, 0.1, 0.78, 0.8])
cax.get_xaxis().set_visible(False)
cax.get_yaxis().set_visible(False)
cax.patch.set_alpha(0)
cax.set_frame_on(False)
plt.colorbar(orientation='vertical')
plt.show()

Android WebView not loading URL

Use this it should help.

 var currentUrl = "google.com" 
 var partOfUrl = currentUrl.substring(0, currentUrl.length-2)

 webView.setWebViewClient(object: WebViewClient() {

 override fun onLoadResource(WebView view, String url) {
 //call loadUrl() method  here 
 // also check if url contains partOfUrl, if not load it differently.
 if(url.contains(partOfUrl, true)) {
     //it should work if you reach inside this if scope.
 } else if(!(currentUrl.startWith("w", true))) {
     webView.loadurl("www.$currentUrl")

 } else if(!(currentUrl.startWith("h", true))) {
     webView.loadurl("https://$currentUrl")

 } else { 
   //...
 }
 }

 override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
  // you can call again loadUrl from here too if there is any error.
}
 // You should also override other override method for error such as
 // onReceiveError to see how all these methods are called one after another and how
// they behave while debugging with break point. 
} 

fatal: 'origin' does not appear to be a git repository

This does not answer your question, but I faced a similar error message but due to a different reason. Allow me to make my post for the sake of information collection.

I have a git repo on a network drive. Let's call this network drive RAID. I cloned this repo on my local machine (LOCAL) and on my number crunching cluster (CRUNCHER). For convenience I mounted the user directory of my account on CRUNCHER on my local machine. So, I can manipulate files on CRUNCHER without the need to do the work in an SSH terminal.

Today, I was modifying files in the repo on CRUNCHER via my local machine. At some point I decided to commit the files, so a did a commit. Adding the modified files and doing the commit worked as I expected, but when I called git push I got an error message similar to the one posted in the question.

The reason was, that I called push from within the repo on CRUNCHER on LOCAL. So, all paths in the config file were plain wrong.

When I realized my fault, I logged onto CRUNCHER via Terminal and was able to push the commit.

Feel free to comment if my explanation can't be understood, or you find my post superfluous.

fatal: bad default revision 'HEAD'

I got the same error and couldn't solve it.

Then I noticed 3 extra files in one of my directories.

The files were named:

config, HEAD, description

I deleted the files, and the error didn't appear.

config contained:

[core]
    repositoryformatversion = 0
    filemode = true
    bare = true

HEAD contained:

ref: refs/heads/master

description contained:

Unnamed repository; edit this file 'description' to name the repository.

Object Library Not Registered When Adding Windows Common Controls 6.0

I have been having the same problem. VB6 Win7 64 bit and have come across a very simple solution, so I figured it would be a good idea to share it here in case it helps anyone else.

First I have tried the following with no success:

  • unregistered and re-registering MSCOMCTL, MSCOMCTL2 and the barcode active X controls in every directory I could think of trying (VB98, system 32, sysWOW64, project folder.)

  • Deleting working folder and getting everything again. (through source safe)

  • Copying the OCX files from a machine with no problems and registering those.

  • Installing service pack 6

  • Installing MZ tools - it was worth a try

  • Installing the distributable version of the project.

  • Manually editing the vbp file (after making it writeable) to amend/remove the references and generally fiddling.

  • Un-Installing VB6 and re-Installing (this I thought was a last resort) The problem was occurring on a new project and not just existing ones.

NONE of the above worked but the following did

Open VB6
New project
>Project
    >Components
        Tick the following:
            Microsoft flexigrid control 6.0 (sp6)
            Microsoft MAPI controls 6.0
            Microsoft Masked Edit Control 6.0 (sp3)
            Microsoft Tabbed Dialog Control 6.0 (sp6)
        >Apply

After this I could still not tick the Barcode Active X or the windows common contols 6.0 and windows common controls 2 6.0, but when I clicked apply, the message changed from unregistered, to that it was already in the project.

>exit the components dialog and then load project. 

This time it worked. Tried the components dialog again and the missing three were now ticked. Everything seems fine now.

Git push error: "origin does not appear to be a git repository"

As it has already been mentioned in che's answer about adding the remote part, which I believe you are still missing.

Regarding your edit for adding remote on your local USB drive. First of all you must have a 'bare repository' if you want your repository to be a shared repository i.e. to be able to push/pull/fetch/merge etc..

To create a bare/shared repository, go to your desired location. In your case:

$ cd /Volumes/500gb/   
$ git init --bare myproject.git

See here for more info on creating bare repository

Once you have a bare repository set up in your desired location you can now add it to your working copy as a remote.

$ git remote add origin /Volumes/500gb/myproject.git

And now you can push your changes to your repository

$ git push origin master

modal View controllers - how to display and dismiss

I have solved the issue by using UINavigationController when presenting. In MainVC, when presenting VC1

let vc1 = VC1()
let navigationVC = UINavigationController(rootViewController: vc1)
self.present(navigationVC, animated: true, completion: nil)

In VC1, when I would like to show VC2 and dismiss VC1 in same time (just one animation), I can have a push animation by

let vc2 = VC2()
self.navigationController?.setViewControllers([vc2], animated: true)

And in VC2, when close the view controller, as usual we can use:

self.dismiss(animated: true, completion: nil)

Launch iOS simulator from Xcode and getting a black screen, followed by Xcode hanging and unable to stop tasks

Surprisingly, what worked for me was going to iOS Simulator menu, and pressing "Reset Content and Settings". (in iOS 13, its under Hardware)

Why Git is not allowing me to commit even after configuration?

I had this problem even after setting the config properly. git config

My scenario was issuing git command through supervisor (in Linux). On further debugging, supervisor was not reading the git config from home folder. Hence, I had to set the environment HOME variable in the supervisor config so that it can locate the git config correctly. It's strange that supervisor was not able to locate the git config just from the username configured in supervisor's config (/etc/supervisor/conf.d).

How to disable CSS in Browser for testing purposes

Another way to achieve @David Baucum's solution in fewer steps:

  1. Right click -> inspect element
  2. Click on the stylesheet's name that affect your element (just on the right side of the declaration)
  3. Highlight all of the text and hit delete.

It could be handier in some cases.

Example of Named Pipes

You can actually write to a named pipe using its name, btw.

Open a command shell as Administrator to get around the default "Access is denied" error:

echo Hello > \\.\pipe\PipeName

fatal: Unable to create temporary file '/home/username/git/myrepo.git/./objects/pack/tmp_pack_XXXXXX': Permission denied

A possibility is that the git server you are pushing to is down/crashed, and the solution lies in restarting the git server.

Installing packages in Sublime Text 2

With Package Control in Sublime Text 2, you really need to become cozy with a couple of different things to make it all work:

  1. Always look up a package in the wbond community. There you'll be able to see how many people have installed that package (the more popular, the better) as well as the documentation on the package (if any).
  2. Menu Items under Prefs > Package Control. Here you can install, remove or see a list of all installed packages.
  3. Prefs > Package Settings. Here you'll find the settings that can be tinkered with as well as shortcut keys that are available. Make sure to make any changes in the User Settings, rather than the Default Settings. Otherwise, your settings will be overwritten when that package is updated.
  4. CTRL+SHIFT+P. This will bring up a menu where you can look up a lot of the functions your installed packages can do. Just start typing and it will start filtering.

Converting Integers to Roman Numerals - Java

I think if you study the theory of roman numerals carefully you don't require mappings for numbers 4,9,40 etc because the theory tells us if the roman numeral is IV = 5-1 = 4, hence when the prefix is smaller than the succeeding number in that case you have to subtract the former number from the succeeding number to get the actual value and this is what I have incorporated into my code for the problem, take a look and point out any mistakes if necessary, I followed this table to devise my logic - http://literacy.kent.edu/Minigrants/Cinci/romanchart.htm

import java.util.Set;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedReader;

public class RomanStringToIntegerConversion {
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in)));
        String[] romanString = br.readLine().split("");

        HashMap<String, Integer> romanToIntegerMap = new HashMap<String, Integer>();
        romanToIntegerMap.put("I", 1);
        romanToIntegerMap.put("V", 5);
        romanToIntegerMap.put("X", 10);
        romanToIntegerMap.put("L", 50);
        romanToIntegerMap.put("C", 100);
        romanToIntegerMap.put("D", 500);
        romanToIntegerMap.put("M", 1000);

        int numLength = romanString.length;
        Set<Integer> lessIndices = new HashSet<Integer>();

        for(int i = 0; i < numLength; ++i){
            if(i+1 < numLength){
                if(romanToIntegerMap.get(romanString[i]) < romanToIntegerMap.get(romanString[i+1]))
                    lessIndices.add(i);
            }
        }

        int num = 0;
        for(int i = 0; i < numLength;){
            if(!lessIndices.contains(i)){
                num = num + romanToIntegerMap.get(romanString[i]);
                ++i;
            }
            else{
                num = num + romanToIntegerMap.get(romanString[i+1]) - romanToIntegerMap.get(romanString[i]);
                i+=2;
            }
        }
        System.out.println("The integer representation of the roman numeral is : " + num);
    }
}

Python Matplotlib figure title overlaps axes label when using twiny

I'm not sure whether it is a new feature in later versions of matplotlib, but at least for 1.3.1, this is simply:

plt.title(figure_title, y=1.08)

This also works for plt.suptitle(), but not (yet) for plt.xlabel(), etc.

Java - Getting Data from MySQL database

Here is what I just did right now:

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.sun.javafx.runtime.VersionInfo;  

public class ConnectToMySql {
public static ConnectBean dataBean = new ConnectBean();

public static void main(String args[]) {
    getData();
    }



public static void getData () {

    try {
        Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewpage", 
 "root", "root");
        
 // here mynewpage is database name, root is username and password
    
Statement stmt = con.createStatement();
        System.out.println("stmt  " + stmt);
        ResultSet rs = stmt.executeQuery("select * from carsData");
        System.out.println("rs  " + rs);
        int count = 1;
        while (rs.next()) {
            String vehicleType = rs.getString("VHCL_TYPE");
            System.out.println(count  +": " + vehicleType);
            count++;

        }

        con.close();
    } catch (Exception e) {
        Logger lgr = Logger.getLogger(VersionInfo.class.getName());
        lgr.log(Level.SEVERE, e.getMessage(), e);

        System.out.println(e.getMessage());
    }
    
    
}

}

The Above code will get you the first column of the table you have.

This is the table which you might need to create in your MySQL database

CREATE TABLE
carsData
(
    VHCL_TYPE CHARACTER(10) NOT NULL,
);

Git Push error: refusing to update checked out branch

Maybe your remote repo is in the branch which you want to push. You can try to checkout another branch in your remote machine. I did this, than these error disappeared, and I pushed success to my remote repo. Notice that I use ssh to connect my own server instead of github.com.

apache not accepting incoming connections from outside of localhost

Try with below setting in iptables.config table

iptables -A INPUT -p tcp --dport 80 -j ACCEPT

Run the below command to restart the iptable service

service iptables restart

change the httpd.config file to

Listen 192.170.2.1:80

re-start the apache.

Try now.

Executing Javascript from Python

Using PyV8, I can do this. However, I have to replace document.write with return because there's no DOM and therefore no document.

import PyV8
ctx = PyV8.JSContext()
ctx.enter()

js = """
function escramble_758(){
var a,b,c
a='+1 '
b='84-'
a+='425-'
b+='7450'
c='9'
document.write(a+c+b)
}
escramble_758()
"""

print ctx.eval(js.replace("document.write", "return "))

Or you could create a mock document object

class MockDocument(object):

    def __init__(self):
        self.value = ''

    def write(self, *args):
        self.value += ''.join(str(i) for i in args)


class Global(PyV8.JSClass):
    def __init__(self):
        self.document = MockDocument()

scope = Global()
ctx = PyV8.JSContext(scope)
ctx.enter()
ctx.eval(js)
print scope.document.value

ssh_exchange_identification: Connection closed by remote host under Git bash

Disconnecting and reconnecting to the current network worked for me.

No connection could be made because the target machine actively refused it 127.0.0.1:3446

Check if any other program is using that port.

If an instance of the same program is still active, kill that process.

How do I force git pull to overwrite everything on every pull?

You could try this:

git reset --hard HEAD
git pull

(from How do I force "git pull" to overwrite local files?)

Another idea would be to delete the entire git and make a new clone.

fatal: This operation must be run in a work tree

You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree option for single commands, or the GIT_WORK_TREE environment variable. There is also the core.worktree configuration option but it will not work in a bare repository (check the man page for what it does).

# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status

fatal: Not a valid object name: 'master'

When I git init a folder it doesn't create a master branch

This is true, and expected behaviour. Git will not create a master branch until you commit something.

When I do git --bare init it creates the files.

A non-bare git init will also create the same files, in a hidden .git directory in the root of your project.

When I type git branch master it says "fatal: Not a valid object name: 'master'"

That is again correct behaviour. Until you commit, there is no master branch.

You haven't asked a question, but I'll answer the question I assumed you mean to ask. Add one or more files to your directory, and git add them to prepare a commit. Then git commit to create your initial commit and master branch.

How to pass html string to webview on android

To load your data in WebView. Call loadData() method of WebView

webView.loadData(yourData, "text/html; charset=utf-8", "UTF-8");

You can check this example

http://developer.android.com/reference/android/webkit/WebView.html

Neither BindingResult nor plain target object for bean name available as request attribute

I had a similar problem in IntelliJ IDEA. My code was 100% correct, but after starting the Tomcat, you receive an exception. java.lang.IllegalStateException: Neither BindingResult

I just removed and added again Tomcat configuration. And it worked for me.

A picture Tomcat configuration

enter image description here

Facebook page automatic "like" URL (for QR Code)

In my opinion, it is not possible for the like button (and I hope it is not possible).

But, you can trigger a custom OpenGraph v2 action, or display a like button linked to your facebook page.

Git on Bitbucket: Always asked for password, even after uploading my public SSH key

You may need to double-check your SSH identities file. You may be guiding BitBucket to look at a different/incorrect private key to the equivalent public key that you have saved on BitBucket.

Check it with tail ~/.ssh/config - you will see something similar to:

Host bitbucket.org
 HostName bitbucket.org
 IdentityFile ~/.ssh/personal-bitbucket-ssh-key

Remember, that adding additional identities (such as work and home) can be done with the ssh-add command, for example:

ssh-keygen -t rsa -C "companyName" -f "companyName"
ssh-add ~/.ssh/companyName

Once you have confirmed which private key is being looked at locally, you can then take your public equivalent, in this case:

cat ~/.ssh/personal-bitbucket-ssh-key.pub | pbcopy

And paste that cipher onto BitBucket. Your git pushes will now (provided you are using the SSH clone as aforementioned answers have pointed out) be allowed without a password, as your device is a recognised friendly.

Hopefully this helps clear it up for someone.

How do you use "git --bare init" repository?

You can execute the following commands to initialize your local repository

mkdir newProject
cd newProject
touch .gitignore
git init
git add .
git commit -m "Initial Commit"
git remote add origin user@host:~/path_on_server/newProject.git
git push origin master

You should work on your project from your local repository and use the server as the central repository.

You can also follow this article which explains each and every aspect of creating and maintaining a Git repository. Git for Beginners

Parsing arguments to a Java command line program

You could use https://github.com/jankroken/commandline , here's how to do that:

To make this example work, I must make assumptions about what the arguments means - just picking something here...

-r opt1 => replyAddress=opt1
-S opt2 arg1 arg2 arg3 arg4 => subjects=[opt2,arg1,arg2,arg3,arg4]
--test = test=true (default false)
-A opt3 => address=opt3

this can then be set up this way:

public class MyProgramOptions {
  private String replyAddress;
  private String address;
  private List<String> subjects;
  private boolean test = false;

  @ShortSwitch("r")
  @LongSwitch("replyAddress") // if you also want a long variant. This can be skipped
  @SingleArgument
  public void setReplyAddress(String replyAddress) {
    this.replyAddress = replyAddress;
  }

  @ShortSwitch("S")
  @AllAvailableArguments
  public void setSubjects(List<String> subjects) {
    this.subjects = subjects;
  }

  @LongSwitch("test")
  @Toggle(true)
  public void setTest(boolean test) {
    this.test = test;
  }

  @ShortSwitch("A")
  @SingleArgument
  public void setAddress(String address) {
    this.address = address;
  }

  // getters...
}

and then in the main method, you can just do:

public final static void main(String[] args) {
  try {
    MyProgramOptions options = CommandLineParser.parse(MyProgramOptions.class, args, OptionStyle.SIMPLE);

    // and then you can pass options to your application logic...

  } catch
    ...
  }
}

Setting up a git remote origin

Using SSH

git remote add origin ssh://login@IP/path/to/repository

Using HTTP

git remote add origin http://IP/path/to/repository

However having a simple git pull as a deployment process is usually a bad idea and should be avoided in favor of a real deployment script.

Is it safe to shallow clone with --depth 1, create commits, and pull updates again?

Note that Git 1.9/2.0 (Q1 2014) has removed that limitation.
See commit 82fba2b, from Nguy?n Thái Ng?c Duy (pclouds):

Now that git supports data transfer from or to a shallow clone, these limitations are not true anymore.

The documentation now reads:

--depth <depth>::

Create a 'shallow' clone with a history truncated to the specified number of revisions.

That stems from commits like 0d7d285, f2c681c, and c29a7b8 which support clone, send-pack /receive-pack with/from shallow clones.
smart-http now supports shallow fetch/clone too.

All the details are in "shallow.c: the 8 steps to select new commits for .git/shallow".

Update June 2015: Git 2.5 will even allow for fetching a single commit!
(Ultimate shallow case)


Update January 2016: Git 2.8 (Mach 2016) now documents officially the practice of getting a minimal history.
See commit 99487cf, commit 9cfde9e (30 Dec 2015), commit 9cfde9e (30 Dec 2015), commit bac5874 (29 Dec 2015), and commit 1de2e44 (28 Dec 2015) by Stephen P. Smith (``).
(Merged by Junio C Hamano -- gitster -- in commit 7e3e80a, 20 Jan 2016)

This is "Documentation/user-manual.txt"

A <<def_shallow_clone,shallow clone>> is created by specifying the git-clone --depth switch.
The depth can later be changed with the git-fetch --depth switch, or full history restored with --unshallow.

Merging inside a <<def_shallow_clone,shallow clone>> will work as long as a merge base is in the recent history.
Otherwise, it will be like merging unrelated histories and may have to result in huge conflicts.
This limitation may make such a repository unsuitable to be used in merge based workflows.

Update 2020:

  • git 2.11.1 introduced option git fetch --shallow-exclude= to prevent fetching all history
  • git 2.11.1 introduced option git fetch --shallow-since= to prevent fetching old commits.

For more on the shallow clone update process, see "How to update a git shallow clone?".


As commented by Richard Michael:

to backfill history: git pull --unshallow

And Olle Härstedt adds in the comments:

To backfill part of the history: git fetch --depth=100.

Return Type for jdbcTemplate.queryForList(sql, object, classType)

queryForList returns a List of LinkedHashMap objects.

You need to cast it first like this:


    List list = jdbcTemplate.queryForList(...);
    for (Object o : list) {
       Map m = (Map) o;
       ...
    }

Parsing JSON using C

You can have a look at Jansson

The website states the following: Jansson is a C library for encoding, decoding and manipulating JSON data. It features:

  • Simple and intuitive API and data model
  • Can both encode to and decode from JSON
  • Comprehensive documentation
  • No dependencies on other libraries
  • Full Unicode support (UTF-8)
  • Extensive test suite

T-SQL query to show table definition?

I know it's an old question, but exactly what I was looking for. Because I want to batch script some tables, I rewrote the C# code from Anthony Faull for PowerShell.

This one is uses Integrated Security:

Import-Module sqlps

$serverInstance = "<server>"
$database = "<database>"
$table = "<table>"
$schema = "<schema>"

$options = New-Object -TypeName Microsoft.SqlServer.Management.Smo.ScriptingOptions
$options.DriAll = $true
$options.SchemaQualify = $true

$connection = New-Object -TypeName Microsoft.SqlServer.Management.Common.ServerConnection `
    -ArgumentList $serverInstance
$server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server `
    -ArgumentList $connection

$server.Databases.Item($database).Tables.Item($table, $schema).Script($options) `
    | ForEach-Object -Process { $_ + "`nGO"}

And here with username and password:

Import-Module sqlps

$serverInstance = "<server>"
$user = "<user>"
$password = "<pasword>"
$database = "<database>"
$table = "<table>"
$schema = "<schema>"

$options = New-Object -TypeName Microsoft.SqlServer.Management.Smo.ScriptingOptions
$options.DriAll = $true
$options.SchemaQualify = $true

$connection = New-Object -TypeName Microsoft.SqlServer.Management.Common.ServerConnection `
    -ArgumentList $serverInstance
$connection.LoginSecure = $false
$connection.Login = $user
$connection.Password = $password
$server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server `
    -ArgumentList $connection

$server.Databases.Item($database).Tables.Item($table, $schema).Script($options) `
    | ForEach-Object -Process { $_ + "`nGO"}

git clone through ssh

I did : git clone --bare "/GITREPOSITORIES/RepoA" "ssh://luc@EERSTENASDS119J/volume1/RepoA" Result : fatal: destination path 'ssh://luc@EERSTENASDS119J/volume1/RepoA' already exists and is not an empty directory.

The system created a directory ssh://luc@EERSTENASDS119J/volume1/RepoA in my current path.

So git clone did not interpret the URL specification. Used the workaround of Alec.

Why can't I push to this bare repository?

If you:

 git push origin master

it will push to the bare repo.

It sounds like your alice repo isn't tracking correctly.

cat .git/config

This will show the default remote and branch.

If you

 git push -u origin master

You should start tracking that remote and branch. I'm not sure if that option has always been in git.

How to update a git clone --mirror?

See here: Git doesn't clone all branches on subsequent clones?

If you really want this by pulling branches instead of push --mirror, you can have a look here:

"fetch --all" in a git bare repository doesn't synchronize local branches to the remote ones

This answer provides detailed steps on how to achieve that relatively easily:

Git error: src refspec master does not match any

The quick possible answer: When you first successfully clone an empty git repository, the origin has no master branch. So the first time you have a commit to push you must do:

git push origin master

Which will create this new master branch for you. Little things like this are very confusing with git.

If this didn't fix your issue then it's probably a gitolite-related issue:

Your conf file looks strange. There should have been an example conf file that came with your gitolite. Mine looks like this:

repo    phonegap                                                                                                                                                                           
    RW+     =   myusername otherusername                                                                                                                                               

repo    gitolite-admin                                                                                                                                                                         
    RW+     =   myusername                                                                                                                                                               

Please make sure you're setting your conf file correctly.

Gitolite actually replaces the gitolite user's account with a modified shell that doesn't accept interactive terminal sessions. You can see if gitolite is working by trying to ssh into your box using the gitolite user account. If it knows who you are it will say something like "Hi XYZ, you have access to the following repositories: X, Y, Z" and then close the connection. If it doesn't know you, it will just close the connection.

Lastly, after your first git push failed on your local machine you should never resort to creating the repo manually on the server. We need to know why your git push failed initially. You can cause yourself and gitolite more confusion when you don't use gitolite exclusively once you've set it up.

Git status shows files as changed even though contents are the same

For me the issue was a case difference in the file.

I renamed the file and committed the delete, It showed both the upper and lower case versions of the file to be deleted.

After the delete was committed I renamed the file back to its original name and pushed.

Disable ScrollView Programmatically?

I may be late but still...

This answer is based on removing and adding views dynamically

To disable scrolling:

View child = scoll.getChildAt(0);// since scrollView can only have one direct child
ViewGroup parent = (ViewGroup) scroll.getParent();
scroll.removeView(child); // remove child from scrollview
parent.addView(child,parent.indexOfChild(scroll));// add scroll child at the position of scrollview
parent.removeView(scroll);// remove scrollView from parent

To enable ScrollView just reverse the process

What's the -practical- difference between a Bare and non-Bare repository?

A default/non-bare Git repo contains two pieces of state:

  1. A snapshot of all of the files in the repository (this is what "working tree" means in Git jargon)
  2. A history of all changes made to all the files that have ever been in the repository (there doesn't seem to be a concise piece of Git jargon that encompasses all of this)

The snapshot is what you probably think of as your project: your code files, build files, helper scripts, and anything else you version with Git.

The history is the state that allows you to check out a different commit and get a complete snapshot of what the files in your repository looked like when that commit was added. It consists of a bunch of data structures that are internal to Git that you've probably never interacted with directly. Importantly, the history doesn't just store metadata (e.g. "User U added this many lines to File F at Time T as part of Commit C"), it also stores data (e.g. "User U added these exact lines to File F").

The key idea of a bare repository is that you don't actually need to have the snapshot. Git keeps the snapshot around because it's convenient for humans and other non-Git processes that want to interact with your code, but the snapshot is just duplicating state that's already in the history.

A bare repository is a Git repository that does not have a snapshot. It just stores the history.

Why would you want this? Well, if you're only going to interact with your files using Git (that is, you're not going to edit your files directly or use them to build an executable), you can save space by not keeping around the snapshot. In particular, if you're maintaining a centralized version of your repo on a server somewhere (i.e. you're basically hosting your own GitHub), that server should probably have a bare repo (you would still use a non-bare repo on your local machine though, since you'll presumably want to edit your snapshot).

If you want a more in-depth explanation of bare repos and another example use case, I wrote up a blog post here: https://stegosaurusdormant.com/bare-git-repo/

How do I properly force a Git push?

And if push --force doesn't work you can do push --delete. Look at 2nd line on this instance:

git reset --hard HEAD~3  # reset current branch to 3 commits ago
git push origin master --delete  # do a very very bad bad thing
git push origin master  # regular push

But beware...

Never ever go back on a public git history!

In other words:

  • Don't ever force push on a public repository.
  • Don't do this or anything that can break someone's pull.
  • Don't ever reset or rewrite history in a repo someone might have already pulled.

Of course there are exceptionally rare exceptions even to this rule, but in most cases it's not needed to do it and it will generate problems to everyone else.

Do a revert instead.

And always be careful with what you push to a public repo. Reverting:

git revert -n HEAD~3..HEAD  # prepare a new commit reverting last 3 commits
git commit -m "sorry - revert last 3 commits because I was not careful"
git push origin master  # regular push

In effect, both origin HEADs (from the revert and from the evil reset) will contain the same files.


edit to add updated info and more arguments around push --force

Consider pushing force with lease instead of push, but still prefer revert

Another problem push --force may bring is when someone push anything before you do, but after you've already fetched. If you push force your rebased version now you will replace work from others.

git push --force-with-lease introduced in the git 1.8.5 (thanks to @VonC comment on the question) tries to address this specific issue. Basically, it will bring an error and not push if the remote was modified since your latest fetch.

This is good if you're really sure a push --force is needed, but still want to prevent more problems. I'd go as far to say it should be the default push --force behaviour. But it's still far from being an excuse to force a push. People who fetched before your rebase will still have lots of troubles, which could be easily avoided if you had reverted instead.

And since we're talking about git --push instances...

Why would anyone want to force push?

@linquize brought a good push force example on the comments: sensitive data. You've wrongly leaked data that shouldn't be pushed. If you're fast enough, you can "fix"* it by forcing a push on top.

* The data will still be on the remote unless you also do a garbage collect, or clean it somehow. There is also the obvious potential for it to be spread by others who'd fetched it already, but you get the idea.

Undefined reference to `sin`

I had the same problem, which went away after I listed my library last: gcc prog.c -lm

Git: which is the default configured remote for branch?

For the sake of completeness: the previous answers tell how to set the upstream branch, but not how to see it.

There are a few ways to do this:

git branch -vv shows that info for all branches. (formatted in blue in most terminals)

cat .git/config shows this also.

For reference:

Simple and fast method to compare images for similarity

If for matching identical images - code for L2 distance

// Compare two images by getting the L2 error (square-root of sum of squared error).
double getSimilarity( const Mat A, const Mat B ) {
if ( A.rows > 0 && A.rows == B.rows && A.cols > 0 && A.cols == B.cols ) {
    // Calculate the L2 relative error between images.
    double errorL2 = norm( A, B, CV_L2 );
    // Convert to a reasonable scale, since L2 error is summed across all pixels of the image.
    double similarity = errorL2 / (double)( A.rows * A.cols );
    return similarity;
}
else {
    //Images have a different size
    return 100000000.0;  // Return a bad value
}

Fast. But not robust to changes in lighting/viewpoint etc. Source

git: can't push (unpacker error) related to permission issues

I was having trouble with this too, thinking my remote gitolite-admin was corrupted or something wrong.

My setup is Mac OS X (10.6.6) laptop with remote Ubuntu 10 server with gitolite.

It turned out that the problem was with my local checkout of gitolite-admin.

Despite the "unpack failed" error, it turned out the the problem was local.

I figured this out by checking it out again as gitolite-admin2, making a change, and the pushing.

Voila! It worked!

What's the difference between git clone --mirror and git clone --bare

$ git clone --bare https://github.com/example

This command will make the new "example" directory itself the $GIT_DIR (instead of example/.git). Also the branch heads at the remote are copied directly to corresponding local branch heads, without mapping. When this option is used, neither remote-tracking branches nor the related configuration variables are created.

$ git clone --mirror https://github.com/example

As with a bare clone, a mirrored clone includes all remote branches and tags, but all local references (including remote-tracking branches, notes etc.) will be overwritten each time you fetch, so it will always be the same as the original repository.

Div side by side without float

You can also use CSS3 flexbox layout, which is well supported nowadays.

.container {
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-between;
    background:black;
    height:400px;
    width:450px;
}

.left {
    flex: 0 0 300px;
    background:blue;
    height:200px;
}

.right {
    flex: 0 1 100px;
    background:green;
    height:300px;
}

See Example (with legacy styles for maximum compatiblity) & Learn more about flexbox.

How to map calculated properties with JPA and Hibernate

JPA doesn't offer any support for derived property so you'll have to use a provider specific extension. As you mentioned, @Formula is perfect for this when using Hibernate. You can use an SQL fragment:

@Formula("PRICE*1.155")
private float finalPrice;

Or even complex queries on other tables:

@Formula("(select min(o.creation_date) from Orders o where o.customer_id = id)")
private Date firstOrderDate;

Where id is the id of the current entity.

The following blog post is worth the read: Hibernate Derived Properties - Performance and Portability.

Without more details, I can't give a more precise answer but the above link should be helpful.

See also:

Git push error '[remote rejected] master -> master (branch is currently checked out)'

The best way to do this is:

mkdir ..../remote
cd ..../remote
git clone --bare .../currentrepo/

This will clone the repository, but it won't make any working copies in .../remote. If you look at the remote, you'll see one directory created, called currentrepo.git, which is probably what you want.

Then from your local Git repository:

git remote add remoterepo ..../remote/currentrepo.git

After you make changes, you can:

git push remoterepo master

HorizontalScrollView within ScrollView Touch Handling

I've found out that somethimes one ScrollView regains focus and the other loses focus. You can prevent that, by only granting one of the scrollView focus:

    scrollView1= (ScrollView) findViewById(R.id.scrollscroll);
    scrollView1.setAdapter(adapter);
    scrollView1.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            scrollView1.getParent().requestDisallowInterceptTouchEvent(true);
            return false;
        }
    });

Specify JDK for Maven to use

Maven uses variable $JAVACMD as the final java command, set it to where the java executable is will switch maven to different JDK.

How to convert a normal Git repository to a bare one?

The methods that say to remove files and muck about with moving the .git directory are not clean and not using the "git" method of doing something that's should be simple. This is the cleanest method I have found to convert a normal repo into a bare repo.

First clone /path/to/normal/repo into a bare repo called repo.git

git clone --bare /path/to/normal/repo

Next remove the origin that points to /path/to/normal/repo

cd repo.git
git remote rm origin

Finally you can remove your original repo. You could rename repo.git to repo at that point, but the standard convention to signify a git repository is something.git, so I'd personally leave it that way.

Once you've done all that, you can clone your new bare repo (which in effect creates a normal repo, and is also how you would convert it from bare to normal)

Of course if you have other upstreams, you'll want to make a note of them, and update your bare repo to include it. But again, it can all be done with the git command. Remember the man pages are your friend.

Styling an anchor tag to look like a submit button

How about

<a href="url"><input type="button" value="Cancel"></a>

Git: Recover deleted (remote) branch

Your deleted branches are not lost, they were copied into origin/contact_page and origin/new_pictures “remote tracking branches” by the fetch you showed (they were also pushed back out by the push you showed, but they were pushed into refs/remotes/origin/ instead of refs/heads/). Check git log origin/contact_page and git log origin/new_pictures to see if your local copies are “up to date” with whatever you think should be there. If any new commits were pushed onto those branches (from some other repo) between the fetch and push that you showed, you may have “lost” those (but probably you could probably find them in the other repo that most recently pushed those branches).

Fetch/Push Conflict

It looks like you are fetching in a normal, ‘remote mode’ (remote refs/heads/ are stored locally in refs/remotes/origin/), but pushing in ‘mirror mode’ (local refs/ are pushed onto remote refs/). Check your .git/config and reconcile the remote.origin.fetch and remote.origin.push settings.

Make a Backup

Before trying any changes, make a simple tar or zip archive or your whole local repo. That way, if you do not like what happens, you can try again from a restored repo.

Option A: Reconfigure as a Mirror

If you intend to use your remote repo as a mirror of your local one, do this:

git branch contact_page origin/contact_page &&
git branch new_pictures origin/new_pictures &&
git config remote.origin.fetch '+refs/*:refs/*' &&
git config --unset remote.origin.push &&
git config remote.origin.mirror true

You might also eventually want to do delete all your refs/remotes/origin/ refs, since they are not useful if you are operating in mirror mode (your normal branches take the place of the usual remote tracking branches).

Option B: Reconfigure as a Normal Remote

But since it seems that you are using this remote repo with multiple “work” repos, you probably do not want to use mirror mode. You might try this:

git config push.default tracking &&
git config --unset remote.origin.push
git config --unset remote.origin.mirror

Then, you will eventually want to delete the bogus refs/remotes/origin refs in your remote repo: git push origin :refs/remotes/origin/contact_page :refs/remotes/origin/new_pictures ….

Test Push

Try git push --dry-run to see what it git push would do without having it make any changes on the remote repo. If you do not like what it says it is going to do, recover from your backup (tar/zip) and try the other option.

git replacing LF with CRLF

I don't know much about git on Windows, but...

Appears to me that git is converting the return format to match that of the running platform (Windows). CRLF is the default return format in Windows, while LF is the default return format for most other OSes.

Chances are, the return format will be adjusted properly when the code is moved to another system. I also reckon git is smart enough to keep binary files intact rather than trying to convert LFs to CRLFs in, say, JPEGs.

In summary, you probably don't need to fret too much over this conversion. However, if you go to archive your project as a tarball, fellow coders would probably appreciate having LF line terminators rather than CRLF. Depending on how much you care (and depending on you not using Notepad), you might want to set git to use LF returns if you can :)

Appendix: CR is ASCII code 13, LF is ASCII code 10. Thus, CRLF is two bytes, while LF is one.

Test if string is URL encoded in PHP

There's no reliable way to do this, as there are strings which stay the same through the encoding process, i.e. is "abc" encoded or not? There's no clear answer. Also, as you've encountered, some characters have multiple encodings... But...

Your decode-check-encode-check scheme fails due to the fact that some characters may be encoded in more than one way. However, a slight modification to your function should be fairly reliable, just check if the decode modifies the string, if it does, it was encoded.

It won't be fool proof of course, as "10+20=30" will return true (+ gets converted to space), but we're actually just doing arithmetic. I suppose this is what you're scheme is attempting to counter, I'm sorry to say that I don't think there's a perfect solution.

HTH.

Edit:
As I entioned in my own comment (just reiterating here for clarity), a good compromise would probably be to check for invalid characters in your url (e.g. space), and if there are some it's not encoded. If there are none, try to decode and see if the string changes. This still won't handle the arithmetic above (which is impossible), but it'll hopefully be sufficient.

Using a remote repository with non-standard port

SSH doesn't use the : syntax when specifying a port. The easiest way to do this is to edit your ~/.ssh/config file and add:

Host git.host.de
  Port 4019

Then specify just git.host.de without a port number.

Histogram with Logarithmic Scale and custom breaks

Run the hist() function without making a graph, log-transform the counts, and then draw the figure.

hist.data = hist(my.data, plot=F)
hist.data$counts = log(hist.data$counts, 2)
plot(hist.data)

It should look just like the regular histogram, but the y-axis will be log2 Frequency.

Event system in Python

I use zope.event. It's the most bare bones you can imagine. :-) In fact, here is the complete source code:

subscribers = []

def notify(event):
    for subscriber in subscribers:
        subscriber(event)

Note that you can't send messages between processes, for example. It's not a messaging system, just an event system, nothing more, nothing less.

Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

The interesting thing about UITableViewStyleGrouped is that the tableView adds the style to the cells and not to the TableView.

The style is added as backgroundView to the cells as a class called UIGroupTableViewCellBackground which handles drawing different background according to the position of the cell in the section.

So a very simple solution will be to use UITableViewStyleGrouped, set the backgroundColor of the table to clearColor, and simply replace the backgroundView of the cell in cellForRow:

cell.backgroundView = [[[UIView alloc] initWithFrame:cell.bounds] autorelease];

How do I use boolean variables in Perl?

My favourites have always been

use constant FALSE => 1==0;
use constant TRUE => not FALSE;

which is completely independent from the internal representation.

Adjust width and height of iframe to fit with content in it

all can not work using above methods.

javascript:

function resizer(id) {
        var doc = document.getElementById(id).contentWindow.document;
        var body_ = doc.body, html_ = doc.documentElement;

        var height = Math.max(body_.scrollHeight, body_.offsetHeight, html_.clientHeight, html_.scrollHeight, html_.offsetHeight);
        var width = Math.max(body_.scrollWidth, body_.offsetWidth, html_.clientWidth, html_.scrollWidth, html_.offsetWidth);

        document.getElementById(id).style.height = height;
        document.getElementById(id).style.width = width;

    }

html:

<div style="background-color:#b6ff00;min-height:768px;line-height:inherit;height:inherit;margin:0px;padding:0px;overflow:visible" id="mainDiv"  >
         <input id="txtHeight"/>height     <input id="txtWidth"/>width     
        <iframe src="head.html" name="topFrame" scrolling="No" noresize="noresize" id="topFrame" title="topFrame" style="width:100%; height: 47px" frameborder="0"  ></iframe>
        <iframe src="left.aspx" name="leftFrame" scrolling="yes"   id="Iframe1" title="leftFrame" onload="resizer('Iframe1');" style="top:0px;left:0px;right:0px;bottom:0px;width: 30%; border:none;border-spacing:0px; justify-content:space-around;" ></iframe>
        <iframe src="index.aspx" name="mainFrame" id="Iframe2" title="mainFrame" scrolling="yes" marginheight="0" frameborder="0" style="width: 65%; height:100%; overflow:visible;overflow-x:visible;overflow-y:visible; "  onload="resizer('Iframe2');" ></iframe>
</div>

Env: IE 10, Windows 7 x64

What is the coolest thing you can do in <10 lines of simple code? Help me inspire beginners!

How about Processing for JavaScript? I don't know Processing, but the code always seems rather small for what it can do, it's very visual, and you can run it in a browser.
http://processingjs.org/exhibition

How do I get the Git commit count?

The one I used to use was:

git log | grep "^commit" | wc -l

Simple but it worked.

How do you get git to always pull from a specific branch?

There is also a way of configuring Git so, it always pulls and pushes the equivalent remote branch to the branch currently checked out to the working copy. It's called a tracking branch which git ready recommends setting by default.

For the next repository above the present working directory:

git config branch.autosetupmerge true

For all Git repositories, that are not configured otherwise:

git config --global branch.autosetupmerge true

Kind of magic, IMHO but this might help in cases where the specific branch is always the current branch.

When you have branch.autosetupmerge set to true and checkout a branch for the first time, Git will tell you about tracking the corresponding remote branch:

(master)$ git checkout gh-pages
Branch gh-pages set up to track remote branch gh-pages from origin.
Switched to a new branch 'gh-pages'

Git will then push to that corresponding branch automatically:

(gh-pages)$ git push
Counting objects: 8, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (6/6), done.
Writing objects: 100% (6/6), 1003 bytes, done.
Total 6 (delta 2), reused 0 (delta 0)
To [email protected]:bigben87/webbit.git
   1bf578c..268fb60  gh-pages -> gh-pages

Git workflow and rebase vs merge questions

With Git there is no “correct” workflow. Use whatever floats your boat. However, if you constantly get conflicts when merging branches maybe you should coordinate your efforts better with your fellow developer(s)? Sounds like the two of you keep editing the same files. Also, watch out for whitespace and subversion keywords (i.e., “$Id$” and others).

Creating a list of objects in Python

To fill a list with seperate instances of a class, you can use a for loop in the declaration of the list. The * multiply will link each copy to the same instance.

instancelist = [ MyClass() for i in range(29)]

and then access the instances through the index of the list.

instancelist[5].attr1 = 'whamma'

How do I break out of a loop in Perl?

Additional data (in case you have more questions):

FOO: {
       for my $i ( @listone ){
          for my $j ( @listtwo ){
                 if ( cond( $i,$j ) ){

                    last FOO;  # --->
                                   # |
                 }                 # |
          }                        # |
       }                           # |
 } # <-------------------------------

Is there any 'out-of-the-box' 2D/3D plotting library for C++?

Even though this thread is old but gold. QCustomPlot is very recommendable as well to complement this list.

Cause of No suitable driver found for

In order to have HSQLDB register itself, you need to access its jdbcDriver class. You can do this the same way as in this example.

Class.forName("org.hsqldb.jdbcDriver");

It triggers static initialization of jdbcDriver class, which is:

static {
    try {
        DriverManager.registerDriver(new jdbcDriver());
    } catch (Exception e) {}
}

What's wrong with foreign keys?

@imphasing - this is exactly the kind of mindset that causes maintenance nightmares.

Why oh why would you ignore declarative referential integrity, where the data can be guaranteed to be at least consistent, in favour of so called "software enforcement" which is a weak preventative measure at best.

List of macOS text editors and code editors

I use Eclipse as my primary editor (for Python) but I always keep SubEthaEdit handy as my supplemental text editor (free trial, 30 euros to license). It's not super-complicated but it does what I need.

How can I set up an editor to work with Git on Windows?

This is my setup to use Geany as an editor for Git:

git config --global core.editor C:/path/to/geany.bat

with the following content in geany.bat:

#!/bin/sh
"C:\Program Files\Geany\bin\Geany.exe" --new-instance "$*"

It works in both a DOS console and msysgit.

Hidden Features of C#?

Use of @ before a string that contains escape char. Basically when a physical path is used to assign in a string variable everybody uses '\' where escape character is present in a string.

e.g. string strPath="D:\websites\web1\images\";

But escape characters can be ignored using @ before the string value.

e.g. string strPath=@"D:\websites\web1\images\";

How can I print to the same line?

Format your string like so:

[#                    ] 1%\r

Note the \r character. It is the so-called carriage return that will move the cursor back to the beginning of the line.

Finally, make sure you use

System.out.print()

and not

System.out.println()

Javascript - User input through HTML input tag to set a Javascript variable?

This is bad style, but I'll assume you have a good reason for doing something similar.

<html>
<body>
    <input type="text" id="userInput">give me input</input>
    <button id="submitter">Submit</button>
    <div id="output"></div>
    <script>
        var didClickIt = false;
        document.getElementById("submitter").addEventListener("click",function(){
            // same as onclick, keeps the JS and HTML separate
            didClickIt = true;
        });

        setInterval(function(){
            // this is the closest you get to an infinite loop in JavaScript
            if( didClickIt ) {
                didClickIt = false;
                // document.write causes silly problems, do this instead (or better yet, use a library like jQuery to do this stuff for you)
                var o=document.getElementById("output"),v=document.getElementById("userInput").value;
                if(o.textContent!==undefined){
                    o.textContent=v;
                }else{
                    o.innerText=v;
                }
            }
        },500);
    </script>
</body>
</html>

No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

I went to Preferences --> Java --> Installed JREs I did NOT see the JDK in here. I only saw the JRE here. So I added the JDK.

here we have to mandatory remove JRE instead of just unchecking.

Spring JPA @Query with LIKE

Try to use the following approach (it works for me):

@Query("SELECT u.username FROM User u WHERE u.username LIKE CONCAT('%',:username,'%')")
List<String> findUsersWithPartOfName(@Param("username") String username);

Notice: The table name in JPQL must start with a capital letter.

How does OkHttp get Json string?

try {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
        .url(urls[0])
        .build();
    Response responses = null;

    try {
        responses = client.newCall(request).execute();
    } catch (IOException e) {
        e.printStackTrace();
    }
    String jsonData = responses.body().string();
    JSONObject Jobject = new JSONObject(jsonData);
    JSONArray Jarray = Jobject.getJSONArray("employees");

    for (int i = 0; i < Jarray.length(); i++) {
        JSONObject object     = Jarray.getJSONObject(i);
    }
}

Example add to your columns:

JCol employees  = new employees();
colums.Setid(object.getInt("firstName"));
columnlist.add(lastName);           

Install pdo for postgres Ubuntu

Pecl PDO package is now deprecated. By the way the debian package php5-pgsql now includes both the regular and the PDO driver, so just:

apt-get install php-pgsql

Apache also needs to be restarted before sites can use it:

sudo systemctl restart apache2

Rotating a Div Element in jQuery

I doubt you can rotate an element using DOM/CSS. Your best bet would be to render to a canvas and rotate that (not sure on the specifics).

Comparing two maps

Quick Answer

You should use the equals method since this is implemented to perform the comparison you want. toString() itself uses an iterator just like equals but it is a more inefficient approach. Additionally, as @Teepeemm pointed out, toString is affected by order of elements (basically iterator return order) hence is not guaranteed to provide the same output for 2 different maps (especially if we compare two different maps).

Note/Warning: Your question and my answer assume that classes implementing the map interface respect expected toString and equals behavior. The default java classes do so, but a custom map class needs to be examined to verify expected behavior.

See: http://docs.oracle.com/javase/7/docs/api/java/util/Map.html

boolean equals(Object o)

Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings. More formally, two maps m1 and m2 represent the same mappings if m1.entrySet().equals(m2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface.

Implementation in Java Source (java.util.AbstractMap)

Additionally, java itself takes care of iterating through all elements and making the comparison so you don't have to. Have a look at the implementation of AbstractMap which is used by classes such as HashMap:

 // Comparison and hashing

    /**
     * Compares the specified object with this map for equality.  Returns
     * <tt>true</tt> if the given object is also a map and the two maps
     * represent the same mappings.  More formally, two maps <tt>m1</tt> and
     * <tt>m2</tt> represent the same mappings if
     * <tt>m1.entrySet().equals(m2.entrySet())</tt>.  This ensures that the
     * <tt>equals</tt> method works properly across different implementations
     * of the <tt>Map</tt> interface.
     *
     * <p>This implementation first checks if the specified object is this map;
     * if so it returns <tt>true</tt>.  Then, it checks if the specified
     * object is a map whose size is identical to the size of this map; if
     * not, it returns <tt>false</tt>.  If so, it iterates over this map's
     * <tt>entrySet</tt> collection, and checks that the specified map
     * contains each mapping that this map contains.  If the specified map
     * fails to contain such a mapping, <tt>false</tt> is returned.  If the
     * iteration completes, <tt>true</tt> is returned.
     *
     * @param o object to be compared for equality with this map
     * @return <tt>true</tt> if the specified object is equal to this map
     */
    public boolean equals(Object o) {
        if (o == this)
            return true;

        if (!(o instanceof Map))
            return false;
        Map<K,V> m = (Map<K,V>) o;
        if (m.size() != size())
            return false;

        try {
            Iterator<Entry<K,V>> i = entrySet().iterator();
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                K key = e.getKey();
                V value = e.getValue();
                if (value == null) {
                    if (!(m.get(key)==null && m.containsKey(key)))
                        return false;
                } else {
                    if (!value.equals(m.get(key)))
                        return false;
                }
            }
        } catch (ClassCastException unused) {
            return false;
        } catch (NullPointerException unused) {
            return false;
        }

        return true;
    }

Comparing two different types of Maps

toString fails miserably when comparing a TreeMap and HashMap though equals does compare contents correctly.

Code:

public static void main(String args[]) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("2", "whatever2");
map.put("1", "whatever1");
TreeMap<String, Object> map2 = new TreeMap<String, Object>();
map2.put("2", "whatever2");
map2.put("1", "whatever1");

System.out.println("Are maps equal (using equals):" + map.equals(map2));
System.out.println("Are maps equal (using toString().equals()):"
        + map.toString().equals(map2.toString()));

System.out.println("Map1:"+map.toString());
System.out.println("Map2:"+map2.toString());
}

Output:

Are maps equal (using equals):true
Are maps equal (using toString().equals()):false
Map1:{2=whatever2, 1=whatever1}
Map2:{1=whatever1, 2=whatever2}

How do I access nested HashMaps in Java?

You can get the nested value by repeating .get(), but with deeply nested maps you have to do a lot of casting into Map. An easier way is to use a generic method for getting a nested value.

Implementation

public static <T> T getNestedValue(Map map, String... keys) {
    Object value = map;

    for (String key : keys) {
        value = ((Map) value).get(key);
    }

    return (T) value;
}

Usage

// Map contents with string and even a list:
{
  "data": {
    "vehicles": {
      "list": [
        {
          "registration": {
            "owner": {
              "id": "3643619"
            }
          }
        }
      ]
    }
  }
}
List<Map> list = getNestedValue(mapContents, "data", "vehicles", "list");
Map first = list.get(0);
String id = getNestedValue(first, "registration", "owner", "id");

What is the maximum length of a URL in different browsers?

WWW FAQs: What is the maximum length of a URL? has its own answer based on empirical testing and research. The short answer is that going over 2048 characters makes Internet Explorer unhappy and thus this is the limit you should use. See the page for a long answer.

Count immediate child div elements using jQuery

var divss = 0;
$(function(){
   $("#foo div").each(function(){
    divss++;

   });
   console.log(divss);  
});     
<div id="foo">
  <div id="bar" class="1"></div>
  <div id="baz" class="1"></div>
  <div id="bam" class="1"></div>
</div>

Choosing a jQuery datagrid plugin?

The three most used and well supported jQuery grid plugins today are SlickGrid, jqGrid and DataTables. See http://wiki.jqueryui.com/Grid-OtherGrids for more info.

Combine Date and Time columns using python pandas

My dataset had 1second resolution data for a few days and parsing by the suggested methods here was very slow. Instead I used:

dates = pandas.to_datetime(df.Date, cache=True)
times = pandas.to_timedelta(df.Time)
datetimes  = dates + times

Note the use of cache=True makes parsing the dates very efficient since there are only a couple unique dates in my files, which is not true for a combined date and time column.

Change GitHub Account username

Yes, this is an old question. But it's misleading, as this was the first result in my search, and both the answers aren't correct anymore.

You can change your Github account name at any time.

To do this, click your profile picture > Settings > Account Settings > Change Username.

Links to your repositories will redirect to the new URLs, but they should be updated on other sites because someone who chooses your abandoned username can override the links. Links to your profile page will be 404'd.

For more information, see the official help page.

And furthermore, if you want to change your username to something else, but that specific username is being taken up by someone else who has been completely inactive for the entire time their account has existed, you can report their account for name squatting.

jQuery if checkbox is checked

this $('#checkboxId').is(':checked') for verify if is checked

& this $("#checkboxId").prop('checked', true) to check

& this $("#checkboxId").prop('checked', false) to uncheck

How to stop Python closing immediately when executed in Microsoft Windows

Well I got similar issue, It is solved by adding Environment Variable.

Add System Variables in Window

Name : PYTHONPATH

Value : C:\Python27;

Your Python path.

C# : 'is' keyword and checking for Not

The is operator evaluates to a boolean result, so you can do anything you would otherwise be able to do on a bool. To negate it use the ! operator. Why would you want to have a different operator just for this?

Check synchronously if file/directory exists in Node.js

Using the currently recommended (as of 2015) APIs (per the Node docs), this is what I do:

var fs = require('fs');

function fileExists(filePath)
{
    try
    {
        return fs.statSync(filePath).isFile();
    }
    catch (err)
    {
        return false;
    }
}

In response to the EPERM issue raised by @broadband in the comments, that brings up a good point. fileExists() is probably not a good way to think about this in many cases, because fileExists() can't really promise a boolean return. You may be able to determine definitively that the file exists or doesn't exist, but you may also get a permissions error. The permissions error doesn't necessarily imply that the file exists, because you could lack permission to the directory containing the file on which you are checking. And of course there is the chance you could encounter some other error in checking for file existence.

So my code above is really doesFileExistAndDoIHaveAccessToIt(), but your question might be doesFileNotExistAndCouldICreateIt(), which would be completely different logic (that would need to account for an EPERM error, among other things).

While the fs.existsSync answer addresses the question asked here directly, that is often not going to be what you want (you don't just want to know if "something" exists at a path, you probably care about whether the "thing" that exists is a file or a directory).

The bottom line is that if you're checking to see if a file exists, you are probably doing that because you intend to take some action based on the result, and that logic (the check and/or subsequent action) should accommodate the idea that a thing found at that path may be a file or a directory, and that you may encounter EPERM or other errors in the process of checking.

Get Cell Value from Excel Sheet with Apache Poi

May be by:-

    for(Row row : sheet) {          
        for(Cell cell : row) {              
            System.out.print(cell.getStringCellValue());

        }
    }       

For specific type of cell you can try:

switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
    cellValue = cell.getStringCellValue();
    break;

case Cell.CELL_TYPE_FORMULA:
    cellValue = cell.getCellFormula();
    break;

case Cell.CELL_TYPE_NUMERIC:
    if (DateUtil.isCellDateFormatted(cell)) {
        cellValue = cell.getDateCellValue().toString();
    } else {
        cellValue = Double.toString(cell.getNumericCellValue());
    }
    break;

case Cell.CELL_TYPE_BLANK:
    cellValue = "";
    break;

case Cell.CELL_TYPE_BOOLEAN:
    cellValue = Boolean.toString(cell.getBooleanCellValue());
    break;

}

Using R to list all files with a specified extension

I am not very good in using sophisticated regular expressions, so I'd do such task in the following way:

files <- list.files()
dbf.files <- files[-grep(".xml", files, fixed=T)]

First line just lists all files from working dir. Second one drops everything containing ".xml" (grep returns indices of such strings in 'files' vector; subsetting with negative indices removes corresponding entries from vector). "fixed" argument for grep function is just my whim, as I usually want it to peform crude pattern matching without Perl-style fancy regexprs, which may cause surprise for me.

I'm aware that such solution simply reflects drawbacks in my education, but for a novice it may be useful =) at least it's easy.

JS file gets a net::ERR_ABORTED 404 (Not Found)

As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().

Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static for the example. Once it's done, add this line in your server code:

app.use("/static", express.static('./static/'));

This will effectively serve every file in your "static" folder via the /static route.

Querying your index.js file in the client thus becomes:

<script src="static/index.js"></script>

Select a dummy column with a dummy value in SQL?

Try this:

select col1, col2, 'ABC' as col3 from Table1 where col1 = 0;

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

The justify-self and justify-items properties are not implemented in flexbox. This is due to the one-dimensional nature of flexbox, and that there may be multiple items along the axis, making it impossible to justify a single item. To align items along the main, inline axis in flexbox you use the justify-content property.

Reference: Box alignment in CSS Grid Layout

onSaveInstanceState () and onRestoreInstanceState ()

The main thing is that if you don't store in onSaveInstanceState() then onRestoreInstanceState() will not be called. This is the main difference between restoreInstanceState() and onCreate(). Make sure you really store something. Most likely this is your problem.

Making an API call in Python with an API that requires a bearer token

If you are using requests module, an alternative option is to write an auth class, as discussed in "New Forms of Authentication":

import requests

class BearerAuth(requests.auth.AuthBase):
    def __init__(self, token):
        self.token = token
    def __call__(self, r):
        r.headers["authorization"] = "Bearer " + self.token
        return r

and then can you send requests like this

response = requests.get('https://www.example.com/', auth=BearerAuth('3pVzwec1Gs1m'))

which allows you to use the same auth argument just like basic auth, and may help you in certain situations.

Connecting to SQL Server with Visual Studio Express Editions

Workaround:

  1. Open your solution in Visual Web Developer Express. It will not load some of the projects in the solution but it is ok.
  2. Make a new connection in Database Explorer to the required database from SQL Server.
  3. Add a new class library project.
  4. Add a LINQ to SQL Classes item and link it to your database.
  5. Close the solution.
  6. Open the solution in Visual C# Express.

Now you have a LINQ to SQL classes library that is linked to your SQL Server database in Visual C# Express.

Update

The solution is for Visual Studio Express 2010.

jQuery Toggle Text?

Perhaps I'm oversimplifying the problem, but this is what I use.

$.fn.extend({
    toggleText: function(a, b) {
        $.trim(this.html()) == a ? this.html(b) : this.html(a);
    }
});

Which maven dependencies to include for spring 3.0?

Since this questions seems to still get quite a lot of views, it might be useful to note that for Spring 4+ it's easiest to start using Spring Boot and the Spring Boot starter POMs.

Using Spring Boot there's less dependencies to manage (and thus fewer conflicts), and setting up a working, well integrated Spring Context is a whole lot easier. I highly recommend it.

How do I update zsh to the latest version?

I just switched the main shell to zsh. It suppresses the warnings and it isn't too complicated.

Adding image to JFrame

Here is a simple example of adding an image to a JFrame:

frame.add(new JLabel(new ImageIcon("Path/To/Your/Image.png")));

How to maintain aspect ratio using HTML IMG tag

The poster is showing a dimension constrained by height in most cases he posted >>> (256x256, 1024x768, 500x400, 205x246, etc.) but fitting a 64px max height pixel dimension, typical of most landscape "photos". So my guess is he wants an image that is always 64 pixels in height. To achieve that, do the following:

<img id="photo1" style="height:64px;width:auto;" src="photo.jpg" height="64" />

This solution guarantees the images are all 64 pixels max in height and allows width to extend or shrink based on each image's aspect ratio. Setting height to 64 in the img height attribute reserves a space in the browser's Rendertree layout as images download, so the content doesn't shift waiting for images to download. Also, the new HTML5 standard does not always honor width and height attributes. They are dimensional "hints" only, not final dimensions of the image. If in your style sheet you reset or change the image height and width, the actual values in the images attributes get reset to either your CSS value or the images native default dimensions. Setting the CSS height to "64px" and the width to "auto" forces width to start with the native image width (not image attribute width) and then calculate a new aspect-ratio using the CSS style for height. That gets you a new width. So the height and width "img" attributes are really not needed here and just force the browser to do extra calculations.

How does one remove a Docker image?

List images:

ahanjura@ubuntu:~$ sudo docker images

REPOSITORY TAG IMAGE ID CREATED SIZE 88282f8eda00 19 seconds ago 308.5 MB 13e5d3d682f4 19 hours ago 663 MB busybox2 latest 05fe66bb1144 20 hours ago 1.129 MB ubuntu 16.04 00fd29ccc6f1 5 days ago 110.5 MB ubuntu 14.04 67759a80360c 5 days ago 221.4 MB python 2.7 9e92c8430ba0 7 days ago 680.7 MB busybox latest 6ad733544a63 6 weeks ago 1.129 MB ubuntu 16.10 7d3f705d307c 5 months ago 106.7 MB

Delete images:

ahanjura@ubuntu:~$ sudo docker rmi 88282f8eda00

Deleted: sha256:88282f8eda0036f85b5652c44d158308c6f86895ef1345dfa788318e6ba31194 Deleted: sha256:4f211a991fb392cd794bc9ad8833149cd9400c5955958c4017b1e2dc415e25e9 Deleted: sha256:8cc6917ac7f0dcb74969ae7958fe80b4a4ea7b3223fc888dfe1aef42f43df6f8 Deleted: sha256:b74a8932cff5e61c3fd2cc39de3c0989bdfd5c2e5f72b8f99f2807595f8ece43

ahanjura@ubuntu:~$ sudo docker rmi 13e5d3d682f4

Error response from daemon: conflict: unable to delete 13e5d3d682f4 (must be forced) - image is being used by stopped container 5593e25eb638

Delete by force:

ahanjura@ubuntu:~$ sudo docker rmi -f 13e5d3d682f4

Deleted: sha256:13e5d3d682f4de973780b35a3393c46eb314ef3db45d3ae83baf2dd9d702747e Deleted: sha256:3ad9381c7041c03768ccd855ec86caa6bc0244223f10b0465c4898bdb21dc378 Deleted: sha256:5ccb917bce7bc8d3748eccf677d7b60dd101ed3e7fd2aedebd521735276606af Deleted: sha256:18356d19b91f0abcc04496729c9a4c49e695dbfe3f0bb1c595f30a7d4d264ebf

How to make a vertical SeekBar in Android?

Here is a very good implementation of vertical seekbar. Have a look.

http://560b.sakura.ne.jp/android/VerticalSlidebarExample.zip

And Here is my own implementation for Vertical and Inverted Seekbar based on this

https://github.com/AndroSelva/Vertical-SeekBar-Android

protected void onDraw(Canvas c) {
    c.rotate(-90);
    c.translate(-getHeight(),0);

    super.onDraw(c);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (!isEnabled()) {
        return false;
    }

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
        case MotionEvent.ACTION_MOVE:
        case MotionEvent.ACTION_UP:
            int i=0;
            i=getMax() - (int) (getMax() * event.getY() / getHeight());
            setProgress(i);
            Log.i("Progress",getProgress()+"");
            onSizeChanged(getWidth(), getHeight(), 0, 0);
            break;

        case MotionEvent.ACTION_CANCEL:
            break;
    }
    return true;
}

What is the difference between json.dumps and json.load?

json loads -> returns an object from a string representing a json object.

json dumps -> returns a string representing a json object from an object.

load and dump -> read/write from/to file instead of string

AppStore - App status is ready for sale, but not in app store

You may also need to provide your contact info, bank info, and tax info in this page so it will allow your last release on App Store:

https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa/wo/6.0

Rails 4 - Strong Parameters - Nested Objects

If it is Rails 5, because of new hash notation: params.permit(:name, groundtruth: [:type, coordinates:[]]) will work fine.

Linq Query Group By and Selecting First Items

See LINQ: How to get the latest/last record with a group by clause

var firstItemsInGroup = from b in mainButtons
                 group b by b.category into g
select g.First();

I assume that mainButtons are already sorted correctly.

If you need to specify custom sort order, use OrderBy override with Comparer.

var firstsByCompareInGroups = from p in rows
        group p by p.ID into grp
        select grp.OrderBy(a => a, new CompareRows()).First();

See an example in my post "Select First Row In Group using Custom Comparer"

How to put img inline with text

Please make use of the code below to display images inline:

<img style='vertical-align:middle;' src='somefolder/icon.gif'>
<div style='vertical-align:middle; display:inline;'>
Your text here
</div>

"Not allowed to load local resource: file:///C:....jpg" Java EE Tomcat

In Chrome, you are supposed to be able to allow this capability with a runtime flag --allow-file-access-from-files

However, it looks like there is a problem with current versions of Chrome (37, 38) where this doesn't work unless you also pass the runtime flag --disable-web-security

That's an unacceptable solution, except perhaps as a short-term workaround, but it has been identified as an issue: https://code.google.com/p/chromium/issues/detail?id=379206

Using lodash to compare jagged arrays (items existence without order)

PURE JS (works also when arrays and subarrays has more than 2 elements with arbitrary order). If strings contains , use as join('-') parametr character (can be utf) which is not used in strings

array1.map(x=>x.sort()).sort().join() === array2.map(x=>x.sort()).sort().join()

_x000D_
_x000D_
var array1 = [['a', 'b'], ['b', 'c']];_x000D_
var array2 = [['b', 'c'], ['b', 'a']];_x000D_
_x000D_
var r = array1.map(x=>x.sort()).sort().join() === array2.map(x=>x.sort()).sort().join();_x000D_
_x000D_
console.log(r);
_x000D_
_x000D_
_x000D_

Make header and footer files to be included in multiple html pages

I've been working in C#/Razor and since I don't have IIS setup on my home laptop I looked for a javascript solution to load in views while creating static markup for our project.

I stumbled upon a website explaining methods of "ditching jquery," it demonstrates a method on the site does exactly what you're after in plain Jane javascript (reference link at the bottom of post). Be sure to investigate any security vulnerabilities and compatibility issues if you intend to use this in production. I am not, so I never looked into it myself.

JS Function

var getURL = function (url, success, error) {
    if (!window.XMLHttpRequest) return;
    var request = new XMLHttpRequest();
    request.onreadystatechange = function () {
        if (request.readyState === 4) {
            if (request.status !== 200) {
                if (error && typeof error === 'function') {
                    error(request.responseText, request);
                }
                return;
            }
            if (success && typeof success === 'function') {
                success(request.responseText, request);
            }
        }
    };
    request.open('GET', url);
    request.send();
};

Get the content

getURL(
    '/views/header.html',
    function (data) {
        var el = document.createElement(el);
        el.innerHTML = data;
        var fetch = el.querySelector('#new-header');
        var embed = document.querySelector('#header');
        if (!fetch || !embed) return;
        embed.innerHTML = fetch.innerHTML;

    }
);

index.html

<!-- This element will be replaced with #new-header -->
<div id="header"></div>

views/header.html

<!-- This element will replace #header -->
<header id="new-header"></header>

The source is not my own, I'm merely referencing it as it's a good vanilla javascript solution to the OP. Original code lives here: http://gomakethings.com/ditching-jquery#get-html-from-another-page

Android background music service

Create a foreground service with the START_STICKY flag.

@Override
public int onStartCommand(Intent startIntent, int flags, int startId) {
   if (startIntent != null) {
       String action = startIntent.getAction();
       String command = startIntent.getStringExtra(CMD_NAME);
       if (ACTION_CMD.equals(action)) {
           if (CMD_PAUSE.equals(command)) {
               if (mPlayback != null && mPlayback.isPlaying()) {
                   handlePauseRequest();
               }
           } else if (CMD_PLAY.equals(command)) {
               ArrayList<Track> queue = new ArrayList<>();
               for (Parcelable input : startIntent.getParcelableArrayListExtra(ARG_QUEUE)) {
                   queue.add((Track) Parcels.unwrap(input));
               }
               int index = startIntent.getIntExtra(ARG_INDEX, 0);
               playWithQueue(queue, index);
           }
       }
   }

   return START_STICKY;
}

This can then be called from any activity to play some music

Intent intent = new Intent(MusicService.ACTION_CMD, fileUrlToPlay, activity, MusicService::class.java)
intent.putParcelableArrayListExtra(MusicService.ARG_QUEUE, tracks)
intent.putExtra(MusicService.ARG_INDEX, position)
intent.putExtra(MusicService.CMD_NAME, MusicService.CMD_PLAY)
activity.startService(intent)

You can bind to the service using bindService and to make the Service pause/stop from the corresponding activity lifecycle methods.

Here's a good tutorial about Playing music in the background on Android

How to horizontally center an element

Instead of multiple wrappers and/or auto margins, this simple solution works for me:

<div style="top: 50%; left: 50%;
    height: 100px; width: 100px;
    margin-top: -50px; margin-left: -50px;
    background: url('lib/loading.gif') no-repeat center #fff;
    text-align: center;
    position: fixed; z-index: 9002;">Loading...</div>

It puts the div at the center of the view (vertical and horizontal), sizes and adjusts for size, centers background image (vertical and horizontal), centers text (horizontal), and keeps div in the view and on top of the content. Simply place in the HTML body and enjoy.

Is it possible to force Excel recognize UTF-8 CSV files automatically?

Simple vba macro for opening utf-8 text and csv files

Sub OpenTextFile()

   filetoopen = Application.GetOpenFilename("Text Files (*.txt;*.csv), *.txt;*.csv")
   If filetoopen = Null Or filetoopen = Empty Then Exit Sub

   Workbooks.OpenText Filename:=filetoopen, _
   Origin:=65001, DataType:=xlDelimited, Comma:=True

End Sub

Origin:=65001 is UTF-8. Comma:True for .csv files distributed in colums

Save it in Personal.xlsb to have it always available. Personalise excel toolbar adding a macro call button and open files from there. You can add more formating to the macro, like column autofit , alignment,etc.

How to find available directory objects on Oracle 11g system?

The ALL_DIRECTORIES data dictionary view will have information about all the directories that you have access to. That includes the operating system path

SELECT owner, directory_name, directory_path
  FROM all_directories

How to make a Generic Type Cast function

Something like this?

public static T ConvertValue<T>(string value)
{
    return (T)Convert.ChangeType(value, typeof(T));
}

You can then use it like this:

int val = ConvertValue<int>("42");

Edit:

You can even do this more generic and not rely on a string parameter provided the type U implements IConvertible - this means you have to specify two type parameters though:

public static T ConvertValue<T,U>(U value) where U : IConvertible
{
    return (T)Convert.ChangeType(value, typeof(T));
}

I considered catching the InvalidCastException exception that might be raised by Convert.ChangeType() - but what would you return in this case? default(T)? It seems more appropriate having the caller deal with the exception.

How do I force Maven to use my local repository rather than going out to remote repos to retrieve artifacts?

To truly force maven to only use your local repo, you can run with mvn <goals> -o. The -o tells maven to let you work "offline", and it will stay off the network.

Solution for "Fatal error: Maximum function nesting level of '100' reached, aborting!" in PHP

Rather than going for a recursive function calls, work with a queue model to flatten the structure.

$queue = array('http://example.com/first/url');
while (count($queue)) {
    $url = array_shift($queue);

    $queue = array_merge($queue, find_urls($url));
}

function find_urls($url)
{
    $urls = array();

    // Some logic filling the variable

    return $urls;
}

There are different ways to handle it. You can keep track of more information if you need some insight about the origin or paths traversed. There are also distributed queues that can work off a similar model.

How to obtain the query string from the current URL with JavaScript?

You can use this function, for split string from ?id=

 function myfunction(myvar){
  var urls = myvar;
  var myurls = urls.split("?id=");
  var mylasturls = myurls[1];
  var mynexturls = mylasturls.split("&");
  var url = mynexturls[0];
  alert(url)
}
myfunction(window.top.location.href);
myfunction("http://www.myname.com/index.html?id=dance&emp;cid=in_social_facebook-hhp-food-moonlight-influencer_s7_20160623");

here is the fiddle

afxwin.h file is missing in VC++ Express Edition

I see the question is about Express Edition, but this topic is easy to pop up in Google Search, and doesn't have a solution for other editions.

So. If you run into this problem with any VS Edition except Express, you can rerun installation and include MFC files.

detect back button click in browser

Please try this (if the browser does not support "onbeforeunload"):

jQuery(document).ready(function($) {

  if (window.history && window.history.pushState) {

    $(window).on('popstate', function() {
      var hashLocation = location.hash;
      var hashSplit = hashLocation.split("#!/");
      var hashName = hashSplit[1];

      if (hashName !== '') {
        var hash = window.location.hash;
        if (hash === '') {
          alert('Back button was pressed.');
        }
      }
    });

    window.history.pushState('forward', null, './#forward');
  }

});

Uncaught TypeError: Cannot read property 'split' of undefined

og_date = "2012-10-01";
console.log(og_date); // => "2012-10-01"

console.log(og_date.split('-')); // => [ '2012', '10', '01' ]

og_date.value would only work if the date were stored as a property on the og_date object. Such as: var og_date = {}; og_date.value="2012-10-01"; In that case, your original console.log would work.

Django - after login, redirect user to his custom page --> mysite.com/username

Yes! In your settings.py define the following

LOGIN_REDIRECT_URL = '/your-path'

And have '/your-path' be a simple View that looks up self.request.user and does whatever logic it needs to return a HttpResponseRedirect object.

A better way might be to define a simple URL like '/simple' that does the lookup logic there. The URL looks more beautiful, saves you some work, etc.

Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)

I faced the same problem too and I found out that I selected "new Win32 application" instead of "new Win32 console application". Problem solved when I switched. Hope this can help you.

Understanding inplace=True

If you don't use inplace=True or you use inplace=False you basically get back a copy.

So for instance:

testdf.sort_values(inplace=True, by='volume', ascending=False)

will alter the structure with the data sorted in descending order.

then:

testdf2 = testdf.sort_values( by='volume', ascending=True)

will make testdf2 a copy. the values will all be the same but the sort will be reversed and you will have an independent object.

then given another column, say LongMA and you do:

testdf2.LongMA = testdf2.LongMA -1

the LongMA column in testdf will have the original values and testdf2 will have the decrimented values.

It is important to keep track of the difference as the chain of calculations grows and the copies of dataframes have their own lifecycle.

Rendering HTML elements to <canvas>

The CSS element() function may eventually help some people here, even though it's not a direct answer to the question. It allows you to use an element (and all children, including videos, cross-domain iframes, etc.) as a background image (and anywhere else that you'd normally use url(...) in your CSS code). Here's a blog post that shows what you can do with it.

It has been implemented in Firefox since 2011, and is being considered in Chromium/Chrome (don't forget to give the issue a star if you care about this functionality).

How can I check if a Perl array contains a particular value?

You can use smartmatch feature in Perl 5.10 as follows:

For literal value lookup doing below will do the trick.

if ( "value" ~~ @array ) 

For scalar lookup, doing below will work as above.

if ($val ~~ @array)

For inline array doing below, will work as above.

if ( $var ~~ ['bar', 'value', 'foo'] ) 

In Perl 5.18 smartmatch is flagged as experimental therefore you need to turn off the warnings by turning on experimental pragma by adding below to your script/module:

use experimental 'smartmatch';

Alternatively if you want to avoid the use of smartmatch - then as Aaron said use:

if ( grep( /^$value$/, @array ) ) {
  #TODO:
}

Eclipse: The resource is not on the build path of a Java project

You can add the src folder to build path by:

  1. Select Java perspective.
  2. Right click on src folder.
  3. Select Build Path > Use a source folder.

And you are done. Hope this help.

EDIT: Refer to the Eclipse documentation

How to convert a file into a dictionary?

def get_pair(line):
    key, sep, value = line.strip().partition(" ")
    return int(key), value

with open("file.txt") as fd:    
    d = dict(get_pair(line) for line in fd)

React JS onClick event handler

_x000D_
_x000D_
import React from 'react';_x000D_
_x000D_
class MyComponent extends React.Component {_x000D_
_x000D_
  getComponent(event) {_x000D_
      event.target.style.backgroundColor = '#ccc';_x000D_
      _x000D_
      // or you can write_x000D_
      //arguments[0].target.style.backgroundColor = '#ccc';_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return(_x000D_
       <div>_x000D_
         <ul>_x000D_
            <li onClick={this.getComponent.bind(this)}>Component 1</li>_x000D_
         </ul>_x000D_
       </div>_x000D_
    );_x000D_
  }_x000D_
}_x000D_
_x000D_
export { MyComponent };  // use this to be possible in future imports with {} like: import {MyComponent} from './MyComponent'_x000D_
export default MyComponent;
_x000D_
_x000D_
_x000D_

Understanding unique keys for array children in React.js

I was running into this error message because of <></> being returned for some items in the array when instead null needs to be returned.

Convert timestamp to readable date/time PHP

echo 'Le '.date('d/m/Y', 1234567890).' &agrave; '.date('H:i:s', 1234567890);

Count characters in textarea

$(document).ready(function() {
    var count = $("h1").text().length;
    alert(count);
});

Also, you can put your own element id or class instead of "h1" and length event count your characters of text area string ?

Entity Framework code first unique column

Solution for EF4.3

Unique UserName

Add data annotation over column as:

 [Index(IsUnique = true)]
 [MaxLength(255)] // for code-first implementations
 public string UserName{get;set;}

Unique ID , I have added decoration [Key] over my column and done. Same solution as described here: https://msdn.microsoft.com/en-gb/data/jj591583.aspx

IE:

[Key]
public int UserId{get;set;}

Alternative answers

using data annotation

[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column("UserId")]

using mapping

  mb.Entity<User>()
            .HasKey(i => i.UserId);
        mb.User<User>()
          .Property(i => i.UserId)
          .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
          .HasColumnName("UserId");

sed whole word search and replace

In one of my machine, delimiting the word with "\b" (without the quotes) did not work. The solution was to use "\<" for starting delimiter and "\>" for ending delimiter.

To explain with Joakim Lundberg's example:

$ echo "bar embarassment" | sed "s/\<bar\>/no bar/g"
no bar embarassment

Why Choose Struct Over Class?

I wouldn't say that structs offer less functionality.

Sure, self is immutable except in a mutating function, but that's about it.

Inheritance works fine as long as you stick to the good old idea that every class should be either abstract or final.

Implement abstract classes as protocols and final classes as structs.

The nice thing about structs is that you can make your fields mutable without creating shared mutable state because copy on write takes care of that :)

That's why the properties / fields in the following example are all mutable, which I would not do in Java or C# or swift classes.

Example inheritance structure with a bit of dirty and straightforward usage at the bottom in the function named "example":

protocol EventVisitor
{
    func visit(event: TimeEvent)
    func visit(event: StatusEvent)
}

protocol Event
{
    var ts: Int64 { get set }

    func accept(visitor: EventVisitor)
}

struct TimeEvent : Event
{
    var ts: Int64
    var time: Int64

    func accept(visitor: EventVisitor)
    {
        visitor.visit(self)
    }
}

protocol StatusEventVisitor
{
    func visit(event: StatusLostStatusEvent)
    func visit(event: StatusChangedStatusEvent)
}

protocol StatusEvent : Event
{
    var deviceId: Int64 { get set }

    func accept(visitor: StatusEventVisitor)
}

struct StatusLostStatusEvent : StatusEvent
{
    var ts: Int64
    var deviceId: Int64
    var reason: String

    func accept(visitor: EventVisitor)
    {
        visitor.visit(self)
    }

    func accept(visitor: StatusEventVisitor)
    {
        visitor.visit(self)
    }
}

struct StatusChangedStatusEvent : StatusEvent
{
    var ts: Int64
    var deviceId: Int64
    var newStatus: UInt32
    var oldStatus: UInt32

    func accept(visitor: EventVisitor)
    {
        visitor.visit(self)
    }

    func accept(visitor: StatusEventVisitor)
    {
        visitor.visit(self)
    }
}

func readEvent(fd: Int) -> Event
{
    return TimeEvent(ts: 123, time: 56789)
}

func example()
{
    class Visitor : EventVisitor
    {
        var status: UInt32 = 3;

        func visit(event: TimeEvent)
        {
            print("A time event: \(event)")
        }

        func visit(event: StatusEvent)
        {
            print("A status event: \(event)")

            if let change = event as? StatusChangedStatusEvent
            {
                status = change.newStatus
            }
        }
    }

    let visitor = Visitor()

    readEvent(1).accept(visitor)

    print("status: \(visitor.status)")
}

Validate a username and password against Active Directory?

Windows authentication can fail for various reasons: an incorrect user name or password, a locked account, an expired password, and more. To distinguish between these errors, call the LogonUser API function via P/Invoke and check the error code if the function returns false:

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;

using Microsoft.Win32.SafeHandles;

public static class Win32Authentication
{
    private class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
    {
        private SafeTokenHandle() // called by P/Invoke
            : base(true)
        {
        }

        protected override bool ReleaseHandle()
        {
            return CloseHandle(this.handle);
        }
    }

    private enum LogonType : uint
    {
        Network = 3, // LOGON32_LOGON_NETWORK
    }

    private enum LogonProvider : uint
    {
        WinNT50 = 3, // LOGON32_PROVIDER_WINNT50
    }

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool CloseHandle(IntPtr handle);

    [DllImport("advapi32.dll", SetLastError = true)]
    private static extern bool LogonUser(
        string userName, string domain, string password,
        LogonType logonType, LogonProvider logonProvider,
        out SafeTokenHandle token);

    public static void AuthenticateUser(string userName, string password)
    {
        string domain = null;
        string[] parts = userName.Split('\\');
        if (parts.Length == 2)
        {
            domain = parts[0];
            userName = parts[1];
        }

        SafeTokenHandle token;
        if (LogonUser(userName, domain, password, LogonType.Network, LogonProvider.WinNT50, out token))
            token.Dispose();
        else
            throw new Win32Exception(); // calls Marshal.GetLastWin32Error()
    }
}

Sample usage:

try
{
    Win32Authentication.AuthenticateUser("EXAMPLE\\user", "P@ssw0rd");
    // Or: Win32Authentication.AuthenticateUser("[email protected]", "P@ssw0rd");
}
catch (Win32Exception ex)
{
    switch (ex.NativeErrorCode)
    {
        case 1326: // ERROR_LOGON_FAILURE (incorrect user name or password)
            // ...
        case 1327: // ERROR_ACCOUNT_RESTRICTION
            // ...
        case 1330: // ERROR_PASSWORD_EXPIRED
            // ...
        case 1331: // ERROR_ACCOUNT_DISABLED
            // ...
        case 1907: // ERROR_PASSWORD_MUST_CHANGE
            // ...
        case 1909: // ERROR_ACCOUNT_LOCKED_OUT
            // ...
        default: // Other
            break;
    }
}

Note: LogonUser requires a trust relationship with the domain you're validating against.

How do you count the elements of an array in java

When defining an array, you are setting aside a block of memory to hold all the items you want to have in the array.

This will have a default value, depending on the type of the array member types.

What you can't do is find out the number of items that you have populated, except for tracking it in your own code.

Load More Posts Ajax Button in WordPress

UPDATE 24.04.2016.

I've created tutorial on my page https://madebydenis.com/ajax-load-posts-on-wordpress/ about implementing this on Twenty Sixteen theme, so feel free to check it out :)

EDIT

I've tested this on Twenty Fifteen and it's working, so it should be working for you.

In index.php (assuming that you want to show the posts on the main page, but this should work even if you put it in a page template) I put:

    <div id="ajax-posts" class="row">
        <?php
            $postsPerPage = 3;
            $args = array(
                    'post_type' => 'post',
                    'posts_per_page' => $postsPerPage,
                    'cat' => 8
            );

            $loop = new WP_Query($args);

            while ($loop->have_posts()) : $loop->the_post();
        ?>

         <div class="small-12 large-4 columns">
                <h1><?php the_title(); ?></h1>
                <p><?php the_content(); ?></p>
         </div>

         <?php
                endwhile;
        wp_reset_postdata();
         ?>
    </div>
    <div id="more_posts">Load More</div>

This will output 3 posts from category 8 (I had posts in that category, so I used it, you can use whatever you want to). You can even query the category you're in with

$cat_id = get_query_var('cat');

This will give you the category id to use in your query. You could put this in your loader (load more div), and pull with jQuery like

<div id="more_posts" data-category="<?php echo $cat_id; ?>">>Load More</div>

And pull the category with

var cat = $('#more_posts').data('category');

But for now, you can leave this out.

Next in functions.php I added

wp_localize_script( 'twentyfifteen-script', 'ajax_posts', array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'noposts' => __('No older posts found', 'twentyfifteen'),
));

Right after the existing wp_localize_script. This will load WordPress own admin-ajax.php so that we can use it when we call it in our ajax call.

At the end of the functions.php file I added the function that will load your posts:

function more_post_ajax(){

    $ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
    $page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;

    header("Content-Type: text/html");

    $args = array(
        'suppress_filters' => true,
        'post_type' => 'post',
        'posts_per_page' => $ppp,
        'cat' => 8,
        'paged'    => $page,
    );

    $loop = new WP_Query($args);

    $out = '';

    if ($loop -> have_posts()) :  while ($loop -> have_posts()) : $loop -> the_post();
        $out .= '<div class="small-12 large-4 columns">
                <h1>'.get_the_title().'</h1>
                <p>'.get_the_content().'</p>
         </div>';

    endwhile;
    endif;
    wp_reset_postdata();
    die($out);
}

add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');

Here I've added paged key in the array, so that the loop can keep track on what page you are when you load your posts.

If you've added your category in the loader, you'd add:

$cat = (isset($_POST['cat'])) ? $_POST['cat'] : '';

And instead of 8, you'd put $cat. This will be in the $_POST array, and you'll be able to use it in ajax.

Last part is the ajax itself. In functions.js I put inside the $(document).ready(); enviroment

var ppp = 3; // Post per page
var cat = 8;
var pageNumber = 1;


function load_posts(){
    pageNumber++;
    var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
    $.ajax({
        type: "POST",
        dataType: "html",
        url: ajax_posts.ajaxurl,
        data: str,
        success: function(data){
            var $data = $(data);
            if($data.length){
                $("#ajax-posts").append($data);
                $("#more_posts").attr("disabled",false);
            } else{
                $("#more_posts").attr("disabled",true);
            }
        },
        error : function(jqXHR, textStatus, errorThrown) {
            $loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
        }

    });
    return false;
}

$("#more_posts").on("click",function(){ // When btn is pressed.
    $("#more_posts").attr("disabled",true); // Disable the button, temp.
    load_posts();
});

Saved it, tested it, and it works :)

Images as proof (don't mind the shoddy styling, it was done quickly). Also post content is gibberish xD

enter image description here

enter image description here

enter image description here

UPDATE

For 'infinite load' instead on click event on the button (just make it invisible, with visibility: hidden;) you can try with

$(window).on('scroll', function () {
    if ($(window).scrollTop() + $(window).height()  >= $(document).height() - 100) {
        load_posts();
    }
});

This should run the load_posts() function when you're 100px from the bottom of the page. In the case of the tutorial on my site you can add a check to see if the posts are loading (to prevent firing of the ajax twice), and you can fire it when the scroll reaches the top of the footer

$(window).on('scroll', function(){
    if($('body').scrollTop()+$(window).height() > $('footer').offset().top){
        if(!($loader.hasClass('post_loading_loader') || $loader.hasClass('post_no_more_posts'))){
                load_posts();
        }
    }
});

Now the only drawback in these cases is that you could never scroll to the value of $(document).height() - 100 or $('footer').offset().top for some reason. If that should happen, just increase the number where the scroll goes to.

You can easily check it by putting console.logs in your code and see in the inspector what they throw out

$(window).on('scroll', function () {
    console.log($(window).scrollTop() + $(window).height());
    console.log($(document).height() - 100);
    if ($(window).scrollTop() + $(window).height()  >= $(document).height() - 100) {
        load_posts();
    }
});

And just adjust accordingly ;)

Hope this helps :) If you have any questions just ask.

Java finished with non-zero exit value 2 - Android Gradle

In my case, the problem was that the new library (gradle dependency) that I had added was relying on some other dependencies and two of those underlying dependencies were conflicting/clashing with some dependencies of other libraries/dependencies in my build script. Specifically, I added Apache Commons Validator (for email validation), and two of its dependencies (Apache Commons Logging and Apache Commons Collections) were conflicting with those used by Robolectric (because different versions of same libraries were present in my build path). So I excluded those conflicting versions of dependencies (modules) when adding the new dependency (the Validator):

compile ('commons-validator:commons-validator:1.4.1') {
    exclude module: 'commons-logging'
    exclude module: 'commons-collections'
}

You can see the dependencies of your gradle module(s) (you might have only one module in your project) using the following gradle command (I use the gradle wrapper that gets created for you if you have created your project in Android Studio/Intellij Idea). Run this command in your project's root directory:

./gradlew :YOUR-MODULE-NAME:dependencies

After adding those exclude directives and retrying to run, I got a duplicate file error for NOTICE.txtthat is used by some apache commons libraries like Logging and Collections. I had to exclude that text file when packaging. In my build.gradle, I added:

packagingOptions {
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/notice.txt'
    exclude 'META-INF/NOTICE.txt'
}

It turned out that the new library (the Validator) can work with slightly older versions of its dependencies/modules (which are already imported into my build path by another library (Robolectric)). This was the case with this specific library, but other libraries might be using the latest API of the underlying dependencies (in which case you have to try to see if the other libraries that rely on the conflicting module/dependency are able to work with the newer version (by excluding the older version of the module/dependecy under those libraries's entries)).

How to refresh table contents in div using jquery/ajax

You can load HTML page partial, in your case is everything inside div#mytable.

setTimeout(function(){
   $( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds

more information read this http://api.jquery.com/load/

Update Code (if you don't want it auto-refresh)

<button id="refresh-btn">Refresh Table</button>

<script>
$(document).ready(function() {

   function RefreshTable() {
       $( "#mytable" ).load( "your-current-page.html #mytable" );
   }

   $("#refresh-btn").on("click", RefreshTable);

   // OR CAN THIS WAY
   //
   // $("#refresh-btn").on("click", function() {
   //    $( "#mytable" ).load( "your-current-page.html #mytable" );
   // });


});
</script>

Is there a list of Pytz Timezones?

They appear to be populated by the tz database time zones found here.

enter image description here

Java - how do I write a file to a specified directory

The best practice is using File.separator in the paths.

What does the error "JSX element type '...' does not have any construct or call signatures" mean?

If you really don't care about props then the widest possible type is React.ReactType.

This would allow passing native dom elements as string. React.ReactType covers all of these:

renderGreeting('button');
renderGreeting(() => 'Hello, World!');
renderGreeting(class Foo extends React.Component {
   render() {
      return 'Hello, World!'
   }
});

TSQL CASE with if comparison in SELECT statement

Should be:

SELECT registrationDate, 
       (SELECT CASE
        WHEN COUNT(*)< 2 THEN 'Ama'
        WHEN COUNT(*)< 5 THEN 'SemiAma' 
        WHEN COUNT(*)< 7 THEN 'Good'  
        WHEN COUNT(*)< 9 THEN 'Better' 
        WHEN COUNT(*)< 12 THEN 'Best'
        ELSE 'Outstanding'
        END as a FROM Articles 
        WHERE Articles.userId = Users.userId) as ranking,
        (SELECT COUNT(*) 
        FROM Articles 
        WHERE userId = Users.userId) as articleNumber,
hobbies, etc...
FROM USERS

Differences between "java -cp" and "java -jar"?

Like already said, the -cp is just for telling the jvm in the command line which class to use for the main thread and where it can find the libraries (define classpath). In -jar it expects the class-path and main-class to be defined in the jar file manifest. So other is for defining things in command line while other finding them inside the jar manifest. There is no difference in performance. You can't use them at the same time, -jar will override the -cp.

Though even if you use -cp, it will still check the manifest file. So you can define some of the class-paths in the manifest and some in the command line. This is particularly useful when you have a dependency on some 3rd party jar, which you might not provide with your build or don't want to provide (expecting it to be found already in the system where it's to be installed for example). So you can use it to provide external jars. It's location may vary between systems or it may even have a different version on different system (but having the same interfaces). This way you can build the app with other version and add the actual 3rd party dependency to class-path on the command line when running it on different systems.

What is the best Java email address validation method?

Using the official java email package is the easiest:

public static boolean isValidEmailAddress(String email) {
   boolean result = true;
   try {
      InternetAddress emailAddr = new InternetAddress(email);
      emailAddr.validate();
   } catch (AddressException ex) {
      result = false;
   }
   return result;
}

AngularJS ui router passing data between states without URL

The params object is included in $stateParams, but won't be part of the url.

1) In the route configuration:

$stateProvider.state('edit_user', {
    url: '/users/:user_id/edit',
    templateUrl: 'views/editUser.html',
    controller: 'editUserCtrl',
    params: {
        paramOne: { objectProperty: "defaultValueOne" },  //default value
        paramTwo: "defaultValueTwo"
    }
});

2) In the controller:

.controller('editUserCtrl', function ($stateParams, $scope) {       
    $scope.paramOne = $stateParams.paramOne;
    $scope.paramTwo = $stateParams.paramTwo;
});

3A) Changing the State from a controller

$state.go("edit_user", {
    user_id: 1,                
    paramOne: { objectProperty: "test_not_default1" },
    paramTwo: "from controller"
});

3B) Changing the State in html

<div ui-sref="edit_user({ user_id: 3, paramOne: { objectProperty: 'from_html1' }, paramTwo: 'fromhtml2' })"></div>

Example Plunker

How to programmatically set the ForeColor of a label to its default?

For example summer :

lblSummer.foreColor = color.Yellow;

Is there a way to link someone to a YouTube Video in HD 1080p quality?

No, this is not working. And it's not just for you, in case you spent the last hour trying to find an answer for having your embeded videos open in HD.

Question: Oh, but how do you know this is not working anymore and there is no other alternative to make embeded videos open in a different quality?

Answer: Just went to Google's official documentation regarding Youtube's player parameters and there is not a single parameter that allows you to change its quality.

Also, hd=1 doesn't work either. More info here.

Apparently Youtube analyses the width and height of the user's window (or iframe) and automatically sets the quality based on this.

UPDATE:

As of 10 of April of 2018 it still doesn't work (see my comment on the accepted answer for more details).

What I can see from comments is that it MAY work sometimes, but some others it doesn't. The accepted answer states that "it measures the network speed and the screen and player sizes". So, by that, we can understand that I CANNOT force HD as YouTube will still do whatever it wants in case of low network speed/screen resolution. From my perspective everyone saying it works just have false positives on their hands and on the occasion they tested it worked for some random reason not related to the vq parameter. If it was a valid parameter, Google would document it somewhere, and vq isn't documented anywhere.

MongoDB "root" user

Mongodb user management:

roles list:

read
readWrite
dbAdmin
userAdmin
clusterAdmin
readAnyDatabase
readWriteAnyDatabase
userAdminAnyDatabase
dbAdminAnyDatabase

create user:

db.createUser(user, writeConcern)

db.createUser({ user: "user",
  pwd: "pass",
  roles: [
    { role: "read", db: "database" } 
  ]
})

update user:

db.updateUser("user",{
  roles: [
    { role: "readWrite", db: "database" } 
  ]
})

drop user:

db.removeUser("user")

or

db.dropUser("user")

view users:

db.getUsers();

more information: https://docs.mongodb.com/manual/reference/security/#read

How to determine the longest increasing subsequence using dynamic programming?

Here is my Leetcode solution using Binary Search:->

class Solution:
    def binary_search(self,s,x):
        low=0
        high=len(s)-1
        flag=1
        while low<=high:
              mid=(high+low)//2
              if s[mid]==x:
                 flag=0
                 break
              elif s[mid]<x:
                  low=mid+1
              else:
                 high=mid-1
        if flag:
           s[low]=x
        return s

    def lengthOfLIS(self, nums: List[int]) -> int:
         if not nums:
            return 0
         s=[]
         s.append(nums[0])
         for i in range(1,len(nums)):
             if s[-1]<nums[i]:
                s.append(nums[i])
             else:
                 s=self.binary_search(s,nums[i])
         return len(s)

in iPhone App How to detect the screen resolution of the device

UIScreen class lets you find screen resolution in Points and Pixels.

Screen resolutions is measured in Points or Pixels. It should never be confused with screen size. A smaller screen size can have higher resolution.

UIScreen's 'bounds.width' return rectangular size in Points enter image description here

UIScreen's 'nativeBounds.width' return rectangular size in Pixels.This value is detected as PPI ( Point per inch ). Shows the sharpness & clarity of the Image on a device. enter image description here

You can use UIScreen class to detect all these values.

Swift3

// Normal Screen Bounds - Detect Screen size in Points.
let width = UIScreen.main.bounds.width
let height = UIScreen.main.bounds.height
print("\n width:\(width) \n height:\(height)")

// Native Bounds - Detect Screen size in Pixels.
let nWidth = UIScreen.main.nativeBounds.width
let nHeight = UIScreen.main.nativeBounds.height
print("\n Native Width:\(nWidth) \n Native Height:\(nHeight)")

Console

width:736.0 
height:414.0

Native Width:1080.0 
Native Height:1920.0

Swift 2.x

//Normal Bounds - Detect Screen size in Points.
    let width  = UIScreen.mainScreen.bounds.width
    let height = UIScreen.mainScreen.bounds.height

// Native Bounds - Detect Screen size in Pixels.
    let nWidth  = UIScreen.mainScreen.nativeBounds.width
    let nHeight = UIScreen.mainScreen.nativeBounds.height

ObjectiveC

// Normal Bounds - Detect Screen size in Points.
CGFloat *width  = [UIScreen mainScreen].bounds.size.width;
CGFloat *height = [UIScreen mainScreen].bounds.size.height;

// Native Bounds - Detect Screen size in Pixels.
CGFloat *width  = [UIScreen mainScreen].nativeBounds.size.width
CGFloat *height = [UIScreen mainScreen].nativeBounds.size.width

How do I add images in laravel view?

<img src="/images/yourfile.png">

Store your files in public/images directory.

Hidden features of Python

A slight misfeature of python. The normal fast way to join a list of strings together is,

''.join(list_of_strings)

scp copy directory to another server with private key auth

The command looks quite fine. Could you try to run -v (verbose mode) and then we can figure out what it is wrong on the authentication?

Also as mention in the other answer, maybe could be this issue - that you need to convert the keys (answered already here): How to convert SSH keypairs generated using PuttyGen(Windows) into key-pairs used by ssh-agent and KeyChain(Linux) OR http://winscp.net/eng/docs/ui_puttygen (depending what you need)

Converting integer to string in Python

Here is a simpler solution:

one = "1"
print(int(one))

Output console

>>> 1

In the above program, int() is used to convert the string representation of an integer.

Note: A variable in the format of string can be converted into an integer only if the variable is completely composed of numbers.

In the same way, str() is used to convert an integer to string.

number = 123567
a = []
a.append(str(number))
print(a) 

I used a list to print the output to highlight that variable (a) is a string.

Output console

>>> ["123567"]

But to understand the difference how a list stores a string and integer, view the below code first and then the output.

Code

a = "This is a string and next is an integer"
listone=[a, 23]
print(listone)

Output console

>>> ["This is a string and next is an integer", 23]

How to change UIButton image in Swift

From your Obc-C code I think you want to set an Image for button so try this way:

let playButton  = UIButton(type: .Custom)
if let image = UIImage(named: "play.png") {
    playButton.setImage(image, forState: .Normal)
}

In Short:

playButton.setImage(UIImage(named: "play.png"), forState: UIControlState.Normal)

For Swift 3:

let playButton  = UIButton(type: .custom)
playButton.setImage(UIImage(named: "play.png"), for: .normal)

How to add a title to a html select tag

Typically, I would suggest that you use the <optgroup> option, as that gives some nice styling and indenting to the element.

The HTML element creates a grouping of options within a element. (Source: MDN Web Docs: <optgroup>.

But, since an <optgroup> cannot be a selected value, you can make an <option selected disabled> and then stylize it with CSS so that it behaves like an <optgroup>....

_x000D_
_x000D_
.optionGroup {
    font-weight: bold;
    font-style: italic;
}
_x000D_
<select>
    <option class="optionGroup" selected disabled>Choose one</option>
    <option value="sydney" class="optionChild">&nbsp;&nbsp;&nbsp;&nbsp;Sydney</option>
    <option value="melbourne" class="optionChild">&nbsp;&nbsp;&nbsp;&nbsp;Melbourne</option>
    <option value="cromwell" class="optionChild">&nbsp;&nbsp;&nbsp;&nbsp;Cromwell</option>
    <option value="queenstown" class="optionChild">&nbsp;&nbsp;&nbsp;&nbsp;Queenstown</option>
</select>
_x000D_
_x000D_
_x000D_

How to ftp with a batch file?

The answer by 0x90h helped a lot...

I saved this file as u.ftp:

open 10.155.8.215 
user
password
lcd /D "G:\Subfolder\"
cd  folder/
binary
mget file.csv
disconnect
quit

I then ran this command:

ftp -i -s:u.ftp

And it worked!!!

Thanks a lot man :)

How to use UTF-8 in resource properties with ResourceBundle

As one suggested, i went through implementation of resource bundle.. but that did not help.. as the bundle was always called under en_US locale... i tried to set my default locale to a different language and still my implementation of resource bundle control was being called with en_US... i tried to put log messages and do a step through debug and see if a different local call was being made after i change locale at run time through xhtml and JSF calls... that did not happend... then i tried to do a system set default to a utf8 for reading files by my server (tomcat server).. but that caused pronlem as all my class libraries were not compiled under utf8 and tomcat started to read then in utf8 format and server was not running properly... then i ended up with implementing a method in my java controller to be called from xhtml files.. in that method i did the following:

        public String message(String key, boolean toUTF8) throws Throwable{
            String result = "";
            try{
                FacesContext context = FacesContext.getCurrentInstance();
                String message = context.getApplication().getResourceBundle(context, "messages").getString(key);

                result = message==null ? "" : toUTF8 ? new String(message.getBytes("iso8859-1"), "utf-8") : message;
            }catch(Throwable t){}
            return result;
        }

I was particularly nervous as this could slow down performance of my application... however, after implementing this, it looks like as if my application is faster now.. i think it is because, i am now directly accessing the properties instead of letting JSF parse its way into accessing properties... i specifically pass Boolean argument in this call because i know some of the properties would not be translated and do not need to be in utf8 format...

Now I have saved my properties file in UTF8 format and it is working fine as each user in my application has a referent locale preference.

How to use Macro argument as string literal?

You want to use the stringizing operator:

#define STRING(s) #s

int main()
{
    const char * cstr = STRING(abc); //cstr == "abc"
}

Android get Current UTC time

System.currentTimeMillis() does give you the number of milliseconds since January 1, 1970 00:00:00 UTC. The reason you see local times might be because you convert a Date instance to a string before using it. You can use DateFormats to convert Dates to Strings in any timezone:

DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("gmt"));
String gmtTime = df.format(new Date());

Also see this related question.

How can I create a dynamic button click event on a dynamic button?

You can create button in a simple way, such as:

Button button = new Button();
button.Click += new EventHandler(button_Click);

protected void button_Click (object sender, EventArgs e)
{
    Button button = sender as Button;
    // identify which button was clicked and perform necessary actions
}

But event probably will not fire, because the element/elements must be recreated at every postback or you will lose the event handler.

I tried this solution that verify that ViewState is already Generated and recreate elements at every postback,

for example, imagine you create your button on an event click:

    protected void Button_Click(object sender, EventArgs e)
    {
       if (Convert.ToString(ViewState["Generated"]) != "true")
        {
            CreateDynamicElements();
        }
    
    }

on postback, for example on page load, you should do this:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Convert.ToString(ViewState["Generated"]) == "true") {
            CreateDynamicElements();
        }
    }

In CreateDynamicElements() you can put all the elements you need, such as your button.

This worked very well for me.

public void CreateDynamicElements(){

    Button button = new Button();
    button.Click += new EventHandler(button_Click);

}

Correct syntax to compare values in JSTL <c:if test="${values.type}=='object'">

The comparison needs to be evaluated fully inside EL ${ ... }, not outside.

<c:if test="${values.type eq 'object'}">

As to the docs, those ${} things are not JSTL, but EL (Expression Language) which is a whole subject at its own. JSTL (as every other JSP taglib) is just utilizing it. You can find some more EL examples here.

<c:if test="#{bean.booleanValue}" />
<c:if test="#{bean.intValue gt 10}" />
<c:if test="#{bean.objectValue eq null}" />
<c:if test="#{bean.stringValue ne 'someValue'}" />
<c:if test="#{not empty bean.collectionValue}" />
<c:if test="#{not bean.booleanValue and bean.intValue ne 0}" />
<c:if test="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />

See also:


By the way, unrelated to the concrete problem, if I guess your intent right, you could also just call Object#getClass() and then Class#getSimpleName() instead of adding a custom getter.

<c:forEach items="${list}" var="value">
    <c:if test="${value['class'].simpleName eq 'Object'}">
        <!-- code here -->
    </c:if>
</c:forEeach>

See also:

How to create a custom scrollbar on a div (Facebook style)

Facebook uses a very clever technique I described in context of my scrollbar plugin jsFancyScroll:

The scrolled content is actually scrolled natively by the browser scrolling mechanisms while the native scrollbar is hidden by using overflow definitions and the custom scrollbar is kept in sync by bi-directional event listening.

Feel free to use my plugin for your project: :)

https://github.com/leoselig/jsFancyScroll/

I highly recommend it over plugins such as TinyScrollbar that come with terrible performance issues!

How can I pass command-line arguments to a Perl program?

You can access them directly, by assigning the special variable @ARGV to a list of variables. So, for example:

( $st, $prod, $ar, $file, $chart, $e, $max, $flag ,$id) = @ARGV;

perl tmp.pl 1 2 3 4 5

enter image description here

How do I format XML in Notepad++?

Since I see lots of comments about people having problems with the plugin, I thought I'd mention the work around that I use.

I just use one of the online sites for XML viewing (I use https://codebeautify.org/xmlviewer, but there are plenty out there) as follows:

  1. Paste the XML content in the input window
  2. Click the "Beautify / Format" button
  3. Copy formatted XML output from the result window
  4. Paste in Notepad++

I don't know if it qualifies as answering the OP's question exactly, but it's very simple and easy for anyone who is having problems with the plugin.

Deleting rows from parent and child tables

If the children have FKs linking them to the parent, then you can use DELETE CASCADE on the parent.

e.g.

CREATE TABLE supplier 
( supplier_id numeric(10) not null, 
 supplier_name varchar2(50) not null, 
 contact_name varchar2(50),  
 CONSTRAINT supplier_pk PRIMARY KEY (supplier_id) 
); 



CREATE TABLE products 
( product_id numeric(10) not null, 
 supplier_id numeric(10) not null, 
 CONSTRAINT fk_supplier 
   FOREIGN KEY (supplier_id) 
  REFERENCES supplier(supplier_id) 
  ON DELETE CASCADE 
); 

Delete the supplier, and it will delate all products for that supplier

MySQL combine two columns into one column

This is the only solution that would work for me, when I required a space in between the columns being merged.

select concat(concat(column1,' '), column2)

How do I make a JSON object with multiple arrays?

On the outermost level, a JSON object starts with a { and end with a }.

Sample data:

{
    "cars": {
        "Nissan": [
            {"model":"Sentra", "doors":4},
            {"model":"Maxima", "doors":4},
            {"model":"Skyline", "doors":2}
        ],
        "Ford": [
            {"model":"Taurus", "doors":4},
            {"model":"Escort", "doors":4}
        ]
    }
}

If the JSON is assigned to a variable called data, then accessing it would be like the following:

data.cars['Nissan'][0].model   // Sentra
data.cars['Nissan'][1].model   // Maxima
data.cars['Nissan'][2].doors   // 2

for (var make in data.cars) {
    for (var i = 0; i < data.cars[make].length; i++) {
        var model = data.cars[make][i].model;
        var doors = data.cars[make][i].doors;
        alert(make + ', ' + model + ', ' + doors);
    }
}

Another approach (using an associative array for car models rather than an indexed array):

{
    "cars": {
        "Nissan": {
            "Sentra": {"doors":4, "transmission":"automatic"},
            "Maxima": {"doors":4, "transmission":"automatic"}
        },
        "Ford": {
            "Taurus": {"doors":4, "transmission":"automatic"},
            "Escort": {"doors":4, "transmission":"automatic"}
        }
    }
}

data.cars['Nissan']['Sentra'].doors   // 4
data.cars['Nissan']['Maxima'].doors   // 4
data.cars['Nissan']['Maxima'].transmission   // automatic

for (var make in data.cars) {
    for (var model in data.cars[make]) {
        var doors = data.cars[make][model].doors;
        alert(make + ', ' + model + ', ' + doors);
    }
}

Edit:

Correction: A JSON object starts with { and ends with }, but it's also valid to have a JSON array (on the outermost level), that starts with [ and ends with ].

Also, significant syntax errors in the original JSON data have been corrected: All key names in a JSON object must be in double quotes, and all string values in a JSON object or a JSON array must be in double quotes as well.

See:

How may I reference the script tag that loaded the currently-executing script?

If you can assume the file name of the script, you can find it. I've only really tested the following function in Firefox so far.

  function findMe(tag, attr, file) {
    var tags = document.getElementsByTagName(tag);
    var r = new RegExp(file + '$');
    for (var i = 0;i < tags.length;i++) {
      if (r.exec(tags[i][attr])) {
        return tags[i][attr];
      }
    }
  };
  var element = findMe('script', 'src', 'scripts.js');

How do I detect whether 32-bit Java is installed on x64 Windows, only looking at the filesystem and registry?

If it is not Oracle's Java, you may not be able to tell. When I install Oracle Java 64-bit, the files go into C:\Program Files\Java, but when I install a 32-bit version, they default to C:\Program Files (x86)\Java instead. Of course, the person who installed Java could have overridden those defaults.

Cannot set property 'display' of undefined

document.getElementsByClassName('btn-pageMenu') delivers a nodeList. You should use: document.getElementsByClassName('btn-pageMenu')[0].style.display (if it's the first element from that list you want to change.

If you want to change style.display for all nodes loop through the list:

var elems = document.getElementsByClassName('btn-pageMenu');
for (var i=0;i<elems.length;i+=1){
  elems[i].style.display = 'block';
}

to be complete: if you use jquery it is as simple as:

?$('.btn-pageMenu').css('display'???????????????????????????,'block');??????

Send JSON data with jQuery

It gets serialized so that the URI can read the name value pairs in the POST request by default. You could try setting processData:false to your list of params. Not sure if that would help.

How to set the color of an icon in Angular Material?

In the component.css or app.css add Icon Color styles

.material-icons.color_green { color: #00FF00; }
.material-icons.color_white { color: #FFFFFF; }

In the component.html set the icon class

<mat-icon class="material-icons color_green">games</mat-icon>
<mat-icon class="material-icons color_white">cloud</mat-icon>

ng build

Python: BeautifulSoup - get an attribute value based on the name attribute

theharshest's answer is the best solution, but FYI the problem you were encountering has to do with the fact that a Tag object in Beautiful Soup acts like a Python dictionary. If you access tag['name'] on a tag that doesn't have a 'name' attribute, you'll get a KeyError.

How to animate GIFs in HTML document?

Agreed with Yuri Tkachenko's answer.

I wanna point this out.

It's a pretty specific scenario. BUT it happens.

When you copy a gif before its loaded fully in some site like google images. it just gives the preview image address of that gif. Which is clearly not a gif.

So, make sure it ends with .gif extension

How can I install packages using pip according to the requirements.txt file from a local directory?

First of all, create a virtual environment.

In Python 3.6

virtualenv --python=/usr/bin/python3.6 <path/to/new/virtualenv/>

In Python 2.7

virtualenv --python=/usr/bin/python2.7 <path/to/new/virtualenv/>

Then activate the environment and install all the packages available in the requirement.txt file.

source <path/to/new/virtualenv>/bin/activate
pip install -r <path/to/requirement.txt>

How to find the size of integer array

If the array is a global, static, or automatic variable (int array[10];), then sizeof(array)/sizeof(array[0]) works.

If it is a dynamically allocated array (int* array = malloc(sizeof(int)*10);) or passed as a function argument (void f(int array[])), then you cannot find its size at run-time. You will have to store the size somewhere.
Note that sizeof(array)/sizeof(array[0]) compiles just fine even for the second case, but it will silently produce the wrong result.

How to blur background images in Android

The easiest way to do that is use a library. Take a look at this one: https://github.com/wasabeef/Blurry

With the library you only need to do this:

Blurry.with(context)
  .radius(10)
  .sampling(8)
  .color(Color.argb(66, 255, 255, 0))
  .async()
  .onto(rootView);

Parsing JSON with Unix tools

I can not use any of the answers here. No available jq, no shell arrays, no declare, no grep -P, no lookbehind and lookahead, no Python, no Perl, no Ruby, no - not even Bash... Remaining answers simply do not work well. JavaScript sounded familiar, but the tin says Nescaffe - so it is a no go, too :) Even if available, for my simple need - they would be overkill and slow.

Yet, it is extremely important for me to get many variables from the json formatted reply of my modem. I am doing it in a sh with very trimmed down BusyBox at my routers! No problems using awk alone: just set delimiters and read the data. For a single variable, that is all!

awk 'BEGIN { FS="\""; RS="," }; { if ($2 == "login") {print $4} }' test.json

Remember I have no arrays? I had to assign within the awk parsed data to the 11 variables which I need in a shell script. Wherever I looked, that was said to be an impossible mission. No problem with that, too.

My solution is simple. This code will: 1) parse .json file from the question (actually, I have borrowed a working data sample from the most upvoted answer) and pick out the quoted data, plus 2) create shell variables from within the awk assigning free named shell variable names.

eval $( curl -s 'https://api.github.com/users/lambda' | 
awk ' BEGIN { FS="\""; RS="," };
{
    if ($2 == "login") { print "Login=\""$4"\"" }
    if ($2 == "name") { print "Name=\""$4"\"" }
    if ($2 == "updated_at") { print "Updated=\""$4"\"" }
}' )
echo "$Login, $Name, $Updated"

No problems with blanks within. In my use, the same command parses a long single line output. As eval is used, this solution is suited for trusted data only. It is simple to adapt it to pickup unquoted data. For huge number of variables, marginal speed gain can be achieved using else if. Lack of array obviously means: no multiple records without extra fiddling. But where arrays are available, adapting this solution is a simple task.

@maikel sed answer almost works (but I can not comment on it). For my nicely formatted data - it works. Not so much with the example used here (missing quotes throw it off). It is complicated and difficult to modify. Plus, I do not like having to make 11 calls to extract 11 variables. Why? I timed 100 loops extracting 9 variables: the sed function took 48.99 sec and my solution took 0.91 sec! Not fair? Doing just a single extraction of 9 variables: 0.51 vs. 0.02 sec.

Does mobile Google Chrome support browser extensions?

Just use a different browser. Follow the steps given below to install Chrome extensions on your Android device.

Step 1: Open Google Play Store and download Yandex Browser. Install the browser on your phone.

Step 2: In the URL box of your new browser, open 'chrome.google.com/webstore’ by entering the same in the URL address.

Step 3: Look for the Chrome extension that you want and once you have it, tap on 'Add to Chrome.’

The added Chrome extension will now be automatically added to the Yandex browser.

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT maximum storage sizes

This is nice but doesn't answer the question:

"A VARCHAR should always be used instead of TINYTEXT." Tinytext is useful if you have wide rows - since the data is stored off the record. There is a performance overhead, but it does have a use.

How can I create C header files

  1. Open your favorite text editor
  2. Create a new file named whatever.h
  3. Put your function prototypes in it

DONE.

Example whatever.h

#ifndef WHATEVER_H_INCLUDED
#define WHATEVER_H_INCLUDED
int f(int a);
#endif

Note: include guards (preprocessor commands) added thanks to luke. They avoid including the same header file twice in the same compilation. Another possibility (also mentioned on the comments) is to add #pragma once but it is not guaranteed to be supported on every compiler.

Example whatever.c

#include "whatever.h"

int f(int a) { return a + 1; }

And then you can include "whatever.h" into any other .c file, and link it with whatever.c's object file.

Like this:

sample.c

#include "whatever.h"

int main(int argc, char **argv)
{
    printf("%d\n", f(2)); /* prints 3 */
    return 0;
}

To compile it (if you use GCC):

$ gcc -c whatever.c -o whatever.o
$ gcc -c sample.c -o sample.o

To link the files to create an executable file:

$ gcc sample.o whatever.o -o sample

You can test sample:

$ ./sample
3
$

Remove Sub String by using Python

>>> import re
>>> st = " i think mabe 124 + <font color=\"black\"><font face=\"Times New Roman\">but I don't have a big experience it just how I see it in my eyes <font color=\"green\"><font face=\"Arial\">fun stuff"
>>> re.sub("<.*?>","",st)
" i think mabe 124 + but I don't have a big experience it just how I see it in my eyes fun stuff"
>>> 

How to change lowercase chars to uppercase using the 'keyup' event?

Above answers are pretty good, just wanted to add short form for this

 <input type="text" name="input_text"  onKeyUP="this.value = this.value.toUpperCase();">

receiving json and deserializing as List of object at spring mvc controller

Here is the code that works for me. The key is that you need a wrapper class.

public class Person {

    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }

A PersonWrapper class

public class PersonWrapper {

    private List<Person> persons;

    /**
     * @return the persons
     */
    public List<Person> getPersons() {
        return persons;
    }

    /**
     * @param persons the persons to set
     */
    public void setPersons(List<Person> persons) {
        this.persons = persons;
    }
}

My Controller methods

@RequestMapping(value="person", method=RequestMethod.POST,consumes="application/json",produces="application/json")
    @ResponseBody
    public List<String> savePerson(@RequestBody PersonWrapper wrapper) {
        List<String> response = new ArrayList<String>();
        for (Person person: wrapper.getPersons()){
        personService.save(person);
         response.add("Saved person: " + person.toString());
    }
        return response;
    }

The request sent is json in POST

{"persons":[{"name":"shail1","age":"2"},{"name":"shail2","age":"3"}]}

And the response is

["Saved person: Person [name=shail1, age=2]","Saved person: Person [name=shail2, age=3]"]

Python assigning multiple variables to same value? list behavior

in your first example a = b = c = [1, 2, 3] you are really saying:

 'a' is the same as 'b', is the same as 'c' and they are all [1, 2, 3]

If you want to set 'a' equal to 1, 'b' equal to '2' and 'c' equal to 3, try this:

a, b, c = [1, 2, 3]

print(a)
--> 1
print(b)
--> 2
print(c)
--> 3

Hope this helps!

Get record counts for all tables in MySQL database

Like @Venkatramanan and others I found INFORMATION_SCHEMA.TABLES unreliable (using InnoDB, MySQL 5.1.44), giving different row counts each time I run it even on quiesced tables. Here's a relatively hacky (but flexible/adaptable) way of generating a big SQL statement you can paste into a new query, without installing Ruby gems and stuff.

SELECT CONCAT(
    'SELECT "', 
    table_name, 
    '" AS table_name, COUNT(*) AS exact_row_count FROM `', 
    table_schema,
    '`.`',
    table_name, 
    '` UNION '
) 
FROM INFORMATION_SCHEMA.TABLES 
WHERE table_schema = '**my_schema**';

It produces output like this:

SELECT "func" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.func UNION                         
SELECT "general_log" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.general_log UNION           
SELECT "help_category" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.help_category UNION       
SELECT "help_keyword" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.help_keyword UNION         
SELECT "help_relation" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.help_relation UNION       
SELECT "help_topic" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.help_topic UNION             
SELECT "host" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.host UNION                         
SELECT "ndb_binlog_index" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.ndb_binlog_index UNION 

Copy and paste except for the last UNION to get nice output like,

+------------------+-----------------+
| table_name       | exact_row_count |
+------------------+-----------------+
| func             |               0 |
| general_log      |               0 |
| help_category    |              37 |
| help_keyword     |             450 |
| help_relation    |             990 |
| help_topic       |             504 |
| host             |               0 |
| ndb_binlog_index |               0 |
+------------------+-----------------+
8 rows in set (0.01 sec)

How to deselect a selected UITableView cell?

use this code

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
 {
    //Change the selected background view of the cell.
     [tableView deselectRowAtIndexPath:indexPath animated:YES];
 }

Swift 3.0:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    //Change the selected background view of the cell.
    tableView.deselectRow(at: indexPath, animated: true)
}

Getting a HeadlessException: No X11 DISPLAY variable was set

This appears to be a more general SWING/AWT/JDK problem that just the JBOSS installer:

The accepted answer below solved the issue for me :

Unable to run java gui programs with ubuntu

("sudo apt-get install openjdk-6-jdk")

Android XXHDPI resources

The resolution is 480 dpi, the launcher icon is 144*144px all is scaled 3x respect to mdpi (so called "base", "baseline" or "normal") sizes.

Setting a max character length in CSS

Modern CSS Grid Answer

View the fully working code on CodePen. Given the following HTML:

<div class="container">
    <p>Several paragraphs of text...</p>
</div>

You can use CSS Grid to create three columns and tell the container to take a maximum width of 70 characters for the middle column which contains our paragraph.

.container
{
  display: grid;
  grid-template-columns: 1fr, 70ch 1fr;
}

p {
  grid-column: 2 / 3;
}

This is what it looks like (Checkout CodePen for a fully working example):

enter image description here

Here is another example where you can use minmax to set a range of values. On small screens the width will be set to 50 characters wide and on large screens it will be 70 characters wide.

.container
{
  display: grid;
  grid-template-columns: 1fr minmax(50ch, 70ch) 1fr;
}

p {
  grid-column: 2 / 3;
}

How to print_r $_POST array?

$_POST is already an array. Try this:

foreach ($_POST as $key => $value) {
    echo "<p>".$key."</p>";
    echo "<p>".$value."</p>";
    echo "<hr />";
} 

GET and POST methods with the same Action name in the same Controller

Since you cannot have two methods with the same name and signature you have to use the ActionName attribute:

[HttpGet]
public ActionResult Index()
{
  // your code
  return View();
}

[HttpPost]
[ActionName("Index")]
public ActionResult IndexPost()
{
  // your code
  return View();
}

Also see "How a Method Becomes An Action"

JavaScript chop/slice/trim off last character in string

You can, in fact, remove the last arr.length - 2 items of an array using arr.length = 2, which if the array length was 5, would remove the last 3 items.

Sadly, this does not work for strings, but we can use split() to split the string, and then join() to join the string after we've made any modifications.

_x000D_
_x000D_
var str = 'string'

String.prototype.removeLast = function(n) {
  var string = this.split('')
  string.length = string.length - n

  return string.join('')
}

console.log(str.removeLast(3))
_x000D_
_x000D_
_x000D_

Check if program is running with bash shell script?

If you want to execute that command, you should probably change:

PROCESS_NUM='ps -ef | grep "$1" | grep -v "grep" | wc -l'

to:

PROCESS_NUM=$(ps -ef | grep "$1" | grep -v "grep" | wc -l)

How to index an element of a list object in R

Indexing a list is done using double bracket, i.e. hypo_list[[1]] (e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table does not return a table but a dataframe (see value section in ?read.table). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.

Note: In R, the index for the first entry is a 1 (not 0 like in some other languages).

Dataframes

l <- list(anscombe, iris)   # put dfs in list
l[[1]]             # returns anscombe dataframe

anscombe[1:2, 2]   # access first two rows and second column of dataset
[1] 10  8

l[[1]][1:2, 2]     # the same but selecting the dataframe from the list first
[1] 10  8

Table objects

tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2)  # put tables in a list

tbl1[1:2]              # access first two elements of table 1 

Now with the list

l[[1]]                 # access first table from the list

1  2  3  4  5 
9 11 12  9  9 

l[[1]][1:2]            # access first two elements in first table

1  2 
9 11 

Find row in datatable with specific id

Hello just create a simple function that looks as shown below.. That returns all rows where the call parameter entered is valid or true.

 public  DataTable SearchRecords(string Col1, DataTable RecordDT_, int KeyWORD)
    {
        TempTable = RecordDT_;
        DataView DV = new DataView(TempTable);
        DV.RowFilter = string.Format(string.Format("Convert({0},'System.String')",Col1) + " LIKE '{0}'", KeyWORD);
        return DV.ToTable();
    }

and simply call it as shown below;

  DataTable RowsFound=SearchRecords("IdColumn", OriginalTable,5);

where 5 is the ID. Thanks..

JavaScript get element by name

You want this:

function validate() {
    var acc = document.getElementsByName('acc')[0].value;
    var pass = document.getElementsByName('pass')[0].value;

    alert (acc);
}

AttributeError: 'str' object has no attribute 'strftime'

you should change cr_date(str) to datetime object then you 'll change the date to the specific format:

cr_date = '2013-10-31 18:23:29.000227'
cr_date = datetime.datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
cr_date = cr_date.strftime("%m/%d/%Y")

Xcode Error: "The app ID cannot be registered to your development team."

I was able to get the original bundle identifier to work on my paid team membership account (after having it assigned to my personal team) by revoking the personal team signing certificate that was assigned to the same account id.

  1. On the Apple Developer website sign in with the paid account it, go to Certificates, IDs & Profiles.
  2. Click the personal team certificate.
  3. Click the Revoke button.
  4. Go back to XCode and try signing again. A new certificate will be generated that should work with the bundle id.

This won't work if you still need the certificate for other apps.

Is it possible to hide the cursor in a webpage using CSS or Javascript?

Pointer Lock API

While the cursor: none CSS solution is definitely a solid and easy workaround, if your actual goal is to remove the default cursor while your web application is being used, or implement your own interpretation of raw mouse movement (for FPS games, for example), you might want to consider using the Pointer Lock API instead.

You can use requestPointerLock on an element to remove the cursor, and redirect all mousemove events to that element (which you may or may not handle):

document.body.requestPointerLock();

To release the lock, you can use exitPointerLock:

document.exitPointerLock();

Additional notes

No cursor, for real

This is a very powerful API call. It not only renders your cursor invisible, but it actually removes your operating system's native cursor. You won't be able to select text, or do anything with your mouse (except listening to some mouse events in your code) until the pointer lock is released (either by using exitPointerLock or pressing ESC in some browsers).

That is, you cannot leave the window with your cursor for it to show again, as there is no cursor.

Restrictions

As mentioned above, this is a very powerful API call, and is thus only allowed to be made in response to some direct user-interaction on the web, such as a click; for example:

document.addEventListener("click", function () {
    document.body.requestPointerLock();
});

Also, requestPointerLock won't work from a sandboxed iframe unless the allow-pointer-lock permission is set.

User-notifications

Some browsers will prompt the user for a confirmation before the lock is engaged, some will simply display a message. This means pointer lock might not activate right away after the call. However, the actual activation of pointer locking can be listened to by listening to the pointerchange event on the element on which requestPointerLock was called:

document.body.addEventListener("pointerlockchange", function () {
    if (document.pointerLockElement === document.body) {
        // Pointer is now locked to <body>.
    }
});

Most browsers will only display the message once, but Firefox will occasionally spam the message on every single call. AFAIK, this can only be worked around by user-settings, see Disable pointer-lock notification in Firefox.

Listening to raw mouse movement

The Pointer Lock API not only removes the mouse, but instead redirects raw mouse movement data to the element requestPointerLock was called on. This can be listened to simply by using the mousemove event, then accessing the movementX and movementY properties on the event object:

document.body.addEventListener("mousemove", function (e) {
    console.log("Moved by " + e.movementX + ", " + e.movementY);
});

Difference between Running and Starting a Docker container

Explanation with an example:

Consider you have a game (iso) image in your computer.

When you run (mount your image as a virtual drive), a virtual drive is created with all the game contents in the virtual drive and the game installation file is automatically launched. [Running your docker image - creating a container and then starting it.]

But when you stop (similar to docker stop) it, the virtual drive still exists but stopping all the processes. [As the container exists till it is not deleted]

And when you do start (similar to docker start), from the virtual drive the games files start its execution. [starting the existing container]

In this example - The game image is your Docker image and virtual drive is your container.

How can I use a carriage return in a HTML tooltip?

If you are using jQuery :

$(td).attr("title", "One \n Two \n Three");

will work.

tested in IE-9 : working.

How do I use a C# Class Library in a project?

  1. Add a reference to your library
  2. Import the namespace
  3. Consume the types in your library

How do I return multiple values from a function?

I vote for the dictionary.

I find that if I make a function that returns anything more than 2-3 variables I'll fold them up in a dictionary. Otherwise I tend to forget the order and content of what I'm returning.

Also, introducing a 'special' structure makes your code more difficult to follow. (Someone else will have to search through the code to find out what it is)

If your concerned about type look up, use descriptive dictionary keys, for example, 'x-values list'.

def g(x):
  y0 = x + 1
  y1 = x * 3
  y2 = y0 ** y3
  return {'y0':y0, 'y1':y1 ,'y2':y2 }

Column count doesn't match value count at row 1

  1. you missed the comma between two values or column name
  2. you put extra values or an extra column name

Differences between "BEGIN RSA PRIVATE KEY" and "BEGIN PRIVATE KEY"

See https://polarssl.org/kb/cryptography/asn1-key-structures-in-der-and-pem (search the page for "BEGIN RSA PRIVATE KEY") (archive link for posterity, just in case).

BEGIN RSA PRIVATE KEY is PKCS#1 and is just an RSA key. It is essentially just the key object from PKCS#8, but without the version or algorithm identifier in front. BEGIN PRIVATE KEY is PKCS#8 and indicates that the key type is included in the key data itself. From the link:

The unencrypted PKCS#8 encoded data starts and ends with the tags:

-----BEGIN PRIVATE KEY-----
BASE64 ENCODED DATA
-----END PRIVATE KEY-----

Within the base64 encoded data the following DER structure is present:

PrivateKeyInfo ::= SEQUENCE {
  version         Version,
  algorithm       AlgorithmIdentifier,
  PrivateKey      BIT STRING
}

AlgorithmIdentifier ::= SEQUENCE {
  algorithm       OBJECT IDENTIFIER,
  parameters      ANY DEFINED BY algorithm OPTIONAL
}

So for an RSA private key, the OID is 1.2.840.113549.1.1.1 and there is a RSAPrivateKey as the PrivateKey key data bitstring.

As opposed to BEGIN RSA PRIVATE KEY, which always specifies an RSA key and therefore doesn't include a key type OID. BEGIN RSA PRIVATE KEY is PKCS#1:

RSA Private Key file (PKCS#1)

The RSA private key PEM file is specific for RSA keys.

It starts and ends with the tags:

-----BEGIN RSA PRIVATE KEY-----
BASE64 ENCODED DATA
-----END RSA PRIVATE KEY-----

Within the base64 encoded data the following DER structure is present:

RSAPrivateKey ::= SEQUENCE {
  version           Version,
  modulus           INTEGER,  -- n
  publicExponent    INTEGER,  -- e
  privateExponent   INTEGER,  -- d
  prime1            INTEGER,  -- p
  prime2            INTEGER,  -- q
  exponent1         INTEGER,  -- d mod (p-1)
  exponent2         INTEGER,  -- d mod (q-1)
  coefficient       INTEGER,  -- (inverse of q) mod p
  otherPrimeInfos   OtherPrimeInfos OPTIONAL
}

View markdown files offline

You may use Firefox Markdown Viewer plugin that is so easy to install and use.

How does Java deal with multiple conditions inside a single IF statement

Yes, Java (similar to other mainstream languages) uses lazy evaluation short-circuiting which means it evaluates as little as possible.

This means that the following code is completely safe:

if(p != null && p.getAge() > 10)

Also, a || b never evaluates b if a evaluates to true.

Add a summary row with totals

If you want to display more column values without an aggregation function use GROUPING SETS instead of ROLLUP:

SELECT
  Type = ISNULL(Type, 'Total'),
  SomeIntColumn = ISNULL(SomeIntColumn, 0),
  TotalSales = SUM(TotalSales)
FROM atable
GROUP BY GROUPING SETS ((Type, SomeIntColumn ), ())
ORDER BY SomeIntColumn --Displays summary row as the first row in query result

How to prevent robots from automatically filling up a form?

What I did is to use a hidden field and put the timestamp on it and then compared it to the timestamp on the Server using PHP.

If it was faster than 15 seconds (depends on how big or small is your forms) that was a bot.

Hope this help

Example JavaScript code to parse CSV data

csvToArray v1.3

A compact (645 bytes), but compliant function to convert a CSV string into a 2D array, conforming to the RFC4180 standard.

https://code.google.com/archive/p/csv-to-array/downloads

Common Usage: jQuery

 $.ajax({
        url: "test.csv",
        dataType: 'text',
        cache: false
 }).done(function(csvAsString){
        csvAsArray=csvAsString.csvToArray();
 });

Common usage: JavaScript

csvAsArray = csvAsString.csvToArray();

Override field separator

csvAsArray = csvAsString.csvToArray("|");

Override record separator

csvAsArray = csvAsString.csvToArray("", "#");

Override Skip Header

csvAsArray = csvAsString.csvToArray("", "", 1);

Override all

csvAsArray = csvAsString.csvToArray("|", "#", 1);

Show pop-ups the most elegant way

  • Create a 'popup' directive and apply it to the container of the popup content
  • In the directive, wrap the content in a absolute position div along with the mask div below it.
  • It is OK to move the 2 divs in the DOM tree as needed from within the directive. Any UI code is OK in the directives, including the code to position the popup in center of screen.
  • Create and bind a boolean flag to controller. This flag will control visibility.
  • Create scope variables that bond to OK / Cancel functions etc.

Editing to add a high level example (non functional)

<div id='popup1-content' popup='showPopup1'>
  ....
  ....
</div>


<div id='popup2-content' popup='showPopup2'>
  ....
  ....
</div>



.directive('popup', function() {
  var p = {
      link : function(scope, iElement, iAttrs){
           //code to wrap the div (iElement) with a abs pos div (parentDiv)
          // code to add a mask layer div behind 
          // if the parent is already there, then skip adding it again.
         //use jquery ui to make it dragable etc.
          scope.watch(showPopup, function(newVal, oldVal){
               if(newVal === true){
                   $(parentDiv).show();
                 } 
              else{
                 $(parentDiv).hide();
                }
          });
      }


   }
  return p;
});

Programmatically navigate using react router V4

Use useHistory hook if you're using function components

You can use useHistory hook to get history instance.

import { useHistory } from "react-router-dom";

const MyComponent = () => {
  const history = useHistory();
  
  return (
    <button onClick={() => history.push("/about")}>
      Click me
    </button>
  );
}

The useHistory hook gives you access to the history instance that you may use to navigate.

Use history property inside page components

React Router injects some properties including history to page components.

class HomePage extends React.Component {
  render() {
    const { history } = this.props;

    return (
      <div>
        <button onClick={() => history.push("/projects")}>
          Projects
        </button>
      </div>
    );
  }
}

Wrap child components withRouter to inject router properties

withRouter wrapper injects router properties to components. For example you can use this wrapper to inject router to logout button component placed inside user menu.

import { withRouter } from "react-router";

const LogoutButton = withRouter(({ history }) => {
  return (
    <button onClick={() => history.push("/login")}>
      Logout
    </button>
  );
});

export default LogoutButton;

Why is HttpClient BaseAddress not working?

Ran into a issue with the HTTPClient, even with the suggestions still could not get it to authenticate. Turns out I needed a trailing '/' in my relative path.

i.e.

var result = await _client.GetStringAsync(_awxUrl + "api/v2/inventories/?name=" + inventoryName);
var result = await _client.PostAsJsonAsync(_awxUrl + "api/v2/job_templates/" + templateId+"/launch/" , new {
                inventory = inventoryId
            });

To check if string contains particular word

.contains() is perfectly valid and a good way to check.

(http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#contains(java.lang.CharSequence))

Since you didn't post the error, I guess d is either null or you are getting the "Cannot refer to a non-final variable inside an inner class defined in a different method" error.

To make sure it's not null, first check for null in the if statement. If it's the other error, make sure d is declared as final or is a member variable of your class. Ditto for c.

EC2 Instance Cloning

The easier way is through the web management console:

  1. go to the instance
  2. select the instance and click on instance action
  3. create image

Once you have an image you can launch another cloned instance, data and all. :)

Request header field Access-Control-Allow-Headers is not allowed by itself in preflight response

const express = require('express')
const cors = require('cors')
const app = express()

app.get('/with-cors', cors(), (req, res, next) => {
  res.json({ msg: 'WHOAH with CORS it works!  ' })
})

Adding cors in get function Is what worked for me

PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client

In my.cnf file check below 2 steps.

  • check this value -

    old_passwords=0;

    it should be 0.

  • check this also-

    [mysqld] default_authentication_plugin= mysql_native_password Another value to check is to make sure

    [mysqld] section should be like this.

How do I rename a file using VBScript?

From what I understand, your context is to download from ALM. In this case, ALM saves the files under: C:/Users/user/AppData/Local/Temp/TD_80/ALM_VERSION/random_string/Attach/artefact_type/ID

where :

ALM_VERSION is the version of your alm installation, e.g 12.53.2.0_952

artefact_type is the type of the artefact, e.g : REQ

ID is the ID of the artefact

Herebelow a code sample which connects to an instance of ALM, domain 'DEFAUT', project 'MY_PROJECT', gets all the attachments from a REQ with id 6 and saves them in c:/tmp. It's ruby code, but it's easy to transcribe to VBSctript

require 'win32ole'
require 'fileutils'

# login to ALM and domain/project 
alm_server = ENV['CURRRENT_ALM_SERVER']
tdc = WIN32OLE.new('TDApiOle80.TDConnection')
tdc.InitConnectionEx(alm_server)
username, password = ENV['ALM_CREDENTIALS'].split(':')
tdc.Login(username, password)
tdc.Connect('DEFAULT', 'MY_PROJECT')

# get a handle for the Requirements 
reqFact = tdc.ReqFactory

# get Requirement with ID=6
req = reqFact.item(6)

# get a handle for the attachment of REQ 
att = req.Attachments

# get a handle for the list of attachements
attList = att.NewList("")

thePath= 'c:/tmp'

# for each attachment:
attList.each do |el|
  clientPath = nil

  # download the attachment to its default location
  el.Load true, clientPath

  baseName = File.basename(el.FileName)
  dirName = File.dirname(el.FileName)
  puts "file downloaded as : #{baseName}\n in Folder #{dirName}"  
  FileUtils.mkdir_p thePath
  puts "now moving #{baseName} to #{thePath}"  
  FileUtils.mv el.FileName, thePath
end

The output:

=> file downloaded as : REQ_6_20191112_143346.png

=> in Folder C:\Users\user\AppData\Local\Temp\TD_80\12.53.2.0_952\e68ab622\Attach\REQ\6

=> now moving REQ_6_20191112_143346.png to c:/tmp

ZIP file content type for HTTP request

.zip    application/zip, application/octet-stream

Download a div in a HTML page as pdf using javascript

Your solution requires some ajax method to pass the html to a back-end server that has a html to pdf facility and then returning the pdf output generated back to the browser.

First setting up the client side code, we will setup the jquery code as

   var options = {
            "url": "/pdf/generate/convert_to_pdf.php",
            "data": "data=" + $("#content").html(),
            "type": "post",
        }
   $.ajax(options)

Then intercept the data from the html2pdf generation script (somewhere from the internet).
convert_to_pdf.php (given as url in JQUERY code) looks like this -

<?php
    $html = $_POST['data'];
    $pdf = html2pdf($html);
    
    header("Content-Type: application/pdf"); //check this is the proper header for pdf
    header("Content-Disposition: attachment; filename='some.pdf';");
    echo $pdf;
?>

How to trigger click event on href element

Triggering a click via JavaScript will not open a hyperlink. This is a security measure built into the browser.

See this question for some workarounds, though.

Input Type image submit form value?

To submit a form you could use:

<input type="submit">

or

<input type="button"> + Javascript 

I never heard of such a crazy guy to try to send a form using a image or a checkbox as you want :))

Export DataTable to Excel File

Try this to export the data to Excel file same as in DataTable and could customize also.

dtDataTable1 = ds.Tables[0];
    try
    {
        Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
        Workbook xlWorkBook = ExcelApp.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);

        for (int i = 1; i > 0; i--)
        {
            Sheets xlSheets = null;
            Worksheet xlWorksheet = null;
            //Create Excel sheet
            xlSheets = ExcelApp.Sheets;
            xlWorksheet = (Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
            xlWorksheet.Name = "MY FIRST EXCEL FILE";
            for (int j = 1; j < dtDataTable1.Columns.Count + 1; j++)
            {
                ExcelApp.Cells[i, j] = dtDataTable1.Columns[j - 1].ColumnName;
                ExcelApp.Cells[1, j].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);
                ExcelApp.Cells[i, j].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.WhiteSmoke);
            }
            // for the data of the excel
            for (int k = 0; k < dtDataTable1.Rows.Count; k++)
            {
                for (int l = 0; l < dtDataTable1.Columns.Count; l++)
                {
                    ExcelApp.Cells[k + 2, l + 1] = dtDataTable1.Rows[k].ItemArray[l].ToString();
                }
            }
            ExcelApp.Columns.AutoFit();
        }
        ((Worksheet)ExcelApp.ActiveWorkbook.Sheets[ExcelApp.ActiveWorkbook.Sheets.Count]).Delete();
        ExcelApp.Visible = true;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

How to do left join in Doctrine?

If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user, picked from your example), then the syntax is quite simple:

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin('a.user', 'u')
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

Since you are applying a condition on the joined result here, using a LEFT JOIN or simply JOIN is the same.

If no association is available, then the query looks like following

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin(
            'User\Entity\User',
            'u',
            \Doctrine\ORM\Query\Expr\Join::WITH,
            'a.user = u.id'
        )
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

This will produce a resultset that looks like following:

array(
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    // ...
)

Unexpected token }

You have endless loop in place:

function save() {
    var filename = id('filename').value;
    var name = id('name').value;
    var text = id('text').value;
    save(filename, name, text);
}

No idea what you're trying to accomplish with that endless loop but first of all get rid of it and see if things are working.

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

UPDATE: this is not the solution but it's a workaround for a problem that can cause the exception presented in the question.

I've solved changing from Release Configuration to Debug Configuration.

MVC 4 client side validation not working

Use:

@Html.EditorFor

Instead of:

@Html.TextBoxFor

How to add two edit text fields in an alert dialog

The API Demos in the Android SDK have an example that does just that.

It's under DIALOG_TEXT_ENTRY. They have a layout, inflate it with a LayoutInflater, and use that as the View.

EDIT: What I had linked to in my original answer is stale. Here is a mirror.

append new row to old csv file python

If you use pandas, you can append your dataframes to an existing CSV file this way:

df.to_csv('log.csv', mode='a', index=False, header=False)

With mode='a' we ensure that we append, rather than overwrite, and with header=False we ensure that we append only the values of df rows, rather than header + values.

How can I display a tooltip message on hover using jQuery?

You can use bootstrap tooltip. Do not forget to initialize it.

<span class="tooltip-r" data-toggle="tooltip" data-placement="left" title="Explanation">
inside span
</span>

Will be shown text Explanation on the left side.

and run it with js:

$('.tooltip-r').tooltip();

Quotation marks inside a string

You can do this using Escape Sequence.

\"

So you will have to write something like this :

String name = "\"john\"";

You can learn about Escape Sequences from here.

Combining a class selector and an attribute selector with jQuery

I think you just need to remove the space. i.e.

$(".myclass[reference=12345]").css('border', '#000 solid 1px');

There is a fiddle here http://jsfiddle.net/xXEHY/

How do I set the focus to the first input element in an HTML form independent from the id?

Putting this code at the end of your body tag will focus the first visible, non-hidden enabled element on the screen automatically. It will handle most cases I can come up with on short notice.

<script>
    (function(){
        var forms = document.forms || [];
        for(var i = 0; i < forms.length; i++){
            for(var j = 0; j < forms[i].length; j++){
                if(!forms[i][j].readonly != undefined && forms[i][j].type != "hidden" && forms[i][j].disabled != true && forms[i][j].style.display != 'none'){
                    forms[i][j].focus();
                    return;
                }
            }
        }
    })();
</script>

Use a normal link to submit a form

you can use OnClick="document.getElementById('formID_NOT_NAME').SUBMIT()"

Delete files older than 3 months old in a directory using .NET

Here's a 1-liner lambda:

Directory.GetFiles(dirName)
         .Select(f => new FileInfo(f))
         .Where(f => f.LastAccessTime < DateTime.Now.AddMonths(-3))
         .ToList()
         .ForEach(f => f.Delete());

Is it possible to have SSL certificate for IP address, not domain name?

It entirely depends upon the Certificate Authority who issuing a certificate.

As far as Let's Encrypt CA, they wont issue TLS certificate on public IP address. https://community.letsencrypt.org/t/certificate-for-public-ip-without-domain-name/6082

To know your Certificate authority , you can execute following command and look for an entry marked below.

curl -v -u <username>:<password> "https://IPaddress/.."

enter image description here

Count character occurrences in a string in C++

#include <boost/range/algorithm/count.hpp>

std::string str = "a_b_c";
int cnt = boost::count(str, '_');

How to Store Historical Data

Another option is to archive the operational data on a [daily|hourly|whatever] basis. Most database engines support the extraction of the data into an archive.

Basically, the idea is to create a scheduled Windows or CRON job that

  1. determines the current tables in the operational database
  2. selects all data from every table into a CSV or XML file
  3. compresses the exported data to a ZIP file, preferably with the timestamp of the generation in the file name for easier archiving.

Many SQL database engines come with a tool that can be used for this purpose. For example, when using MySQL on Linux, the following command can be used in a CRON job to schedule the extraction:

mysqldump --all-databases --xml --lock-tables=false -ppassword | gzip -c | cat > /media/bak/servername-$(date +%Y-%m-%d)-mysql.xml.gz

What is difference between sjlj vs dwarf vs seh?

There's a short overview at MinGW-w64 Wiki:

Why doesn't mingw-w64 gcc support Dwarf-2 Exception Handling?

The Dwarf-2 EH implementation for Windows is not designed at all to work under 64-bit Windows applications. In win32 mode, the exception unwind handler cannot propagate through non-dw2 aware code, this means that any exception going through any non-dw2 aware "foreign frames" code will fail, including Windows system DLLs and DLLs built with Visual Studio. Dwarf-2 unwinding code in gcc inspects the x86 unwinding assembly and is unable to proceed without other dwarf-2 unwind information.

The SetJump LongJump method of exception handling works for most cases on both win32 and win64, except for general protection faults. Structured exception handling support in gcc is being developed to overcome the weaknesses of dw2 and sjlj. On win64, the unwind-information are placed in xdata-section and there is the .pdata (function descriptor table) instead of the stack. For win32, the chain of handlers are on stack and need to be saved/restored by real executed code.

GCC GNU about Exception Handling:

GCC supports two methods for exception handling (EH):

  • DWARF-2 (DW2) EH, which requires the use of DWARF-2 (or DWARF-3) debugging information. DW-2 EH can cause executables to be slightly bloated because large call stack unwinding tables have to be included in th executables.
  • A method based on setjmp/longjmp (SJLJ). SJLJ-based EH is much slower than DW2 EH (penalising even normal execution when no exceptions are thrown), but can work across code that has not been compiled with GCC or that does not have call-stack unwinding information.

[...]

Structured Exception Handling (SEH)

Windows uses its own exception handling mechanism known as Structured Exception Handling (SEH). [...] Unfortunately, GCC does not support SEH yet. [...]

See also:

String was not recognized as a valid DateTime " format dd/MM/yyyy"

private DateTime ConvertToDateTime(string strDateTime)
{
DateTime dtFinaldate; string sDateTime;
try { dtFinaldate = Convert.ToDateTime(strDateTime); }
catch (Exception e)
{
string[] sDate = strDateTime.Split('/');
sDateTime = sDate[1] + '/' + sDate[0] + '/' + sDate[2];
dtFinaldate = Convert.ToDateTime(sDateTime);
}
return dtFinaldate;
}

What's "P=NP?", and why is it such a famous question?

There is not much I can add to the what and why of the P=?NP part of the question, but in regards to the proof. Not only would a proof be worth some extra credit, but it would solve one of the Millennium Problems. An interesting poll was recently conducted and the published results (PDF) are definitely worth reading in regards to the subject of a proof.

Is it possible to send a variable number of arguments to a JavaScript function?

Yes you can pass variable no. of arguments to a function. You can use apply to achieve this.

E.g.:

var arr = ["Hi","How","are","you"];

function applyTest(){
    var arg = arguments.length;
    console.log(arg);
}

applyTest.apply(null,arr);

Ajax - 500 Internal Server Error

I think your return string data is very long. so the JSON format has been corrupted. You should change the max size for JSON data in this way :

Open the Web.Config file and paste these lines into the configuration section

<system.web.extensions>
  <scripting>
    <webServices>
      <jsonSerialization maxJsonLength="50000000"/>
    </webServices>
  </scripting>
</system.web.extensions>

Check if string is in a pandas dataframe

If there is any chance that you will need to search for empty strings,

    a['Names'].str.contains('') 

will NOT work, as it will always return True.

Instead, use

    if '' in a["Names"].values

to accurately reflect whether or not a string is in a Series, including the edge case of searching for an empty string.

HSL to RGB color conversion

Here's a fast, super-simple, branchless version in GLSL:

vec3 hsl2rgb( vec3 c ) {
    vec3 rgb = clamp(abs(mod(c.x*6.0 + vec3(0.0, 4.0, 2.0), 6.0)-3.0)-1.0, 0.0, 1.0);
    return c.z + c.y * (rgb-0.5)*(1.0-abs(2.0*c.z-1.0));
}

Doesn't get much shorter than that ~


Link to the original proof-of-concept: https://www.shadertoy.com/view/XljGzV

(Disclaimer: not my code!)

UICollectionView current visible cell index

In this thread, There are so many solutions that work fine if cell takes full screen but they use collection view bounds and midpoints of Visible rect However there is a simple solution to this problem

    DispatchQueue.main.async {
        let visibleCell = self.collImages.visibleCells.first
        print(self.collImages.indexPath(for: visibleCell))
    }

by this, you can get indexPath of the visible cell. I have added DispatchQueue because when you swipe faster and if for a brief moment the next cell is shown then without dispactchQueue you'll get indexPath of briefly shown cell not the cell that is being displayed on the screen.

Java, How to get number of messages in a topic in apache kafka

Since ConsumerOffsetChecker is no longer supported, you can use this command to check all messages in topic:

bin/kafka-run-class.sh kafka.admin.ConsumerGroupCommand \
    --group my-group \
    --bootstrap-server localhost:9092 \
    --describe

Where LAG is the count of messages in topic partition:

enter image description here

Also you can try to use kafkacat. This is an open source project that may help you to read messages from a topic and partition and prints them to stdout. Here is a sample that reads the last 10 messages from sample-kafka-topic topic, then exit:

kafkacat -b localhost:9092 -t sample-kafka-topic -p 0 -o -10 -e

Python mysqldb: Library not loaded: libmysqlclient.18.dylib

I found there was another solution for this problem rather than creating a symbolic link.

You set the path to your directory, where libmysqlclient.18.dylib resides, to DYLD_LIBRARY_PATH environment variable. What I did is to put following line in my .bash_profile:

export DYLD_LIBRARY_PATH=/usr/local/mysql-5.5.15-osx10.6-x86/lib/:$DYLD_LIBRARY_PATH

That's it.

Ionic android build Error - Failed to find 'ANDROID_HOME' environment variable

Setup for Linux/Ubuntu/Mint

  1. download Android Studio or SDK only
  2. install
  3. set PATH

3.1) Open terminal and edit ~/.bashrc

sudo su
vim ~/.bashrc

3.2) Export ANDROID_HOME and add folders with binaries to your PATH

Common default install folders:

  • /root/Android/Sdk
  • ~/Android/Sdk

Example .bashrc

export ANDROID_HOME=/root/Android/Sdk
PATH=$PATH:$ANDROID_HOME/tools
PATH=$PATH:$ANDROID_HOME/platform-tools

3.3) Refresh your PATH

source ~/.bashrc

4) Install correct SDK

When ionic build android still fails it could be because of wrong sdk version. To install correct versions and images run android from command line. Since it is now in your PATH you should be able to run it from anywhere.

Array of an unknown length in C#

In a nutshell, please use Collections and Generics.

It's a must for any C# developer, it's worth spending time to learn :)

How do I print out the contents of an object in Rails for easy debugging?

inspect is great but sometimes not good enough. E.g. BigDecimal prints like this: #<BigDecimal:7ff49f5478b0,'0.1E2',9(18)>.

To have full control over what's printed you could redefine to_s or inspect methods. Or create your own one to not confuse future devs too much.

  class Something < ApplicationRecord

    def to_s
      attributes.map{ |k, v| { k => v.to_s } }.inject(:merge)
    end

  end

This will apply a method (i.e. to_s) to all attributes. This example will get rid of the ugly BigDecimals.

You can also redefine a handful of attributes only:

  def to_s
    attributes.merge({ my_attribute: my_attribute.to_s })
  end

You can also create a mix of the two or somehow add associations.

Eclipse: Error ".. overlaps the location of another project.." when trying to create new project

Eclipse is erroring because if you try and create a project on a directory that exists, Eclipse doesn't know if it's an actual project or not - so it errors, saving you from losing work!

So you have two solutions:

  1. Move the folder counter_src somewhere else, then create the project (which will create the directory), then import the source files back into the newly created counter_src.

  2. Right-click on the project explorer and import an existing project, select C:\Users\Martin\Java\Counter\ as your root directory. If Eclipse sees a project, you will be able to import it.

How to decrypt the password generated by wordpress

You will not be able to retrieve a plain text password from wordpress.

Wordpress use a 1 way encryption to store the passwords using a variation of md5. There is no way to reverse this.

See this article for more info http://wordpress.org/support/topic/how-is-the-user-password-encrypted-wp_hash_password

How to create empty data frame with column names specified in R?

Perhaps:

> data.frame(aname=NA, bname=NA)[numeric(0), ]
[1] aname bname
<0 rows> (or 0-length row.names)

Remove element by id

This one actually comes from Firefox... for once, IE was ahead of the pack and allowed the removal of an element directly.

This is just my assumption, but I believe the reason that you must remove a child through the parent is due to an issue with the way Firefox handled the reference.

If you call an object to commit hari-kari directly, then immediately after it dies, you are still holding that reference to it. This has the potential to create several nasty bugs... such as failing to remove it, removing it but keeping references to it that appear valid, or simply a memory leak.

I believe that when they realized the issue, the workaround was to remove an element through its parent because when the element is gone, you are now simply holding a reference to the parent. This would stop all that unpleasantness, and (if closing down a tree node by node, for example) would 'zip-up' rather nicely.

It should be an easily fixable bug, but as with many other things in web programming, the release was probably rushed, leading to this... and by the time the next version came around, enough people were using it that changing this would lead to breaking a bunch of code.

Again, all of this is simply my guesswork.

I do, however, look forward to the day when web programming finally gets a full spring cleaning, all these strange little idiosyncracies get cleaned up, and everyone starts playing by the same rules.

Probably the day after my robot servant sues me for back wages.