Programs & Examples On #Palm os

Questions about Palm OS (now also known as Garnet OS) from PalmSource/ACCESS. Note that this is distinct from HP/Palm webOS.

What is the difference between public, protected, package-private and private in Java?

My two cents :)

private:

class -> a top level class cannot be private. inner classes can be private which are accessible from same class.

instance variable -> accessible only in the class. Cannot access outside the class.

package-private:

class -> a top level class can be package-private. It can only be accessible from same package. Not from sub package, not from outside package.

instance variable -> accessible from same package. Not from sub package, not from outside package.

protected:

class -> a top level class cannot be protected.

instance variable -> Only accessible in same package or subpackage. Can only be access outside the package while extending class.

public:

class -> accessible from package/subpackage/another package

instance variable -> accessible from package/subpackage/another package

Here is detailed answer

https://github.com/junto06/java-4-beginners/blob/master/basics/access-modifier.md

Android Image View Pinch Zooming

I made my own custom imageview with pinch to zoom. There is no limits/borders on Chirag Ravals code, so user can drag the image off the screen. This will fix it.

Here is the CustomImageView class:

    public class CustomImageVIew extends ImageView implements OnTouchListener {


    private Matrix matrix = new Matrix();
    private Matrix savedMatrix = new Matrix();

    static final int NONE = 0;
    static final int DRAG = 1;
    static final int ZOOM = 2;

    private int mode = NONE;

    private PointF mStartPoint = new PointF();
    private PointF mMiddlePoint = new PointF();
    private Point mBitmapMiddlePoint = new Point();

    private float oldDist = 1f;
    private float matrixValues[] = {0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f};
    private float scale;
    private float oldEventX = 0;
    private float oldEventY = 0;
    private float oldStartPointX = 0;
    private float oldStartPointY = 0;
    private int mViewWidth = -1;
    private int mViewHeight = -1;
    private int mBitmapWidth = -1;
    private int mBitmapHeight = -1;
    private boolean mDraggable = false;


    public CustomImageVIew(Context context) {
        this(context, null, 0);
    }

    public CustomImageVIew(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomImageVIew(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.setOnTouchListener(this);
    }

    @Override
    public void onSizeChanged (int w, int h, int oldw, int oldh){
        super.onSizeChanged(w, h, oldw, oldh);
        mViewWidth = w;
        mViewHeight = h;
    }

    public void setBitmap(Bitmap bitmap){
        if(bitmap != null){
            setImageBitmap(bitmap);

            mBitmapWidth = bitmap.getWidth();
            mBitmapHeight = bitmap.getHeight();
            mBitmapMiddlePoint.x = (mViewWidth / 2) - (mBitmapWidth /  2);
            mBitmapMiddlePoint.y = (mViewHeight / 2) - (mBitmapHeight / 2);

            matrix.postTranslate(mBitmapMiddlePoint.x, mBitmapMiddlePoint.y);
            this.setImageMatrix(matrix);
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event){
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
            savedMatrix.set(matrix);
            mStartPoint.set(event.getX(), event.getY());
            mode = DRAG;
            break;
        case MotionEvent.ACTION_POINTER_DOWN:
            oldDist = spacing(event);
            if(oldDist > 10f){
                savedMatrix.set(matrix);
                midPoint(mMiddlePoint, event);
                mode = ZOOM;
            }
            break;
        case MotionEvent.ACTION_UP:
        case MotionEvent.ACTION_POINTER_UP:
            mode = NONE;
            break;
        case MotionEvent.ACTION_MOVE:
            if(mode == DRAG){
                drag(event);
            } else if(mode == ZOOM){
                zoom(event);
            } 
            break;
        }

        return true;
    }



   public void drag(MotionEvent event){
       matrix.getValues(matrixValues);

       float left = matrixValues[2];
       float top = matrixValues[5];
       float bottom = (top + (matrixValues[0] * mBitmapHeight)) - mViewHeight;
       float right = (left + (matrixValues[0] * mBitmapWidth)) -mViewWidth;

       float eventX = event.getX();
       float eventY = event.getY();
       float spacingX = eventX - mStartPoint.x;
       float spacingY = eventY - mStartPoint.y;
       float newPositionLeft = (left  < 0 ? spacingX : spacingX * -1) + left;
       float newPositionRight = (spacingX) + right;
       float newPositionTop = (top  < 0 ? spacingY : spacingY * -1) + top;
       float newPositionBottom = (spacingY) + bottom;
       boolean x = true;
       boolean y = true;

       if(newPositionRight < 0.0f || newPositionLeft > 0.0f){
           if(newPositionRight < 0.0f && newPositionLeft > 0.0f){
               x = false;
           } else{
               eventX = oldEventX;
               mStartPoint.x = oldStartPointX;
           }
       }
       if(newPositionBottom < 0.0f || newPositionTop > 0.0f){
           if(newPositionBottom < 0.0f && newPositionTop > 0.0f){
               y = false;
           } else{
               eventY = oldEventY;
               mStartPoint.y = oldStartPointY;
           }
       }

       if(mDraggable){
           matrix.set(savedMatrix);
           matrix.postTranslate(x? eventX - mStartPoint.x : 0, y? eventY - mStartPoint.y : 0);
           this.setImageMatrix(matrix);
           if(x)oldEventX = eventX;
           if(y)oldEventY = eventY;
           if(x)oldStartPointX = mStartPoint.x;
           if(y)oldStartPointY = mStartPoint.y;
       }

   }

   public void zoom(MotionEvent event){
       matrix.getValues(matrixValues);

       float newDist = spacing(event);
       float bitmapWidth = matrixValues[0] * mBitmapWidth;
       float bimtapHeight = matrixValues[0] * mBitmapHeight;
       boolean in = newDist > oldDist;

       if(!in && matrixValues[0] < 1){
           return;
       }
       if(bitmapWidth > mViewWidth || bimtapHeight > mViewHeight){
           mDraggable = true;
       } else{
           mDraggable = false;
       }

       float midX = (mViewWidth / 2);
       float midY = (mViewHeight / 2);

       matrix.set(savedMatrix);
       scale = newDist / oldDist;
       matrix.postScale(scale, scale, bitmapWidth > mViewWidth ? mMiddlePoint.x : midX, bimtapHeight > mViewHeight ? mMiddlePoint.y : midY); 

       this.setImageMatrix(matrix);


   }





    /** Determine the space between the first two fingers */
    private float spacing(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);

        return (float)Math.sqrt(x * x + y * y);
    }

    /** Calculate the mid point of the first two fingers */
    private void midPoint(PointF point, MotionEvent event) {
        float x = event.getX(0) + event.getX(1);
        float y = event.getY(0) + event.getY(1);
        point.set(x / 2, y / 2);
    }


}

This is how you can use it in your activity:

CustomImageVIew mImageView = (CustomImageVIew)findViewById(R.id.customImageVIew1);
mImage.setBitmap(your bitmap);

And layout:

<your.package.name.CustomImageVIew
        android:id="@+id/customImageVIew1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginBottom="15dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_marginTop="15dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" 
        android:scaleType="matrix"/> // important

Fetching distinct values on a column using Spark DataFrame

Well to obtain all different values in a Dataframe you can use distinct. As you can see in the documentation that method returns another DataFrame. After that you can create a UDF in order to transform each record.

For example:

val df = sc.parallelize(Array((1, 2), (3, 4), (1, 6))).toDF("age", "salary")

// I obtain all different values. If you show you must see only {1, 3}
val distinctValuesDF = df.select(df("age")).distinct

// Define your udf. In this case I defined a simple function, but they can get complicated.
val myTransformationUDF = udf(value => value / 10)

// Run that transformation "over" your DataFrame
val afterTransformationDF = distinctValuesDF.select(myTransformationUDF(col("age")))

How to select last one week data from today's date

Yes, the syntax is accurate and it should be fine.

Here is the SQL Fiddle Demo I created for your particular case

create table sample2
(
    id int primary key,
    created_date date,
    data varchar(10)
  )

insert into sample2 values (1,'2012-01-01','testing');

And here is how to select the data

SELECT Created_Date
FROM sample2
WHERE Created_Date >= DATEADD(day,-11117, GETDATE())

Force uninstall of Visual Studio

Microsoft now has this:

https://github.com/Microsoft/VisualStudioUninstaller/releases

I allowed a windows 10 update to go through that completely f****d VS2015 so I am trying this before having to resort to a rebuild. WT*. :-(

https://visualstudio.uservoice.com/forums/121579-visual-studio-ide/suggestions/3487794-create-a-remove-all-remnants-of-visual-studio-fro

Linking to a specific part of a web page

Create a "jump link" using the following format:

http://www.somesite.com/somepage#anchor

Where anchor is the id of the element you wish to link to on that page. Use browser development tools / view source to find the id of the element you wish to link to.

If the element doesnt have an id and you dont control that site then you cant do it.

Group array items using object

Use lodash's groupby method

Creates an object composed of keys generated from the results of running each element of collection thru iteratee. The order of grouped values is determined by the order they occur in collection. The corresponding value of each key is an array of elements responsible for generating the key. The iteratee is invoked with one argument: (value).

So with lodash you can get what you want in a single line. See below

_x000D_
_x000D_
let myArray = [_x000D_
  {group: "one", color: "red"},_x000D_
  {group: "two", color: "blue"},_x000D_
  {group: "one", color: "green"},_x000D_
  {group: "one", color: "black"},_x000D_
]_x000D_
let grouppedArray=_.groupBy(myArray,'group')_x000D_
console.log(grouppedArray)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

How to enable loglevel debug on Apache2 server

Do note that on newer Apache versions the RewriteLog and RewriteLogLevel have been removed, and in fact will now trigger an error when trying to start Apache (at least on my XAMPP installation with Apache 2.4.2):

AH00526: Syntax error on line xx of path/to/config/file.conf: Invalid command 'RewriteLog', perhaps misspelled or defined by a module not included in the server configuration`

Instead, you're now supposed to use the general LogLevel directive, with a level of trace1 up to trace8. 'debug' didn't display any rewrite messages in the log for me.

Example: LogLevel warn rewrite:trace3

For the official documentation, see here.

Of course this also means that now your rewrite logs will be written in the general error log file and you'll have to sort them out yourself.

sqldeveloper error message: Network adapter could not establish the connection error

In the connection properties window I changed my selection from "SID" to "Service Name", and copied my SID into the Service Name field. No idea why this change happened or why it worked, but it got me back on Oracle.

Which is preferred: Nullable<T>.HasValue or Nullable<T> != null?

If you use linq and want to keep your code short, I recommand to always use !=null

And this is why:

Let imagine we have some class Foo with a nullable double variable SomeDouble

public class Foo
{
    public double? SomeDouble;
    //some other properties
}   

If somewhere in our code we want to get all Foo with a non null SomeDouble values from a collection of Foo (assuming some foos in the collection can be null too), we end up with at least three way to write our function (if we use C# 6) :

public IEnumerable<Foo> GetNonNullFoosWithSomeDoubleValues(IEnumerable<Foo> foos)
{
     return foos.Where(foo => foo?.SomeDouble != null);
     return foos.Where(foo=>foo?.SomeDouble.HasValue); // compile time error
     return foos.Where(foo=>foo?.SomeDouble.HasValue == true); 
     return foos.Where(foo=>foo != null && foo.SomeDouble.HasValue); //if we don't use C#6
}

And in this kind of situation I recommand to always go for the shorter one

Is Android using NTP to sync time?

I have a Samsung Galaxy Tab 2 7.0 with Android 4.1.1. Apparently it does NOT sync to ntp. I loaded an app that says my tablet is 20 seconds off of ntp, but it can't set it unless I root the device.

OpenCV - Saving images to a particular folder of choice

FOR MAC USERS if you are working with open cv

import cv2

cv2.imwrite('path_to_folder/image.jpg',image)

C++ cout hex values?

There are different kinds of flags & masks you can use as well. Please refer http://www.cplusplus.com/reference/iostream/ios_base/setf/ for more information.

#include <iostream>
using namespace std;

int main()
{
    int num = 255;
    cout.setf(ios::hex, ios::basefield);
    cout << "Hex: " << num << endl;

    cout.unsetf(ios::hex);
    cout << "Original format: " << num << endl;

    return 0;
}

How to increase buffer size in Oracle SQL Developer to view all records?

https://forums.oracle.com/forums/thread.jspa?threadID=447344

The pertinent section reads:

There's no setting to fetch all records. You wouldn't like SQL Developer to fetch for minutes on big tables anyway. If, for 1 specific table, you want to fetch all records, you can do Control-End in the results pane to go to the last record. You could time the fetching time yourself, but that will vary on the network speed and congestion, the program (SQL*Plus will be quicker than SQL Dev because it's more simple), etc.

There is also a button on the toolbar which is a "Fetch All" button.

FWIW Be careful retrieving all records, for a very large recordset it could cause you to have all sorts of memory issues etc.

As far as I know, SQL Developer uses JDBC behind the scenes to fetch the records and the limit is set by the JDBC setMaxRows() procedure, if you could alter this (it would prob be unsupported) then you might be able to change the SQL Developer behaviour.

How to get value at a specific index of array In JavaScript?

You can just use []:

var valueAtIndex1 = myValues[1];

How do I import .sql files into SQLite 3?

You can also do:

sqlite3 database.db -init dump.sql

Getting an "ambiguous redirect" error

One other thing that can cause "ambiguous redirect" is \t \n \r in the variable name you are writing too

Maybe not \n\r? But err on the side of caution

Try this

echo "a" > ${output_name//[$'\t\n\r']}

I got hit with this one while parsing HTML, Tabs \t at the beginning of the line.

Ruby get object keys as array

Use the keys method: {"apple" => "fruit", "carrot" => "vegetable"}.keys == ["apple", "carrot"]

Implementing SearchView in action bar


For Searchview use these code

  1. For XML

    <android.support.v7.widget.SearchView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/searchView">
    
    </android.support.v7.widget.SearchView>
    

  2. In your Fragment or Activity

    package com.example.user.salaryin;
    
    import android.app.ProgressDialog;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v4.view.MenuItemCompat;
    import android.support.v7.widget.GridLayoutManager;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.support.v7.widget.SearchView;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Toast;
    import com.example.user.salaryin.Adapter.BusinessModuleAdapter;
    import com.example.user.salaryin.Network.ApiClient;
    import com.example.user.salaryin.POJO.ProductDetailPojo;
    import com.example.user.salaryin.Service.ServiceAPI;
    import java.util.ArrayList;
    import java.util.List;
    import retrofit2.Call;
    import retrofit2.Callback;
    import retrofit2.Response;
    
    
    public class OneFragment extends Fragment implements SearchView.OnQueryTextListener {
    
    RecyclerView recyclerView;
    RecyclerView.LayoutManager layoutManager;
    ArrayList<ProductDetailPojo> arrayList;
    BusinessModuleAdapter adapter;
    private ProgressDialog pDialog;
    GridLayoutManager gridLayoutManager;
    SearchView searchView;
    
    public OneFragment() {
        // Required empty public constructor
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    
        View rootView = inflater.inflate(R.layout.one_fragment,container,false);
    
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Please wait...");
    
    
        searchView=(SearchView)rootView.findViewById(R.id.searchView);
        searchView.setQueryHint("Search BY Brand");
        searchView.setOnQueryTextListener(this);
    
        recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
        layoutManager = new LinearLayoutManager(this.getActivity());
        recyclerView.setLayoutManager(layoutManager);
        gridLayoutManager = new GridLayoutManager(this.getActivity().getApplicationContext(), 2);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setHasFixedSize(true);
        getImageData();
    
    
        // Inflate the layout for this fragment
        //return inflater.inflate(R.layout.one_fragment, container, false);
        return rootView;
    }
    
    
    private void getImageData() {
        pDialog.show();
        ServiceAPI service = ApiClient.getRetrofit().create(ServiceAPI.class);
        Call<List<ProductDetailPojo>> call = service.getBusinessImage();
    
        call.enqueue(new Callback<List<ProductDetailPojo>>() {
            @Override
            public void onResponse(Call<List<ProductDetailPojo>> call, Response<List<ProductDetailPojo>> response) {
                if (response.isSuccessful()) {
                    arrayList = (ArrayList<ProductDetailPojo>) response.body();
                    adapter = new BusinessModuleAdapter(arrayList, getActivity());
                    recyclerView.setAdapter(adapter);
                    pDialog.dismiss();
                } else if (response.code() == 401) {
                    pDialog.dismiss();
                    Toast.makeText(getActivity(), "Data is not found", Toast.LENGTH_SHORT).show();
                }
    
            }
    
            @Override
            public void onFailure(Call<List<ProductDetailPojo>> call, Throwable t) {
                Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_SHORT).show();
                pDialog.dismiss();
    
            }
        });
    }
    
       /* @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        getActivity().getMenuInflater().inflate(R.menu.menu_search, menu);
        MenuItem menuItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
        searchView.setQueryHint("Search Product");
        searchView.setOnQueryTextListener(this);
    }*/
    
    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }
    
    @Override
    public boolean onQueryTextChange(String newText) {
        newText = newText.toLowerCase();
        ArrayList<ProductDetailPojo> newList = new ArrayList<>();
        for (ProductDetailPojo productDetailPojo : arrayList) {
            String name = productDetailPojo.getDetails().toLowerCase();
    
            if (name.contains(newText) )
                newList.add(productDetailPojo);
            }
        adapter.setFilter(newList);
        return true;
       }
    }
    
  3. In adapter class

     public void setFilter(List<ProductDetailPojo> newList){
        arrayList=new ArrayList<>();
        arrayList.addAll(newList);
        notifyDataSetChanged();
    }
    

Calling another method java GUI

I'm not sure what you're trying to do, but here's something to consider: c(); won't do anything. c is an instance of the class checkbox and not a method to be called. So consider this:

public class FirstWindow extends JFrame {      public FirstWindow() {         checkbox c = new checkbox();         c.yourMethod(yourParameters); // call the method you made in checkbox     } }  public class checkbox extends JFrame {      public checkbox(yourParameters) {          // this is the constructor method used to initialize instance variables     }      public void yourMethod() // doesn't have to be void     {         // put your code here     } } 

Fastest way to count number of occurrences in a Python list

You can convert list in string with elements seperated by space and split it based on number/char to be searched..

Will be clean and fast for large list..

>>>L = [2,1,1,2,1,3]
>>>strL = " ".join(str(x) for x in L)
>>>strL
2 1 1 2 1 3
>>>count=len(strL.split(" 1"))-1
>>>count
3

Static methods - How to call a method from another method?

class.method should work.

class SomeClass:
  @classmethod
  def some_class_method(cls):
    pass

  @staticmethod
  def some_static_method():
    pass

SomeClass.some_class_method()
SomeClass.some_static_method()

Enable CORS in Web API 2

CORS works absolutely fine in Microsoft.AspNet.WebApi.Cors version 5.2.2. The following steps configured CORS like a charm for me:

  1. Install-Package Microsoft.AspNet.WebApi.Cors -Version "5.2.2" // run from Package manager console
  2. In Global.asax, add the following line: BEFORE ANY MVC ROUTE REGISTRATIONS

    GlobalConfiguration.Configure(WebApiConfig.Register);
    
  3. In the WebApiConfig Register method, have the following code:

    public static void Register(HttpConfiguration config)
    {
        config.EnableCors();
        config.MapHttpAttributeRoutes();
    }
    

In the web.config, the following handler must be the first one in the pipeline:

<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

In the controller derived from ApiController, add the EnableCorsAttribute:

[EnableCors(origins: "*", headers: "*", methods: "*")] // tune to your needs
[RoutePrefix("")]
public class MyController : ApiController

That should set you up nicely!

Loop and get key/value pair for JSON array using jQuery

Parse the JSON string and you can loop through the keys.

_x000D_
_x000D_
var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"[email protected]","Phone":"123 dead drive"}';_x000D_
var data = JSON.parse(resultJSON);_x000D_
_x000D_
for (var key in data)_x000D_
{_x000D_
    //console.log(key + ' : ' + data[key]);_x000D_
    alert(key + ' --> ' + data[key]);_x000D_
}
_x000D_
_x000D_
_x000D_

Why do we use __init__ in Python classes?

class Dog(object):

    # Class Object Attribute
    species = 'mammal'

    def __init__(self,breed,name):
        self.breed = breed
        self.name = name

In above example we use species as a global since it will be always same(Kind of constant you can say). when you call __init__ method then all the variable inside __init__ will be initiated(eg:breed,name).

class Dog(object):
    a = '12'

    def __init__(self,breed,name,a):
        self.breed = breed
        self.name = name
        self.a= a

if you print the above example by calling below like this

Dog.a
12

Dog('Lab','Sam','10')
Dog.a
10

That means it will be only initialized during object creation. so anything which you want to declare as constant make it as global and anything which changes use __init__

When to use React setState callback

The 1. usecase which comes into my mind, is an api call, which should't go into the render, because it will run for each state change. And the API call should be only performed on special state change, and not on every render.

changeSearchParams = (params) => {
  this.setState({ params }, this.performSearch)
} 

performSearch = () => {
  API.search(this.state.params, (result) => {
    this.setState({ result })
  });
}

Hence for any state change, an action can be performed in the render methods body.

Very bad practice, because the render-method should be pure, it means no actions, state changes, api calls, should be performed, just composite your view and return it. Actions should be performed on some events only. Render is not an event, but componentDidMount for example.

Getting Index of an item in an arraylist;

To find the item that has a name, should I just use a for loop, and when the item is found, return the element position in the ArrayList?

Yes to the loop (either using indexes or an Iterator). On the return value, either return its index, or the item iteself, depending on your needs. ArrayList doesn't have an indexOf(Object target, Comparator compare)` or similar. Now that Java is getting lambda expressions (in Java 8, ~March 2014), I expect we'll see APIs get methods that accept lambdas for things like this.

Is There a Better Way of Checking Nil or Length == 0 of a String in Ruby?

Have you tried Refinements?

module Nothingness
  refine String do
    alias_method :nothing?, :empty?
  end

  refine NilClass do
    alias_method :nothing?, :nil?
  end
end

using Nothingness

return my_string.nothing?

How can I refresh c# dataGridView after update ?

I know i am late to the party but hope this helps someone who will do the same with Class binding

var newEntry = new MyClassObject();

var bindingSource = dataGridView.DataSource as BindingSource;
var myClassObjects = bindingSource.DataSource as List<MyClassObject>;
myClassObjects.Add(newEntry);
bindingSource.DataSource = myClassObjects;

dataGridView.DataSource = null;
dataGridView.DataSource = bindingSource;
dataGridView.Update();
dataGridView.Refresh();

Difference between private, public, and protected inheritance

Limiting the visibility of inheritance will make code not able to see that some class inherits another class: Implicit conversions from the derived to the base won't work, and static_cast from the base to the derived won't work either.

Only members/friends of a class can see private inheritance, and only members/friends and derived classes can see protected inheritance.

public inheritance

  1. IS-A inheritance. A button is-a window, and anywhere where a window is needed, a button can be passed too.

    class button : public window { };
    

protected inheritance

  1. Protected implemented-in-terms-of. Rarely useful. Used in boost::compressed_pair to derive from empty classes and save memory using empty base class optimization (example below doesn't use template to keep being at the point):

    struct empty_pair_impl : protected empty_class_1 
    { non_empty_class_2 second; };
    
    struct pair : private empty_pair_impl {
      non_empty_class_2 &second() {
        return this->second;
      }
    
      empty_class_1 &first() {
        return *this; // notice we return *this!
      }
    };
    

private inheritance

  1. Implemented-in-terms-of. The usage of the base class is only for implementing the derived class. Useful with traits and if size matters (empty traits that only contain functions will make use of the empty base class optimization). Often containment is the better solution, though. The size for strings is critical, so it's an often seen usage here

    template<typename StorageModel>
    struct string : private StorageModel {
    public:
      void realloc() {
        // uses inherited function
        StorageModel::realloc();
      }
    };
    

public member

  1. Aggregate

    class pair {
    public:
      First first;
      Second second;
    };
    
  2. Accessors

    class window {
    public:
        int getWidth() const;
    };
    

protected member

  1. Providing enhanced access for derived classes

    class stack {
    protected:
      vector<element> c;
    };
    
    class window {
    protected:
      void registerClass(window_descriptor w);
    };
    

private member

  1. Keep implementation details

    class window {
    private:
      int width;
    };
    

Note that C-style casts purposely allows casting a derived class to a protected or private base class in a defined and safe manner and to cast into the other direction too. This should be avoided at all costs, because it can make code dependent on implementation details - but if necessary, you can make use of this technique.

How to sum a variable by group

You can also use the dplyr package for that purpose:

library(dplyr)
x %>% 
  group_by(Category) %>% 
  summarise(Frequency = sum(Frequency))

#Source: local data frame [3 x 2]
#
#  Category Frequency
#1    First        30
#2   Second         5
#3    Third        34

Or, for multiple summary columns (works with one column too):

x %>% 
  group_by(Category) %>% 
  summarise(across(everything(), sum))

Here are some more examples of how to summarise data by group using dplyr functions using the built-in dataset mtcars:

# several summary columns with arbitrary names
mtcars %>% 
  group_by(cyl, gear) %>%                            # multiple group columns
  summarise(max_hp = max(hp), mean_mpg = mean(mpg))  # multiple summary columns

# summarise all columns except grouping columns using "sum" 
mtcars %>% 
  group_by(cyl) %>% 
  summarise(across(everything(), sum))

# summarise all columns except grouping columns using "sum" and "mean"
mtcars %>% 
  group_by(cyl) %>% 
  summarise(across(everything(), list(mean = mean, sum = sum)))

# multiple grouping columns
mtcars %>% 
  group_by(cyl, gear) %>% 
  summarise(across(everything(), list(mean = mean, sum = sum)))

# summarise specific variables, not all
mtcars %>% 
  group_by(cyl, gear) %>% 
  summarise(across(c(qsec, mpg, wt), list(mean = mean, sum = sum)))

# summarise specific variables (numeric columns except grouping columns)
mtcars %>% 
  group_by(gear) %>% 
  summarise(across(where(is.numeric), list(mean = mean, sum = sum)))

For more information, including the %>% operator, see the introduction to dplyr.

How to send a POST request with BODY in swift

func get_Contact_list()
{
    ApiUtillity.sharedInstance.showSVProgressHUD(text: "Loading..")
    let cont_nunber = contact_array as NSArray
    print(cont_nunber)

    let token = UserDefaults.standard.string(forKey: "vAuthToken")!
    let apiToken = "Bearer \(token)"


    let headers = [
        "Vauthtoken": apiToken,
        "content-type": "application/json"
    ]

    let myArray: [Any] = cont_nunber as! [Any]
    let jsonData: Data? = try? JSONSerialization.data(withJSONObject: myArray, options: .prettyPrinted)
    //        var jsonString: String = nil
    var jsonString = String()
    if let aData = jsonData {
        jsonString = String(data: aData, encoding: .utf8)!
    }

    let url1 = "URL"
    var request = URLRequest(url: URL(string: url1)!)
    request.httpMethod = "POST"
    request.allHTTPHeaderFields = headers
    request.httpBody = jsonData as! Data

    //        let session = URLSession.shared

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            print("error=\(String(describing: error))")
            ApiUtillity.sharedInstance.dismissSVProgressHUD()
            return
        }

        print("response = \(String(describing: response))")


        let responseString = String(data: data, encoding: .utf8)
        print("responseString = \(String(describing: responseString))")

        let json =  self.convertStringToDictionary(text: responseString!)! as NSDictionary
        print(json)

        let status = json.value(forKey: "status") as! Int

        if status == 200
        {

            let array = (json.value(forKey: "data") as! NSArray).mutableCopy() as! NSMutableArray


        }
        else if status == 401
        {
            ApiUtillity.sharedInstance.dismissSVProgressHUD()

        }
        else
        {
            ApiUtillity.sharedInstance.dismissSVProgressHUD()
        }


    }
    task.resume()
}

func convertStringToDictionary(text: String) -> [String:AnyObject]? {
    if let data = text.data(using: String.Encoding.utf8) {
        do {
            let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:AnyObject]
            return json
        } catch {
            print("Something went wrong")
        }
    }
    return nil
}

parseInt with jQuery

var test = parseInt($("#testid").val());

Truncate a string straight JavaScript

Thought I would give Sugar.js a mention. It has a truncate method that is pretty smart.

From the documentation:

Truncates a string. Unless split is true, truncate will not split words up, and instead discard the word where the truncation occurred.

Example:

'just sittin on the dock of the bay'.truncate(20)

Output:

just sitting on...

Angular 2 / 4 / 5 - Set base href dynamically

In angular4, you can also configure the baseHref in .angular-cli.json apps.

in .angular-cli.json

{   ....
 "apps": [
        {
            "name": "myapp1"
            "baseHref" : "MY_APP_BASE_HREF_1"
         },
        {
            "name": "myapp2"
            "baseHref" : "MY_APP_BASE_HREF_2"
         },
    ],
}

this will update base href in index.html to MY_APP_BASE_HREF_1

ng build --app myapp1

How to Use Multiple Columns in Partition By And Ensure No Duplicate Row is Returned

I'd create a cte and do an inner join. It's not efficient but it's convenient

with table as (
SELECT DATE, STATUS, TITLE, ROW_NUMBER() 
OVER (PARTITION BY DATE, STATUS,  TITLE ORDER BY QUANTITY ASC) AS Row_Num
 FROM TABLE)

select *

from table t
join select(
max(Row_Num) as Row_Num
,DATE
,STATUS
,TITLE
from table 
group by date, status, title) t2  
on t2.Row_Num = t.Row_Num and t2
and t2.date = t.date
and t2.title = t.title

Convert YYYYMMDD to DATE

In your case it should be:

Select convert(datetime,convert(varchar(10),GRADUATION_DATE,120)) as
'GRADUATION_DATE' from mydb

Datepicker: How to popup datepicker when click on edittext

#1. I want to show a datepicker with current date as preselected (I use butterknife for injection)

  @OnClick(R.id.your_view) public void onClickYourView() {

    final Calendar myCalendar = Calendar.getInstance();
    DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
      @Override
      public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        // TODO Auto-generated method stub
        myCalendar.set(Calendar.YEAR, year);
        myCalendar.set(Calendar.MONTH, monthOfYear);
        myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        String myFormat = "dd MMMM yyyy"; // your format
        SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.getDefault());

        your_view.setText(sdf.format(myCalendar.getTime()));
      }

    };
    new DatePickerDialog(mContext, date, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)).show();

  }

2. If you want to preselect the date replace the last part with

new DatePickerDialog(mContext, date, 1990, 0, 1).show();

then you can get it using myCalendar variable or directly the text on your view.

How to compile and run C/C++ in a Unix console/Mac terminal?

All application execution in a Unix (Linux, Mac OS X, AIX, etc.) environment depends on the executable search path.

You can display this path in the terminal with this command:

echo $PATH

On Mac OS X (by default) this will display the following colon separated search path:

/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin

So any executable in the listed directories can by run just by typing in their name. For example:

cat mytextfile.txt

This runs /bin/cat and displays mytextfile.txt to the terminal.

To run any other command that is not in the executable search path requires that you qualify the path to the executable. So say I had an executable called MyProgram in my home directory on Mac OS X I can fully qualify it like so:

/Users/oliver/MyProgram

If you are in a location that is near the program you wished to execute you can qualify the name with a partial path. For example, if MyProgram was in the directory /Users/oliver/MyProject I and I was in my home directory I can qualify the executable name like this, and have it execute:

MyProject/MyProgram

Or say I was in the directory /Users/oliver/MyProject2 and I wanted to execute /Users/oliver/MyProject/MyProgram I can use a relative path like this, to execute it:

../MyProject/MyProgram

Similarly if I am in the same directory as MyProgram I need to use a "current directory" relative path. The current directory you are in is the period character followed by a slash. For example:

./MyProgram

To determine which directory you are currently in use the pwd command.

If you are commonly putting programs in a place on your hard disk that you wish to run without having to qualify their names. For example, if you have a "bin" directory in your home directory for regularly used shell scripts of other programs it may be wise to alter your executable search path.

This can be does easily by either creating or editing the existing .bash_profile file in your home directory and adding the lines:

#!/bin/sh
export PATH=$PATH:~/bin

Here the tilde (~) character is being used as a shortcut for /Users/oliver. Also note that the hash bang (#!) line needs to be the first line of the file (if it doesn't already exist). Note also that this technique requires that your login shell be bash (the default on Mac OS X and most Linux distributions). Also note that if you want your programs installed in ~/bin to be used in preference to system executables your should reorder the export statement as follows:

export PATH=~/bin:$PATH

How do I print a double value with full precision using cout?

Most portably...

#include <limits>

using std::numeric_limits;

    ...
    cout.precision(numeric_limits<double>::digits10 + 1);
    cout << d;

getting the error: expected identifier or ‘(’ before ‘{’ token

you need to place the opening brace after main , not before it

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{

How to get the mouse position without events (without moving the mouse)?

The most simple solution but not 100% accurate

$(':hover').last().offset()

Result: {top: 148, left: 62.5}
The result depend on the nearest element size and return undefined when user switched the tab

Strip / trim all strings of a dataframe

def trim(x):
    if x.dtype == object:
        x = x.str.split(' ').str[0]
    return(x)

df = df.apply(trim)

Navigation Drawer (Google+ vs. YouTube)

Personally I like the navigationDrawer in Google Drive official app. It just works and works great. I agree that the navigation drawer shouldn't move the action bar because is the key point to open and close the navigation drawer.

If you are still trying to get that behavior I recently create a project Called SherlockNavigationDrawer and as you may expect is the implementation of the Navigation Drawer with ActionBarSherlock and works for pre Honeycomb devices. Check it:

SherlockNavigationDrawer github

Mongoose, update values in array of objects

For each document, the update operator $set can set multiple values, so rather than replacing the entire object in the items array, you can set the name and value fields of the object individually.

{'$set':  {'items.$.name': update.name , 'items.$.value': update.value}}

Calling a java method from c++ in Android

Solution posted by Denys S. in the question post:

I quite messed it up with c to c++ conversion (basically env variable stuff), but I got it working with the following code for C++:

#include <string.h>
#include <stdio.h>
#include <jni.h>

jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj){

    jstring jstr = (*env)->NewStringUTF(env, "This comes from jni.");
    jclass clazz = (*env)->FindClass(env, "com/inceptix/android/t3d/MainActivity");
    jmethodID messageMe = (*env)->GetMethodID(env, clazz, "messageMe", "(Ljava/lang/String;)Ljava/lang/String;");
    jobject result = (*env)->CallObjectMethod(env, obj, messageMe, jstr);

    const char* str = (*env)->GetStringUTFChars(env,(jstring) result, NULL); // should be released but what a heck, it's a tutorial :)
    printf("%s\n", str);

    return (*env)->NewStringUTF(env, str);
}

And next code for java methods:

    public class MainActivity extends Activity {
    private static String LIB_NAME = "thelib";

    static {
        System.loadLibrary(LIB_NAME);
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView tv = (TextView) findViewById(R.id.textview);
        tv.setText(this.getJniString());
    }

    // please, let me live even though I used this dark programming technique
    public String messageMe(String text) {
        System.out.println(text);
        return text;
    }

    public native String getJniString();
}

How to set the size of button in HTML

This cannot be done with pure HTML/JS, you will need CSS

CSS:

button {
     width: 100%;
     height: 100%;
}

Substitute 100% with required size

This can be done in many ways

Catching exceptions from Guzzle

If the Exception is being thrown in that try block then at worst case scenario Exception should be catching anything uncaught.

Consider that the first part of the test is throwing the Exception and wrap that in the try block as well.

Remove innerHTML from div

jQuery Data is a different concept than HTML. removeData is not for removing element content, it's for removing data items you've previously stored.

Just do

divToUpdate.html("");

or

divToUpdate.empty();

'innerText' works in IE, but not in Firefox

Firefox uses the W3C-compliant textContent property.

I'd guess Safari and Opera also support this property.

Npm install cannot find module 'semver'

On Ubuntu, if you would rather manage Node through the default repositories using apt, it's best to install both nodejs and npm this way.

It's very likely that the version of npm you are using is expecting semver in a specific place that is not aligned with the version of Node JS you have installed. If there is only one version of nodejs and only one version of npm, and they are both installed using the default repositories, this should work perfectly.

Here is my best guidance for getting Node and npm working using the main Ubuntu repositories:

  1. sudo apt-get purge nodejs --auto-remove and sudo apt-get purge npm --auto-remove
  2. whereis node: remove all the versions of node, one at a time. Repeat until this command returns a blank after node:.
  3. sudo apt-get install nodejs
  4. node --version: should return ... no such file or directory
  5. nodejs --version: should return v1x.x.x. This is the version installed by apt. It will probably be less recent that the latest version available on the Node JS website.
  6. sudo apt-get install npm
  7. npm --version: it will use the nodejs installed by apt and work correctly.

BigDecimal setScale and round

One important point that is alluded to but not directly addressed is the difference between "precision" and "scale" and how they are used in the two statements. "precision" is the total number of significant digits in a number. "scale" is the number of digits to the right of the decimal point.

The MathContext constructor only accepts precision and RoundingMode as arguments, and therefore scale is never specified in the first statement.

setScale() obviously accepts scale as an argument, as well as RoundingMode, however precision is never specified in the second statement.

If you move the decimal point one place to the right, the difference will become clear:

// 1.
new BigDecimal("35.3456").round(new MathContext(4, RoundingMode.HALF_UP));
//result = 35.35
// 2.
new BigDecimal("35.3456").setScale(4, RoundingMode.HALF_UP);
// result = 35.3456

Login with facebook android sdk app crash API 4

The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):

Mikhail,

The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.

Good luck with your implementation.

Check if DataRow exists by column name in c#?

if (drMyRow.Table.Columns["ColNameToCheck"] != null)
{
   doSomethingUseful;
{
else { return; }

Although the DataRow does not have a Columns property, it does have a Table that the column can be checked for.

Create an array or List of all dates between two dates

Our resident maestro Jon Skeet has a great Range Class that can do this for DateTimes and other types.

PreparedStatement setNull(..)

You could also consider using preparedStatement.setObject(index,value,type);

Python object.__repr__(self) should be an expression?

It should be a Python expression that, when eval'd, creates an object with the exact same properties as this one. For example, if you have a Fraction class that contains two integers, a numerator and denominator, your __repr__() method would look like this:

# in the definition of Fraction class
def __repr__(self):
    return "Fraction(%d, %d)" % (self.numerator, self.denominator)

Assuming that the constructor takes those two values.

Failed to install Python Cryptography package with PIP and setup.py

I am having same problem:

pip install cryptography

.
.
.
Installing collected packages: cffi, cryptography
     Running setup.py install for cffi ... error

Then I install libffi-devel and problem is solved

yum install libffi-devel

How to download the latest artifact from Artifactory repository?

I use Nexus and this code works for me—can retrive both release and last snaphsot, depending on repository type:

server="http://example.com/nexus/content/repositories"
repo="snapshots"
name="com.exmple.server"
artifact="com/example/$name"
path=$server/$repo/$artifact
mvnMetadata=$(curl -s "$path/maven-metadata.xml")
echo "Metadata: $mvnMetadata"
jar=""
version=$( echo "$mvnMetadata" | xpath -e "//versioning/release/text()" 2> /dev/null)
if [[ $version = *[!\ ]* ]]; then
  jar=$name-$version.jar
else
  version=$(echo "$mvnMetadata" | xpath -e "//versioning/versions/version[last()]/text()")
  snapshotMetadata=$(curl -s "$path/$version/maven-metadata.xml")
  timestamp=$(echo "$snapshotMetadata" | xpath -e "//snapshot/timestamp/text()")
  buildNumber=$(echo "$snapshotMetadata" | xpath -e "//snapshot/buildNumber/text()")
  snapshotVersion=$(echo "$version" | sed 's/\(-SNAPSHOT\)*$//g')
  jar=$name-$snapshotVersion-$timestamp-$buildNumber.jar
fi
jarUrl=$path/$version/$jar
echo $jarUrl
mkdir -p /opt/server/
wget -O /opt/server/server.jar -q -N $jarUrl

How to have PHP display errors? (I've added ini_set and error_reporting, but just gives 500 on errors)

To people using Codeigniter (i'm on C3):

The index.php file overwrite php.ini configuration, so on index.php file, line 68:

case 'development':
        error_reporting(-1);
        ini_set('display_errors', 1);
    break;

You can change this option to set what you need. Here's the complete list:

1   E_ERROR
2   E_WARNING
4   E_PARSE
8   E_NOTICE
16  E_CORE_ERROR
32  E_CORE_WARNING
64  E_COMPILE_ERROR
128 E_COMPILE_WARNING
256 E_USER_ERROR
512 E_USER_WARNING
1024    E_USER_NOTICE
6143    E_ALL
2048    E_STRICT
4096    E_RECOVERABLE_ERROR

Hope it helps.

How to get numeric position of alphabets in java?

Another way to do this problem besides using ASCII conversions is the following:

String input = "abc".toLowerCase();
final static String alphabet = "abcdefghijklmnopqrstuvwxyz";
for(int i=0; i < input.length(); i++){
    System.out.print(alphabet.indexOf(input.charAt(i))+1);
}

How can I add 1 day to current date?

int days = 1;
var newDate = new Date(Date.now() + days*24*60*60*1000);

CodePen

_x000D_
_x000D_
var days = 2;_x000D_
var newDate = new Date(Date.now()+days*24*60*60*1000);_x000D_
_x000D_
document.write('Today: <em>');_x000D_
document.write(new Date());_x000D_
document.write('</em><br/> New: <strong>');_x000D_
document.write(newDate);
_x000D_
_x000D_
_x000D_

How to write to error log file in PHP

you can simply use :

error_log("your message");

By default, the message will be send to the php system logger.

typescript: error TS2693: 'Promise' only refers to a type, but is being used as a value here

Here is my tip. Tested with vscode 1.21.1 (on MAC)

Put below config to tsconfig.json

"lib": [
"es2016",
"dom"
]

into compilerOptions

Restart IDE (this action is required :D )

What is the difference between .*? and .* regular expressions?

Let's say you have:

<a></a>

<(.*)> would match a></a where as <(.*?)> would match a. The latter stops after the first match of >. It checks for one or 0 matches of .* followed by the next expression.

The first expression <(.*)> doesn't stop when matching the first >. It will continue until the last match of >.

Changing API level Android Studio

For android studio users:

  1. right click the App directory
  2. choose the "module setting" option
  3. change the ADK Platform as what you need
  4. Click Apply

The gradle will rebuild the project automatically.

how to specify new environment location for conda create

While using the --prefix option works, you have to explicitly use it every time you create an environment. If you just want your environments stored somewhere else by default, you can configure it in your .condarc file.

Please see: https://conda.io/docs/user-guide/configuration/use-condarc.html#specify-environment-directories-envs-dirs

Add space between two particular <td>s

The simplest way:

td:nth-child(2) {
    padding-right: 20px;
}?

But that won't work if you need to work with background color or images in your table. In that case, here is a slightly more advanced solution (CSS3):

td:nth-child(2) {
    border-right: 10px solid transparent;
    -webkit-background-clip: padding;
    -moz-background-clip: padding;
    background-clip: padding-box;
}

It places a transparent border to the right of the cell and pulls the background color/image away from the border, creating the illusion of spacing between the cells.

Note: For this to work, the parent table must have border-collapse: separate. If you have to work with border-collapse: collapse then you have to apply the same border style to the next table cell, but on the left side, to accomplish the same results.

Java: Rotating Images

Sorry, but all the answers are difficult to understand for me as a beginner in graphics...

After some fiddling, this is working for me and it is easy to reason about.

@Override
public void draw(Graphics2D g) {
    AffineTransform tr = new AffineTransform();
    // X and Y are the coordinates of the image
    tr.translate((int)getX(), (int)getY());
    tr.rotate(
            Math.toRadians(this.rotationAngle),
            img.getWidth() / 2,
            img.getHeight() / 2
    );

    // img is a BufferedImage instance
    g.drawImage(img, tr, null);
}

I suppose that if you want to rotate a rectangular image this method wont work and will cut the image, but I thing you should create square png images and rotate that.

Bind service to activity in Android

"If you start an android Service with startService(..) that Service will remain running until you explicitly invoke stopService(..). There are two reasons that a service can be run by the system. If someone calls Context.startService() then the system will retrieve the service (creating it and calling its onCreate() method if needed) and then call its onStartCommand(Intent, int, int) method with the arguments supplied by the client. The service will at this point continue running until Context.stopService() or stopSelf() is called. Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCommand()), so no matter how many times it is started a service will be stopped once Context.stopService() or stopSelf() is called; however, services can use their stopSelf(int) method to ensure the service is not stopped until started intents have been processed.

Clients can also use Context.bindService() to obtain a persistent connection to a service. This likewise creates the service if it is not already running (calling onCreate() while doing so), but does not call onStartCommand(). The client will receive the IBinder object that the service returns from its onBind(Intent) method, allowing the client to then make calls back to the service. The service will remain running as long as the connection is established (whether or not the client retains a reference on the Service's IBinder). Usually the IBinder returned is for a complex interface that has been written in AIDL.

A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag. Once neither of these situations hold, the Service's onDestroy() method is called and the service is effectively terminated. All cleanup (stopping threads, unregistering receivers) should be complete upon returning from onDestroy()."

Fix footer to bottom of page

For your footer:

#footer {
    position: fixed;
    height: 50px;
    background-color: red;
    bottom: 0px;
    left: 0px;
    right: 0px;
    margin-bottom: 0px;
}

For your body:

body {
    margin-bottom:50px;
}

_x000D_
_x000D_
#footer {_x000D_
  background-color: red;_x000D_
  position: fixed;_x000D_
  bottom: 0px;_x000D_
  left: 0px;_x000D_
  right: 0px;_x000D_
  height: 50px;_x000D_
  margin-bottom: 0px;_x000D_
}_x000D_
_x000D_
div {_x000D_
  margin: 20px 20px;_x000D_
}_x000D_
_x000D_
body {_x000D_
  margin-bottom: 50px;_x000D_
}
_x000D_
<div>_x000D_
  Although most pages on my site have enough content to push the footer to the bottom of the page for most people. I would like to know it's always fixed to the bottom regardless of screen size from now on anyway. I've tried a number of ways such as bottom:_x000D_
  0x; position:absolute: etc. Never seems to work very well, occasionally pushes the footer out of it's container to fix to the bottom using some of those examples right there. Included is the HTML and CSS for the two parts of the footer (footer & copyright_x000D_
  bar). They're both inside of a div anyway. I removed my attempts at getting it to stick so people can have a look at it right now and see what the current code is to amend. Although most pages on my site have enough content to push the footer to the_x000D_
  bottom of the page for most people. I would like to know it's always fixed to the bottom regardless of screen size from now on anyway. I've tried a number of ways such as bottom: 0x; position:absolute: etc. Never seems to work very well, occasionally_x000D_
  pushes the footer out of it's container to fix to the bottom using some of those examples right there. Included is the HTML and CSS for the two parts of the footer (footer & copyright bar). They're both inside of a div anyway. I removed my attempts_x000D_
  at getting it to stick so people can have a look at it right now and see what the current code is to amend. Although most pages on my site have enough content to push the footer to the bottom of the page for most people. I would like to know it's always_x000D_
  fixed to the bottom regardless of screen size from now on anyway. I've tried a number of ways such as bottom: 0x; position:absolute: etc. Never seems to work very well, occasionally pushes the footer out of it's container to fix to the bottom using_x000D_
  some of those examples right there. Included is the HTML and CSS for the two parts of the footer (footer & copyright bar). They're both inside of a div anyway. I removed my attempts at getting it to stick so people can have a look at it right now and_x000D_
  see what the current code is to amend. Although most pages on my site have enough content to push the footer to the bottom of the page for most people. I would like to know it's always fixed to the bottom regardless of screen size from now on anyway._x000D_
  I've tried a number of ways such as bottom: 0x; position:absolute: etc. Never seems to work very well, occasionally pushes the footer out of it's container to fix to the bottom using some of those examples right there. Included is the HTML and CSS for_x000D_
  the two parts of the footer (footer & copyright bar). They're both inside of a div anyway. I removed my attempts at getting it to stick so people can have a look at it right now and see what the current code is to amend. Although most pages on my site_x000D_
  have enough content to push the footer to the bottom of the page for most people. I would like to know it's always fixed to the bottom regardless of screen size from now on anyway. I've tried a number of ways such as bottom: 0x; position:absolute: etc._x000D_
  Never seems to work very well, occasionally pushes the footer out of it's container to fix to the bottom using some of those examples right there. Included is the HTML and CSS for the two parts of the footer (footer & copyright bar). They're both inside_x000D_
  of a div anyway. I removed my attempts at getting it to stick so people can have a look at it right now and see what the current code is to amend. Although most pages on my site have enough content to push the footer to the bottom of the page for most_x000D_
  people. I would like to know it's always fixed to the bottom regardless of screen size from now on anyway. I've tried a number of ways such as bottom: 0x; position:absolute: etc. Never seems to work very well, occasionally pushes the footer out of it's_x000D_
  container to fix to the bottom using some of those examples right there. Included is the HTML and CSS for the two parts of the footer (footer & copyright bar). They're both inside of a div anyway. I removed my attempts at getting it to stick so people_x000D_
  can have a look at it right now and see what the current code is to amend._x000D_
</div>_x000D_
<div id="footer">_x000D_
  This is footer_x000D_
</div>
_x000D_
_x000D_
_x000D_

jsFiddle Demo

Find (and kill) process locking port 3000 on Mac

Using sindresorhus's fkill tool, you can do this:

$ fkill :3000

C++ style cast from unsigned char * to const char *

unsigned char* is basically a byte array and should be used to represent raw data rather than a string generally. A unicode string would be represented as wchar_t*

According to the C++ standard a reinterpret_cast between unsigned char* and char* is safe as they are the same size and have the same construction and constraints. I try to avoid reintrepret_cast even more so than const_cast in general.

If static cast fails with what you are doing you may want to reconsider your design because frankly if you are using C++ you may want to take advantage of what the "plus plus" part offers and use string classes and STL (aka std::basic_string might work better for you)

Oracle insert from select into table with more columns

Just add in the '0' in your select.

INSERT INTO table_name (a,b,c,d)
    SELECT
       other_table.a AS a,
       other_table.b AS b,
       other_table.c AS c,
       '0' AS d
    FROM other_table

How can I set the 'backend' in matplotlib in Python?

FYI, I found I needed to put matplotlib.use('Agg') first in Python import order. For what I was doing (unit testing needed to be headless) that meant putting

import matplotlib
matplotlib.use('Agg')

at the top of my master test script. I didn't have to touch any other files.

How can I check for Python version in a program that uses new language features?

I just found this question after a quick search whilst trying to solve the problem myself and I've come up with a hybrid based on a few of the suggestions above.

I like DevPlayer's idea of using a wrapper script, but the downside is that you end up maintaining multiple wrappers for different OSes, so I decided to write the wrapper in python, but use the same basic "grab the version by running the exe" logic and came up with this.

I think it should work for 2.5 and onwards. I've tested it on 2.66, 2.7.0 and 3.1.2 on Linux and 2.6.1 on OS X so far.

import sys, subprocess
args = [sys.executable,"--version"]

output, error = subprocess.Popen(args ,stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate()
print("The version is: '%s'"  %error.decode(sys.stdout.encoding).strip("qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLMNBVCXZ,.+ \n") )

Yes, I know the final decode/strip line is horrible, but I just wanted to quickly grab the version number. I'm going to refine that.

This works well enough for me for now, but if anyone can improve it (or tell me why it's a terrible idea) that'd be cool too.

How can I pass a parameter to a setTimeout() callback?

Some answers are correct but convoluted.

I am answering this again, 4 years later, because I still run into overly complex code to solve exactly this question. There IS an elegant solution.

First of all, do not pass in a string as the first parameter when calling setTimeout because it effectively invokes a call to the slow "eval" function.

So how do we pass in a parameter to a timeout function? By using closure:

settopic=function(topicid){
  setTimeout(function(){
    //thanks to closure, topicid is visible here
    postinsql(topicid);
  },4000);
}

...
if (xhr.readyState==4){
  settopic(xhr.responseText);
}

Some have suggested using anonymous function when calling the timeout function:

if (xhr.readyState==4){
  setTimeout(function(){
    settopic(xhr.responseText);
  },4000);
}

The syntax works out. But by the time settopic is called, i.e. 4 seconds later, the XHR object may not be the same. Therefore it's important to pre-bind the variables.

HTML5 Video Autoplay not working correctly

_x000D_
_x000D_
html {_x000D_
  padding: 20px 0;_x000D_
  background-color: #efefef;_x000D_
}_x000D_
_x000D_
body {_x000D_
  width: 400px;_x000D_
  padding: 40px;_x000D_
  margin: 0 auto;_x000D_
  background: #fff;_x000D_
  box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.5);_x000D_
}_x000D_
_x000D_
video {_x000D_
  width: 400px;_x000D_
  display: block;_x000D_
}
_x000D_
<video onloadeddata="this.play();this.muted=false;" poster="https://durian.blender.org/wp-content/themes/durian/images/void.png" playsinline loop muted controls>_x000D_
    <source src="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" type="video/mp4" />_x000D_
    Your browser does not support the video tag or the file format of this video._x000D_
</video>
_x000D_
_x000D_
_x000D_

How to show another window from mainwindow in QT

  1. Implement a slot in your QMainWindow where you will open your new Window,
  2. Place a widget on your QMainWindow,
  3. Connect a signal from this widget to a slot from the QMainWindow (for example: if the widget is a QPushButton connect the signal click() to the QMainWindow custom slot you have created).

Code example:

MainWindow.h

// ...
include "newwindow.h"
// ...
public slots:
   void openNewWindow();
// ...
private:
   NewWindow *mMyNewWindow;
// ...
}

MainWindow.cpp

// ...
   MainWindow::MainWindow()
   {
      // ...
      connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
      // ...
   }
// ...
void MainWindow::openNewWindow()
{
   mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
   mMyNewWindow->show();
   // ...
}

This is an example on how display a custom new window. There are a lot of ways to do this.

How do I convert an object to an array?

I ran into an issue with Andy Earnshaw's answer because I had factored this function out to a separate class within my application, "HelperFunctions", which meant the recursive call to objectToArray() failed.

I overcame this by specifying the class name within the array_map call like so:

public function objectToArray($object) {
    if (!is_object($object) && !is_array($object))
        return $object;
    return array_map(array("HelperFunctions", "objectToArray"), (array) $object);
}

I would have written this in the comments but I don't have enough reputation yet.

What is the use of the @Temporal annotation in Hibernate?

We use @Temporal annotation to insert date, time or both in database table.Using TemporalType we can insert data, time or both int table.

@Temporal(TemporalType.DATE) // insert date
@Temporal(TemporalType.TIME) // insert time
@Temporal(TemporalType.TIMESTAMP) // insert  both time and date.

`node-pre-gyp install --fallback-to-build` failed during MeanJS installation on OSX

Hope my scenario can help someone else. I had the same problem with the package bcrypt. First, I have tried with npm i -g node-gyp as suggested by Anne but the problem persisted. Then I read again the error message to have a better understanding of the problem and discovered that the script fails to build the package from scratch - since a precompiled version doesn't exist. In particular, it can't find the g++ command so I solved installing the build-essential package with sudo apt install build-essential -y.

How to create a HashMap with two keys (Key-Pair, Value)?

You can't have an hash map with multiple keys, but you can have an object that takes multiple parameters as the key.

Create an object called Index that takes an x and y value.

public class Index {

    private int x;
    private int y;

    public Index(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public int hashCode() {
        return this.x ^ this.y;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Index other = (Index) obj;
        if (x != other.x)
            return false;
        if (y != other.y)
            return false;
        return true;
    }
}

Then have your HashMap<Index, Value> to get your result. :)

Google Maps API v3: Can I setZoom after fitBounds?

If I'm not mistaken, I'm assuming you want all your points to be visible on the map with the highest possible zoom level. I accomplished this by initializing the zoom level of the map to 16(not sure if it's the highest possible zoom level on V3).

var map = new google.maps.Map(document.getElementById('map_canvas'), {
  zoom: 16,
  center: marker_point,
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

Then after that I did the bounds stuff:

var bounds = new google.maps.LatLngBounds();

// You can have a loop here of all you marker points
// Begin loop
bounds.extend(marker_point);
// End loop

map.fitBounds(bounds);

Result: Success!

Indexes of all occurrences of character in a string

A class for splitting strings I came up with. A short test is provided at the end.

SplitStringUtils.smartSplitToShorterStrings(String str, int maxLen, int maxParts) will split by spaces without breaking words, if possible, and if not, will split by indexes according to maxLen.

Other methods provided to control how it is split: bruteSplitLimit(String str, int maxLen, int maxParts), spaceSplit(String str, int maxLen, int maxParts).

public class SplitStringUtils {

  public static String[] smartSplitToShorterStrings(String str, int maxLen, int maxParts) {
    if (str.length() <= maxLen) {
      return new String[] {str};
    }
    if (str.length() > maxLen*maxParts) {
      return bruteSplitLimit(str, maxLen, maxParts);
    }

    String[] res = spaceSplit(str, maxLen, maxParts);
    if (res != null) {
      return res;
    }

    return bruteSplitLimit(str, maxLen, maxParts);
  }

  public static String[] bruteSplitLimit(String str, int maxLen, int maxParts) {
    String[] bruteArr = bruteSplit(str, maxLen);
    String[] ret = Arrays.stream(bruteArr)
          .limit(maxParts)
          .collect(Collectors.toList())
          .toArray(new String[maxParts]);
    return ret;
  }

  public static String[] bruteSplit(String name, int maxLen) {
    List<String> res = new ArrayList<>();
    int start =0;
    int end = maxLen;
    while (end <= name.length()) {
      String substr = name.substring(start, end);
      res.add(substr);
      start = end;
      end +=maxLen;
    }
    String substr = name.substring(start, name.length());
    res.add(substr);
    return res.toArray(new String[res.size()]);
  }

  public static String[] spaceSplit(String str, int maxLen, int maxParts) {
    List<Integer> spaceIndexes = findSplitPoints(str, ' ');
    List<Integer> goodSplitIndexes = new ArrayList<>();
    int goodIndex = -1; 
    int curPartMax = maxLen;
    for (int i=0; i< spaceIndexes.size(); i++) {
      int idx = spaceIndexes.get(i);
      if (idx < curPartMax) {
        goodIndex = idx;
      } else {
        goodSplitIndexes.add(goodIndex+1);
        curPartMax = goodIndex+1+maxLen;
      }
    }
    if (goodSplitIndexes.get(goodSplitIndexes.size()-1) != str.length()) {
      goodSplitIndexes.add(str.length());
    }
    if (goodSplitIndexes.size()<=maxParts) {
      List<String> res = new ArrayList<>();
      int start = 0;
      for (int i=0; i<goodSplitIndexes.size(); i++) {
        int end = goodSplitIndexes.get(i);
        if (end-start > maxLen) {
          return null;
        }
        res.add(str.substring(start, end));
        start = end;
      }
      return res.toArray(new String[res.size()]);
    }
    return null;
  }


  private static List<Integer> findSplitPoints(String str, char c) {
    List<Integer> list = new ArrayList<Integer>();
    for (int i = 0; i < str.length(); i++) {
      if (str.charAt(i) == c) {
        list.add(i);
      }
    }
    list.add(str.length());
    return list;
  }
}

Simple test code:

  public static void main(String[] args) {
    String [] testStrings = {
        "123",
        "123 123 123 1123 123 123 123 123 123 123",
        "123 54123 5123 513 54w567 3567 e56 73w45 63 567356 735687 4678 4678 u4678 u4678 56rt64w5 6546345",
        "1345678934576235784620957029356723578946",
        "12764444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444",
        "3463356 35673567567 3567 35 3567 35 675 653 673567 777777777777777777777777777777777777777777777777777777777777777777"
    };

    int max = 35;
    int maxparts = 2;


    for (String str : testStrings) {
      System.out.println("TEST\n    |"+str+"|");
      printSplitDetails(max, maxparts);
      String[] res = smartSplitToShorterStrings(str, max, maxparts);
      for (int i=0; i< res.length;i++) {
        System.out.println("  "+i+": "+res[i]);
      }
      System.out.println("===========================================================================================================================================================");
    }

  }

  static void printSplitDetails(int max, int maxparts) {
    System.out.print("  X: ");
    for (int i=0; i<max*maxparts; i++) {
      if (i%max == 0) {
        System.out.print("|");
      } else {
        System.out.print("-");
      }
    }
    System.out.println();
  }

What is a lambda expression in C++11?

Lambda expressions are typically used to encapsulate algorithms so that they can be passed to another function. However, it is possible to execute a lambda immediately upon definition:

[&](){ ...your code... }(); // immediately executed lambda expression

is functionally equivalent to

{ ...your code... } // simple code block

This makes lambda expressions a powerful tool for refactoring complex functions. You start by wrapping a code section in a lambda function as shown above. The process of explicit parameterization can then be performed gradually with intermediate testing after each step. Once you have the code-block fully parameterized (as demonstrated by the removal of the &), you can move the code to an external location and make it a normal function.

Similarly, you can use lambda expressions to initialize variables based on the result of an algorithm...

int a = []( int b ){ int r=1; while (b>0) r*=b--; return r; }(5); // 5!

As a way of partitioning your program logic, you might even find it useful to pass a lambda expression as an argument to another lambda expression...

[&]( std::function<void()> algorithm ) // wrapper section
   {
   ...your wrapper code...
   algorithm();
   ...your wrapper code...
   }
([&]() // algorithm section
   {
   ...your algorithm code...
   });

Lambda expressions also let you create named nested functions, which can be a convenient way of avoiding duplicate logic. Using named lambdas also tends to be a little easier on the eyes (compared to anonymous inline lambdas) when passing a non-trivial function as a parameter to another function. Note: don't forget the semicolon after the closing curly brace.

auto algorithm = [&]( double x, double m, double b ) -> double
   {
   return m*x+b;
   };

int a=algorithm(1,2,3), b=algorithm(4,5,6);

If subsequent profiling reveals significant initialization overhead for the function object, you might choose to rewrite this as a normal function.

Remove the title bar in Windows Forms

Set FormsBorderStyle of the Form to None.

If you do, it's up to you how to implement the dragging and closing functionality of the window.

Use Conditional formatting to turn a cell Red, yellow or green depending on 3 values in another sheet

  1. Highlight the range in question.
  2. On the Home tab, in the Styles Group, Click "Conditional Formatting".
  3. Click "Highlight cell rules"

For the first rule,

Click "greater than", then in the value option box, click on the cell criteria you want it to be less than, than use the format drop-down to select your color.

For the second,

Click "less than", then in the value option box, type "=.9*" and then click the cell criteria, then use the formatting just like step 1.

For the third,

Same as the second, except your formula is =".8*" rather than .9.

Change Schema Name Of Table In SQL

Through SSMS, I created a new schema by:

  • Clicking the Security folder in the Object Explorer within my server,
  • right clicked Schemas
  • Selected "New Schema..."
  • Named my new schema (exe in your case)
  • Hit OK

I found this post to change the schema, but was also getting the same permissions error when trying to change to the new schema. I have several databases listed in my SSMS, so I just tried specifying the database and it worked:

USE (yourservername)  
ALTER SCHEMA exe TRANSFER dbo.Employees 

oracle SQL how to remove time from date

When you convert your string to a date you need to match the date mask to the format in the string. This includes a time element, which you need to remove with truncation:

select 
    p1.PA_VALUE as StartDate,
    p2.PA_VALUE as EndDate
from WP_Work p 
LEFT JOIN PARAMETER p1 on p1.WP_ID=p.WP_ID AND p1.NAME = 'StartDate'
LEFT JOIN PARAMETER p2 on p2.WP_ID=p.WP_ID AND p2.NAME = 'Date_To'
WHERE p.TYPE = 'EventManagement2'
AND trunc(TO_DATE(p1.PA_VALUE, 'DD-MM-YYYY HH24:MI')) >= TO_DATE('25/10/2012', 'DD/MM/YYYY')
AND trunc(TO_DATE(p2.PA_VALUE, 'DD-MM-YYYY HH24:MI')) <= TO_DATE('26/10/2012', 'DD/MM/YYYY')

How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter?

The following will fit the image to 100% of container width while the height is constant. For local assets, use AssetImage

Container(
  width: MediaQuery.of(context).size.width,
  height: 100,
  decoration: BoxDecoration(
    image: DecorationImage(
      fit: BoxFit.fill,
      image: NetworkImage("https://picsum.photos/250?image=9"),
    ),
  ),
)

Image fill modes:

  • Fill - Image is stretched

    fit: BoxFit.fill
    

    enter image description here


  • Fit Height - image kept proportional while making sure the full height of the image is shown (may overflow)

    fit: BoxFit.fitHeight
    

    enter image description here


  • Fit Width - image kept proportional while making sure the full width of the image is shown (may overflow)

    fit: BoxFit.fitWidth
    

    enter image description here


  • Cover - image kept proportional, ensures maximum coverage of the container (may overflow)

    fit: BoxFit.cover
    

    enter image description here


  • Contain - image kept proportional, minimal as possible, will reduce it's size if needed to display the entire image

    fit: BoxFit.contain
    

    enter image description here

restart mysql server on windows 7

I just have the same problem, just open the task manager, go to services tab and search MySQL_One service, rigth click and start, this works for very good.

Close application and launch home screen on Android

You can not do System.exit(), it's not safe.

You can do this one: Process.killProcess(Process.myPid());

Get a json via Http Request in NodeJS

Just tell request that you are using json:true and forget about header and parse

var options = {
    hostname: '127.0.0.1',
    port: app.get('port'),
    path: '/users',
    method: 'GET',
    json:true
}
request(options, function(error, response, body){
    if(error) console.log(error);
    else console.log(body);
});

and the same for post

var options = {
    hostname: '127.0.0.1',
    port: app.get('port'),
    path: '/users',
    method: 'POST',
    json: {"name":"John", "lastname":"Doe"}
}
request(options, function(error, response, body){
    if(error) console.log(error);
    else console.log(body);
});

How to download a folder from github?

You have to download the whole project with either "Clone to desktop" button that will use native github program or "Download as zip".

And then search that folder in downloaded project.

Bootstrap 3 Collapse show state with Chevron icon

Here's a couple of pure css helper classes which lets you handle any kind of toggle content right in your html.

It works with any element you need to switch. Whatever your layout is you just put it inside a couple of elements with the .if-collapsed and .if-not-collapsed classes within the toggle element.

The only catch is that you have to make sure you put the desired initial state of the toggle. If it's initially closed, then put a collapsed class on the toggle.

It also requires the :not selector, it doesn't work on IE8.

HTML example:

<a class="btn btn-primary collapsed" data-toggle="collapse" href="#collapseExample">
  <!--You can put any valid html inside these!-->
  <span class="if-collapsed">Open</span>
  <span class="if-not-collapsed">Close</span>
</a>
<div class="collapse" id="collapseExample">
  <div class="well">
    ...
  </div>
</div>

Less version:

[data-toggle="collapse"] {
    &.collapsed .if-not-collapsed {
         display: none;
    }
    &:not(.collapsed) .if-collapsed {
         display: none;
    }
}

CSS version:

[data-toggle="collapse"].collapsed .if-not-collapsed {
  display: none;
}
[data-toggle="collapse"]:not(.collapsed) .if-collapsed {
  display: none;
}

Why is the <center> tag deprecated in HTML?

You can add this to your css and use <div class="center"></div>

.center{
  text-align: center;
  margin: auto;
  justify-content: center;
  display: flex;
}

or if you want to keep <center></center> and be prepared in case its ever removed, add this to your css

center{
  text-align: center;
  margin: auto;
  justify-content: center;
  display: flex;
}

Saving awk output to variable

as noted earlier, setting bash variables does not allow whitespace between the variable name on the LHS, and the variable value on the RHS, of the '=' sign.

awk can do everything and avoid the "awk"ward extra 'grep'. The use of awk's printf is to not add an unnecessary "\n" in the string which would give perl-ish matcher programs conniptions. The variable/parameter expansion for your case in bash doesn't have that issue, so either of these work:

variable=$(ps -ef | awk '/port 10 \-/ {print $12}')

variable=`ps -ef | awk '/port 10 \-/ {print $12}'`

The '-' int the awk record matching pattern removes the need to remove awk itself from the search results.

JavaScript: Global variables after Ajax requests

The reason your code fails is because post() will start an asynchronous request to the server. What that means for you is that post() returns immediately, not after the request completes, like you are expecting.

What you need, then, is for the request to be synchronous and block the current thread until the request completes. Thus,

var it_works = false;

$.ajax({
  url: 'some_file.php',
  async: false,  # makes request synchronous
  success: function() {
    it_works = true;
  }
});

alert(it_works);

UICollectionView Self Sizing Cells with Auto Layout

contentView anchor mystery:

In one bizarre case this

    contentView.translatesAutoresizingMaskIntoConstraints = false

would not work. Added four explicit anchors to the contentView and it worked.

class AnnoyingCell: UICollectionViewCell {
    
    @IBOutlet var word: UILabel!
    
    override init(frame: CGRect) {
        super.init(frame: frame); common() }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder); common() }
    
    private func common() {
        contentView.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            contentView.leftAnchor.constraint(equalTo: leftAnchor),
            contentView.rightAnchor.constraint(equalTo: rightAnchor),
            contentView.topAnchor.constraint(equalTo: topAnchor),
            contentView.bottomAnchor.constraint(equalTo: bottomAnchor)
        ])
    }
}

and as usual

    estimatedItemSize = UICollectionViewFlowLayout.automaticSize

in YourLayout: UICollectionViewFlowLayout

Who knows? Might help someone.

Credit

https://www.vadimbulavin.com/collection-view-cells-self-sizing/

stumbled on to the tip there - never saw it anywhere else in all the 1000s articles on this.

Using grep to help subset a data frame in R

You may also use the stringr package

library(dplyr)
library(stringr)
My.Data %>% filter(str_detect(x, '^G45'))

You may not use '^' (starts with) in this case, to obtain the results you need

connecting to MySQL from the command line

This worked for me ::-

mysql --host=hostNameorIp --user=username --password=password  

or

mysql --host=hostNameorIp --user=username --password=password database_name

error LNK2005: xxx already defined in MSVCRT.lib(MSVCR100.dll) C:\something\LIBCMT.lib(setlocal.obj)

Some readers will have another issue and need this fix. read the links below. the same problem occured with visual studio 2015 with the advent of windows sdk 10 which brings up libucrt. ucrt is the windows implementation of C Runtime (CRT) aka the posix runtime library. You most likely have code that was ported from unix... Welcome to the drawback

https://support.microsoft.com/en-us/help/148652/a-lnk2005-error-occurs-when-the-crt-library-and-mfc-libraries-are-linked-in-the-wrong-order-in-visual-c

https://github.com/lordmulder/libsndfile-MSVC/blob/master/src/sf_unistd.h

https://lists.gnu.org/archive/html/bug-gnulib/2011-09/msg00224.html

https://msdn.microsoft.com/en-us/library/y23kc048.aspx

https://blogs.msdn.microsoft.com/vcblog/2015/03/03/introducing-the-universal-crt/

Batch file to copy files from one folder to another folder

To bypass the 'specify a file name or directory name on the target (F = file, D = directory)?' prompt with xcopy, you can do the following...

echo f | xcopy /f /y srcfile destfile

or for those of us just copying large substructures/folders:

use /i which specifies destination must be a directory if copying more than one file

Bash integer comparison

This script works!

#/bin/bash
if [[ ( "$#" < 1 ) || ( !( "$1" == 1 ) && !( "$1" == 0 ) ) ]] ; then
    echo this script requires a 1 or 0 as first parameter.
else
    echo "first parameter is $1"
    xinput set-prop 12 "Device Enabled" $0
fi

But this also works, and in addition keeps the logic of the OP, since the question is about calculations. Here it is with only arithmetic expressions:

#/bin/bash
if (( $# )) && (( $1 == 0 || $1 == 1 )); then
    echo "first parameter is $1"
    xinput set-prop 12 "Device Enabled" $0
else
    echo this script requires a 1 or 0 as first parameter.
fi

The output is the same1:

$ ./tmp.sh 
this script requires a 1 or 0 as first parameter.

$ ./tmp.sh 0
first parameter is 0

$ ./tmp.sh 1
first parameter is 1

$ ./tmp.sh 2
this script requires a 1 or 0 as first parameter.

[1] the second fails if the first argument is a string

LINQ equivalent of foreach for IEnumerable<T>

I took Fredrik's method and modified the return type.

This way, the method supports deferred execution like other LINQ methods.

EDIT: If this wasn't clear, any usage of this method must end with ToList() or any other way to force the method to work on the complete enumerable. Otherwise, the action would not be performed!

public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
    foreach (T item in enumeration)
    {
        action(item);
        yield return item;
    }
}

And here's the test to help see it:

[Test]
public void TestDefferedExecutionOfIEnumerableForEach()
{
    IEnumerable<char> enumerable = new[] {'a', 'b', 'c'};

    var sb = new StringBuilder();

    enumerable
        .ForEach(c => sb.Append("1"))
        .ForEach(c => sb.Append("2"))
        .ToList();

    Assert.That(sb.ToString(), Is.EqualTo("121212"));
}

If you remove the ToList() in the end, you will see the test failing since the StringBuilder contains an empty string. This is because no method forced the ForEach to enumerate.

No Such Element Exception?

I Know this question was aked 3 years ago, but I just had the same problem, and what solved it was instead of putting:

 while (i.hasNext()) {
    // code goes here 
}

I did one iteration at the start, and then checked for condition using:

do {
   // code goes here
} while (i.hasNext());

I hope this will help some people at some stage.

Laravel Blade html image

If you use bootstrap, you might use this -

 <img src="{{URL::asset('/image/propic.png')}}" alt="profile Pic" height="200" width="200">

note: inside public folder create a new folder named image then put your images there. Using URL::asset() you can directly access to the public folder.

Regular expressions in C: examples?

man regex.h reports there is no manual entry for regex.h, but man 3 regex gives you a page explaining the POSIX functions for pattern matching.
The same functions are described in The GNU C Library: Regular Expression Matching, which explains that the GNU C Library supports both the POSIX.2 interface and the interface the GNU C Library has had for many years.

For example, for an hypothetical program that prints which of the strings passed as argument match the pattern passed as first argument, you could use code similar to the following one.

#include <errno.h>
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void print_regerror (int errcode, size_t length, regex_t *compiled);

int
main (int argc, char *argv[])
{
  regex_t regex;
  int result;

  if (argc < 3)
    {
      // The number of passed arguments is lower than the number of
      // expected arguments.
      fputs ("Missing command line arguments\n", stderr);
      return EXIT_FAILURE;
    }

  result = regcomp (&regex, argv[1], REG_EXTENDED);
  if (result)
    {
      // Any value different from 0 means it was not possible to 
      // compile the regular expression, either for memory problems
      // or problems with the regular expression syntax.
      if (result == REG_ESPACE)
        fprintf (stderr, "%s\n", strerror(ENOMEM));
      else
        fputs ("Syntax error in the regular expression passed as first argument\n", stderr);
      return EXIT_FAILURE;               
    }
  for (int i = 2; i < argc; i++)
    {
      result = regexec (&regex, argv[i], 0, NULL, 0);
      if (!result)
        {
          printf ("'%s' matches the regular expression\n", argv[i]);
        }
      else if (result == REG_NOMATCH)
        {
          printf ("'%s' doesn't the regular expression\n", argv[i]);
        }
      else
        {
          // The function returned an error; print the string 
          // describing it.
          // Get the size of the buffer required for the error message.
          size_t length = regerror (result, &regex, NULL, 0);
          print_regerror (result, length, &regex);       
          return EXIT_FAILURE;
        }
    }

  /* Free the memory allocated from regcomp(). */
  regfree (&regex);
  return EXIT_SUCCESS;
}

void
print_regerror (int errcode, size_t length, regex_t *compiled)
{
  char buffer[length];
  (void) regerror (errcode, compiled, buffer, length);
  fprintf(stderr, "Regex match failed: %s\n", buffer);
}

The last argument of regcomp() needs to be at least REG_EXTENDED, or the functions will use basic regular expressions, which means that (for example) you would need to use a\{3\} instead of a{3} used from extended regular expressions, which is probably what you expect to use.

POSIX.2 has also another function for wildcard matching: fnmatch(). It doesn't allow to compile the regular expression, or get the substrings matching a sub-expression, but it is very specific for checking when a filename match a wildcard (e.g. it uses the FNM_PATHNAME flag).

javascript regular expression to not match a word

function doesNotContainAbcOrDef(x) {
    return (x.match('abc') || x.match('def')) === null;
}

Git diff between current branch and master but not including unmerged master commits

Here's what worked for me:

git diff origin/master...

This shows only the changes between my currently selected local branch and the remote master branch, and ignores all changes in my local branch that came from merge commits.

How to use `replace` of directive definition?

You are getting confused with transclude: true, which would append the inner content.

replace: true means that the content of the directive template will replace the element that the directive is declared on, in this case the <div myd1> tag.

http://plnkr.co/edit/k9qSx15fhSZRMwgAIMP4?p=preview

For example without replace:true

<div myd1><span class="replaced" myd1="">directive template1</span></div>

and with replace:true

<span class="replaced" myd1="">directive template1</span>

As you can see in the latter example, the div tag is indeed replaced.

Concatenate string with field value in MySQL

SELECT ..., CONCAT( 'category_id=', tableOne.category_id) as query2  FROM tableOne 
LEFT JOIN tableTwo
ON tableTwo.query = query2

Move / Copy File Operations in Java

Here's how to do this with java.nio operations:

public static void copyFile(File sourceFile, File destFile) throws IOException {
    if(!destFile.exists()) {
        destFile.createNewFile();
    }

    FileChannel source = null;
    FileChannel destination = null;
    try {
        source = new FileInputStream(sourceFile).getChannel();
        destination = new FileOutputStream(destFile).getChannel();

        // previous code: destination.transferFrom(source, 0, source.size());
        // to avoid infinite loops, should be:
        long count = 0;
        long size = source.size();              
        while((count += destination.transferFrom(source, count, size-count))<size);
    }
    finally {
        if(source != null) {
            source.close();
        }
        if(destination != null) {
            destination.close();
        }
    }
}

If Else If In a Sql Server Function

No one seems to have picked that if (yes=no)>na or (no=na)>yes or (na=yes)>no, you get NULL as the result. Don't believe this is what you are after.

Here's also a more condensed form of the function, which works even if any of yes, no or na_ans is NULL.

USE [***]
GO
/****** Object:  UserDefinedFunction [dbo].[fnActionSq]    Script Date: 02/17/2011 10:21:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[fnTally] (@SchoolId nvarchar(50))
RETURNS nvarchar(3)
AS 
BEGIN
return (select (
       select top 1 Result from
       (select 'Yes' Result, yes_ans union all
        select 'No', no_ans union all
        select 'N/A', na_ans) [ ]
        order by yes_ans desc, Result desc)
       from dbo.qrc_maintally
       where school_id = @SchoolId)
End

Save the plots into a PDF

Never mind got the way to do it.

def plotGraph(X,Y):
     fignum = random.randint(0,sys.maxint)
     fig = plt.figure(fignum)
     ### Plotting arrangements ###
     return fig

------ plotting module ------

----- mainModule ----

 import matplotlib.pyplot as plt
 ### tempDLStats, tempDLlabels are the argument
 plot1 = plotGraph(tempDLstats, tempDLlabels)
 plot2 = plotGraph(tempDLstats_1, tempDLlabels_1)
 plot3 = plotGraph(tempDLstats_2, tempDLlabels_2)
 plt.show()
 plot1.savefig('plot1.png')
 plot2.savefig('plot2.png')
 plot3.savefig('plot3.png')

----- mainModule -----

Cannot instantiate the type List<Product>

Use a concrete list type, e.g. ArrayList instead of just List.

Can I make 'git diff' only the line numbers AND changed file names?

1) My favorite:

git diff --name-status

Prepends file status, e.g.:

A   new_file.txt
M   modified_file.txt 
D   deleted_file.txt

2) If you want statistics, then:

git diff --stat

will show something like:

new_file.txt         |  50 +
modified_file.txt    | 100 +-
deleted_file         |  40 -

3) Finally, if you really want only the filenames:

git diff --name-only

Will simply show:

new_file.txt
modified_file.txt
deleted_file

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

Shouldn't you add to the login form?;

<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/> 

As stated in the here in the Spring security documentation

Disable EditText blinking cursor

  1. Change focus to another view (ex: Any textview or Linearlayout in the XML) using

    android:focusableInTouchMode="true"
    android:focusable="true"
    
  2. set addTextChangedListener to edittext in Activity.

  3. and then on aftertextchanged of Edittext put edittext.clearFocus();

This will enable the cursor when keyboard is open and disable when keyboard is closed.

When to use single quotes, double quotes, and backticks in MySQL

Single quotes should be used for string values like in the VALUES() list.

Backticks are generally used to indicate an identifier and as well be safe from accidentally using the reserved keywords.

In combination of PHP and MySQL, double quotes and single quotes make your query writing time so much easier.

How to initialize array to 0 in C?

Global variables and static variables are automatically initialized to zero. If you have simply

char ZEROARRAY[1024];

at global scope it will be all zeros at runtime. But actually there is a shorthand syntax if you had a local array. If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type. You could write:

char ZEROARRAY[1024] = {0};

The compiler would fill the unwritten entries with zeros. Alternatively you could use memset to initialize the array at program startup:

memset(ZEROARRAY, 0, 1024);

That would be useful if you had changed it and wanted to reset it back to all zeros.

How to implement Android Pull-to-Refresh

I've also implemented a robust, open source, easy to use and highly customizable PullToRefresh library for Android. You can replace your ListView with the PullToRefreshListView as described in the documentation on the project page.

https://github.com/erikwt/PullToRefresh-ListView

What is the difference between the operating system and the kernel?

The kernel is part of the operating system and closer to the hardware it provides low level services like:

  • device driver
  • process management
  • memory management
  • system calls

An operating system also includes applications like the user interface (shell, gui, tools, and services).

In CSS how do you change font size of h1 and h2

 h1 { font-size: 150%; }
 h2 { font-size: 120%; }

Tune as needed.

Should I use 'border: none' or 'border: 0'?

While results will most likely be the same (no border), the 0 and none are technically addressing different things.

0 addresses border width and none addresses border style. Obviously a border of 0 width is nonexistent so will therefore have no style.

However, if later on in your stylesheet you intend to override this, you would naturally specifically address one or the other. If I now wanted a 3px border, that would be directly overriding border: 0 in regards to width. If I now wanted a dotted border, that would be directly overriding border: none in regards to styling.

How to change color of Toolbar back button in Android?

I did it this way using the Material Components library:

<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
    <item name="drawerArrowStyle">@style/AppTheme.DrawerArrowToggle</item>
</style>

<style name="AppTheme.DrawerArrowToggle" parent="Widget.AppCompat.DrawerArrowToggle">
    <item name="color">@android:color/white</item>
</style>

How do I check the difference, in seconds, between two dates?

We have function total_seconds() with Python 2.7 Please see below code for python 2.6

import datetime
import time  

def diffdates(d1, d2):
    #Date format: %Y-%m-%d %H:%M:%S
    return (time.mktime(time.strptime(d2,"%Y-%m-%d %H:%M:%S")) -
               time.mktime(time.strptime(d1, "%Y-%m-%d %H:%M:%S")))

d1 = datetime.now()
d2 = datetime.now() + timedelta(days=1)
diff = diffdates(d1, d2)

How can I lock the first row and first column of a table when scrolling, possibly using JavaScript and CSS?

Sort and Lock Table is the only solution I have seen which does work on other browsers than IE. (although this "locked column css" might do the trick as well). Required code block below.

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="robots" content="noindex, nofollow">
  <meta name="googlebot" content="noindex, nofollow">
  <script type="text/javascript" src="/js/lib/dummy.js"></script>
    <link rel="stylesheet" type="text/css" href="/css/result-light.css">
  <style type="text/css">
    /* Scrollable Content Height */
.scrollContent {
 height:100px;
 overflow-x:hidden;
 overflow-y:auto;
}
.scrollContent tr {
 height: auto;
 white-space: nowrap;
}

/* Prevent Mozilla scrollbar from hiding right-most cell content */
.scrollContent tr td:last-child {
 padding-right: 20px;
}

/* Fixed Header Height */
.fixedHeader tr {
 position: relative;
 height: auto;
}

/* Put border around entire table */
div.TableContainer {
 border: 1px solid #7DA87D;
}

/* Table Header formatting */
.headerFormat {
 background-color: white;
 color: #FFFFFF;
 margin: 3px;
 padding: 1px;
 white-space: nowrap;
 font-family: Helvetica;
 font-size: 16px;
 text-decoration: none;
 font-weight: bold;
}
.headerFormat tr td {
 border: 1px solid #000000;
 background-color: #7DA87D;
}

/* Table Body (Scrollable Content) formatting */
.bodyFormat tr td {
    color: #000000;
    margin: 3px;
    padding: 1px;
    border: 0px none;
    font-family: Helvetica;
    font-size: 12px;
}

/* Use to set different color for alternating rows */
.alternateRow {
  background-color: #E0F1E0;
}

/* Styles used for SORTING */
.point {
 cursor:pointer;
}
td.sortedColumn {
  background-color: #E0F1E0;
}

tr.alternateRow td.sortedColumn {
  background-color: #c5e5c5;
}
.total {
    background-color: #FED362;
    color: #000000;
    white-space: nowrap;
    font-size: 12px;
    text-decoration: none;
}
  </style>

  <title></title>
<script type='text/javascript'>//<![CDATA[

/* This script and many more are available free online at
The JavaScript Source :: http://www.javascriptsource.com
Created by: Stan Slaughter :: http://www.stansight.com/ */

/* ======================================================
Generic Table Sort

Basic Concept: A table can be sorted by clicking on the title of any
column in the table, toggling between ascending and descending sorts.


Assumptions:

* The first row of the table contains column titles that are "clicked"
  to sort the table

* The images 'desc.gif','asc.gif','none.gif','sorting.gif' exist

* The img tag is in each column of the the title row to represent the
  sort graphic.

* The CSS classes 'alternateRow' and 'sortedColumn' exist so we can
  have alternating colors for each row and a highlight the sorted
  column.  Something like the <style> definition below, but with the
  background colors set to whatever you want.

   <style>
   tr.alternateRow {
     background-color: #E0F1E0;
   }

   td.sortedColumn {
     background-color: #E0F1E0;
   }

   tr.alternateRow td.sortedColumn {
     background-color: #c5e5c5;
   }
   </style>

====================================================== */

function sortTable(td_element,ignoreLastLines) {

  // If the optional ignoreLastLines parameter (number of lines *not* to sort at end of table)
  // was not passed then make it 0
  ignoreLastLines = (typeof(ignoreLastLines)=='undefined') ? 0 : ignoreLastLines;

  var sortImages =['data:image/gif;base64,R0lGODlhCgAKAMQXAJOkk3mReXume3uTe3mieXGPcXOYc/Hx8Xadds/Wz9vg24ejh3GUcYOgg6a0pnGVcfP18+3w7c3TzdPY06u4q/r8+v///////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABcALAAAAAAKAAoAAAUz4IVcZDleixQIQjA1pFFZx2FVRklZvOWUl8LsVgBeFLyE8TLgDZYESISwvAAA1QvjAQwBADs=','data:image/gif;base64,R0lGODlhCgAKAMQXAJOkk3mReXume3uTe3mieXGPcXOYc/Hx8Xadds/Wz9vg24ejh3GUcYOgg6a0pnGVcfP18+3w7c3TzdPY06u4q/r8+v///////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABcALAAAAAAKAAoAAAUw4CVeDzOeFwCgIhFBBDtY1sAmtIIWFV0VJweNRhkZeoeDpWIQNSYBgSAgWYgQLGwIADs=','data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7','http://web.archive.org/web/20150906203819im_/http://www.javascriptsource.com/miscellaneous/sorting.gif'];

  // Get the image used in the first row of the current column
  var sortColImage = td_element.getElementsByTagName('img')[0];

  // If current image is 'asc.gif' or 'none.gif' (elements 1 and 2 of sortImages array) then this will
  // be a descending sort else it will be ascending - get new sort image icon and set sort order flag
  var sortAscending = false;
  var newSortColImage = "";
  if (sortColImage.getAttribute('src').indexOf(sortImages[1])>-1 ||
    sortColImage.getAttribute('src').indexOf(sortImages[2])>-1) {
    newSortColImage = sortImages[0];
    sortAscending = false;
  } else {
    newSortColImage = sortImages[1];
    sortAscending = true;
  }

  // Assign "SORTING" image icon (element 3 of sortImages array)) to current column title
  // (will replace with newSortColImage when sort completes)
  sortColImage.setAttribute('src',sortImages[3]);

  // Find which column was clicked by getting it's column position
  var indexCol = td_element.cellIndex;

  // Get the table element from the td element that was passed as a parameter to this function
  var table_element = td_element.parentNode;
  while (table_element.nodeName != "TABLE") {
    table_element = table_element.parentNode;
  }

  // Get all "tr" elements from the table and assign then to the Array "tr_elements"
  var tr_elements = table_element.getElementsByTagName('tr');

  // Get all the images used in the first row then set them to 'none.gif'
  // (element 2 or sortImages array) except for the current column (all ready been changed)
  var allImg = tr_elements[0].getElementsByTagName('img');
    for(var i=0;i<allImg.length;i++){
    if(allImg[i]!=sortColImage){allImg[i].setAttribute('src',sortImages[2])}
  }

  // Some explantion of the basic concept of the following code before we
  // actually start.  Essentially we are going to copy the current columns information
  // into an array to be sorted. We'll sort the column array then go back and use the information
  // we saved about the original row positions to re-order the entire table.
  // We are never really sorting more than a columns worth of data, which should keep the sorting fast.

  // Create a new array for holding row information
  var clonedRows = new Array()

  // Create a new array to store just the selected column values, not the whole row
  var originalCol = new Array();

  // Now loop through all the data row elements
  // NOTE: Starting at row 1 because row 0 contains the column titles
  for (var i=1; i<tr_elements.length - ignoreLastLines; i++) {

   // "Clone" the tr element i.e. save a copy all of its attributes and values
   clonedRows[i]=tr_elements[i].cloneNode(true);

   // Text value of the selected column on this row
   var valueCol = getTextValue(tr_elements[i].cells[indexCol]);

   // Format text value for sorting depending on its type, ie Date, Currency, number, etc..
   valueCol = FormatForType(valueCol);

   // Assign the column value AND the row number it was originally on in the table
   originalCol[i]=[valueCol,tr_elements[i].rowIndex];
  }

  // Get rid of element "0" from this array.  A value was never assigned to it because the first row
  // in the table just contained the column titles, which we did not bother to assign.
  originalCol.shift();

  // Sort the column array returning the value of a sort into a new array
  sortCol = originalCol.sort(sortCompare);

  // If it was supposed to be an Ascending sort then reverse the order
  if (sortAscending) { sortCol.reverse(); }

  // Now take the values from the sorted column array and use that information to re-arrange
  // the order of the tr_elements in the table
  for (var i=1; i < tr_elements.length - ignoreLastLines; i++) {

    var old_row = sortCol[i-1][1];
    var new_row = i;
    tr_elements[i].parentNode.replaceChild(clonedRows[old_row],tr_elements[new_row]);
  }

   // Format the table, making the rows alternating colors and highlight the sorted column
   makePretty(table_element,indexCol,ignoreLastLines);

  // Assign correct sort image icon to current column title
  sortColImage.setAttribute('src',newSortColImage);
}

// Function used by the sort routine to compare the current value in the array with the next one
function sortCompare (currValue, nextValue) {
 // Since the elements of this array are actually arrays themselves, just sort
 // on the first element which contiains the value, not the second which contains
 // the original row position
  if ( currValue[0] == nextValue[0] ) return 0;
  if ( currValue[0] < nextValue[0] ) return -1;
  if ( currValue[0] > nextValue[0] ) return 1;
}

//-----------------------------------------------------------------------------
// Functions to get and compare values during a sort.
//-----------------------------------------------------------------------------

// This code is necessary for browsers that don't reflect the DOM constants
// (like IE).
if (document.ELEMENT_NODE == null) {
   document.ELEMENT_NODE = 1;
   document.TEXT_NODE = 3;
}

function getTextValue(el) {
  var i;
  var s;
  // Find and concatenate the values of all text nodes contained within the
  // element.
  s = "";
  for (i = 0; i < el.childNodes.length; i++)
    if (el.childNodes[i].nodeType == document.TEXT_NODE)
      s += el.childNodes[i].nodeValue;
    else if (el.childNodes[i].nodeType == document.ELEMENT_NODE &&
             el.childNodes[i].tagName == "BR")
      s += " ";
    else
      // Use recursion to get text within sub-elements.
      s += getTextValue(el.childNodes[i]);

  return normalizeString(s);
}

// Regular expressions for normalizing white space.
var whtSpEnds = new RegExp("^\\s*|\\s*$", "g");
var whtSpMult = new RegExp("\\s\\s+", "g");

function normalizeString(s) {
  s = s.replace(whtSpMult, " ");  // Collapse any multiple whites space.
  s = s.replace(whtSpEnds, "");   // Remove leading or trailing white space.
  return s;
}

// Function used to modify values to make then sortable depending on the type of information
function FormatForType(itm) {
  var sortValue = itm.toLowerCase();

  // If the item matches a date pattern (MM/DD/YYYY or MM/DD/YY or M/DD/YYYY)
  if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d\d\d$/) ||
      itm.match(/^\d\d[\/-]\d\d[\/-]\d\d$/) ||
      itm.match(/^\d[\/-]\d\d[\/-]\d\d\d\d$/) ) {

    // Convert date to YYYYMMDD format for sort comparison purposes
    // y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
    var yr = -1;

    if (itm.length == 10) {
      sortValue = itm.substr(6,4)+itm.substr(0,2)+itm.substr(3,2);
     } else if (itm.length == 9) {
      sortValue = itm.substr(5,4)+"0" + itm.substr(0,1)+itm.substr(2,2);
    } else {
      yr = itm.substr(6,2);
      if (parseInt(yr) < 50) {
        yr = '20'+yr;
      } else {
        yr = '19'+yr;
      }
        sortValue = yr+itm.substr(3,2)+itm.substr(0,2);
    }

  }



  // If the item matches a Percent patten (contains a percent sign)
  if (itm.match(/%/)) {
   // Replace anything that is not part of a number (decimal pt, neg sign, or 0 through 9) with an empty string.
   sortValue = itm.replace(/[^0-9.-]/g,'');
   sortValue = parseFloat(sortValue);
  }

  // If item starts with a "(" and ends with a ")" then remove them and put a negative sign in front
  if (itm.substr(0,1) == "(" & itm.substr(itm.length - 1,1) == ")") {
   itm = "-" + itm.substr(1,itm.length - 2);
  }

// If the item matches a currency pattern (starts with a dollar or negative dollar sign)
  if (itm.match(/^[£$]|(^-)/)) {
   // Replace anything that is not part of a number (decimal pt, neg sign, or 0 through 9) with an empty string.
   sortValue = itm.replace(/[^0-9.-]/g,'');
   if (isNaN(sortValue)) {
     sortValue = 0;
   } else {
     sortValue = parseFloat(sortValue);
   }
}

  // If the item matches a numeric pattern
  if (itm.match(/(\d*,\d*$)|(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/)) {
   // Replace anything that is not part of a number (decimal pt, neg sign, or 0 through 9) with an empty string.
   sortValue = itm.replace(/[^0-9.-]/g,'');
 //  sortValue = sortValue.replace(/,/g,'');
   if (isNaN(sortValue)) {
     sortValue = 0;
   } else {
     sortValue = parseFloat(sortValue);
   }
  }

  return sortValue;
}

//-----------------------------------------------------------------------------
// Functions to update the table appearance after a sort.
//-----------------------------------------------------------------------------

// Style class names.
var rowClsNm = "alternateRow";
var colClsNm = "sortedColumn";

// Regular expressions for setting class names.
var rowTest = new RegExp(rowClsNm, "gi");
var colTest = new RegExp(colClsNm, "gi");

function makePretty(tblEl, col, ignoreLastLines) {

  var i, j;
  var rowEl, cellEl;

  // Set style classes on each row to alternate their appearance.
  for (i = 1; i < tblEl.rows.length - ignoreLastLines; i++) {
   rowEl = tblEl.rows[i];
   rowEl.className = rowEl.className.replace(rowTest, "");
    if (i % 2 != 0)
      rowEl.className += " " + rowClsNm;
    rowEl.className = normalizeString(rowEl.className);
    // Set style classes on each column (other than the name column) to
    // highlight the one that was sorted.
    for (j = 0; j < tblEl.rows[i].cells.length; j++) {
      cellEl = rowEl.cells[j];
      cellEl.className = cellEl.className.replace(colTest, "");
      if (j == col)
        cellEl.className += " " + colClsNm;
      cellEl.className = normalizeString(cellEl.className);
    }
  }


}

// END Generic Table sort.

// =================================================

// Function to scroll to top before sorting to fix an IE bug
// Which repositions the header off the top of the screen
// if you try to sort while scrolled to bottom.
function GoTop() {
 document.getElementById('TableContainer').scrollTop = 0;
}

//]]> 
</script>
</head>
<body>
  <table cellpadding="0" cellspacing="0" border="0">
<tr><td>
<div id="TableContainer" class="TableContainer" style="height:230px;">
<table class="scrollTable">
 <thead class="fixedHeader headerFormat">
  <tr>
   <td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort"><b>NAME</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
   <td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Amt</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
   <td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Lvl</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
   <td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Rank</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
   <td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Position</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
   <td class="point" onclick="GoTop(); sortTable(this,1);" title="Sort" align="right"><b>Date</b> <img src="data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7" border="0"></td>
  </tr>
 </thead>
 <tbody class="scrollContent bodyFormat" style="height:200px;">
   <tr class="alternateRow">
    <td>Maha</td>
    <td align="right">$19,923.19</td>
    <td align="right">100</td>
    <td align="right">100</td>
    <td>Owner</td>
    <td align="right">01/02/2001</td>
   </tr>
   <tr>
    <td>Thrawl</td>
    <td align="right">$9,550</td>
    <td align="right">159</td>
    <td align="right">100%</td>
    <td>Co-Owner</td>
    <td align="right">11/07/2003</td>
   </tr>
   <tr class="alternateRow">
    <td>Marhanen</td>
    <td align="right">$223.04</td>
    <td align="right">83</td>
    <td align="right">99%</td>
    <td>Banker</td>
    <td align="right">06/27/2006</td>
   </tr>
   <tr>
    <td>Peter</td>
    <td align="right">$121</td>
    <td align="right">567</td>
    <td align="right">23423%</td>
    <td>FishHead</td>
    <td align="right">06/06/2006</td>
   </tr>
   <tr class="alternateRow">
    <td>Jones</td>
    <td align="right">$15</td>
    <td align="right">11</td>
    <td align="right">15%</td>
    <td>Bubba</td>
    <td align="right">10/27/2005</td>
   </tr>
   <tr>
    <td>Supa-De-Dupa</td>
    <td align="right">$145</td>
    <td align="right">91</td>
    <td align="right">32%</td>
    <td>momma</td>
    <td align="right">12/15/1996</td>
   </tr>
   <tr class="alternateRow">
    <td>ClickClock</td>
    <td align="right">$1,213</td>
    <td align="right">23</td>
    <td align="right">1%</td>
    <td>Dada</td>
    <td align="right">1/30/1998</td>
   </tr>
   <tr>
    <td>Mrs. Robinson</td>
    <td align="right">$99</td>
    <td align="right">99</td>
    <td align="right">99%</td>
    <td>Wife</td>
    <td align="right">07/04/1963</td>
   </tr>
   <tr class="alternateRow">
    <td>Maha</td>
    <td align="right">$19,923.19</td>
    <td align="right">100</td>
    <td align="right">100%</td>
    <td>Owner</td>
    <td align="right">01/02/2001</td>
   </tr>
   <tr>
    <td>Thrawl</td>
    <td align="right">$9,550</td>
    <td align="right">159</td>
    <td align="right">100%</td>
    <td>Co-Owner</td>
    <td align="right">11/07/2003</td>
   </tr>
   <tr class="alternateRow">
    <td>Marhanen</td>
    <td align="right">$223.04</td>
    <td align="right">83</td>
    <td align="right">59%</td>
    <td>Banker</td>
    <td align="right">06/27/2006</td>
   </tr>
   <tr>
    <td>Peter</td>
    <td align="right">$121</td>
    <td align="right">567</td>
    <td align="right">534.23%</td>
    <td>FishHead</td>
    <td align="right">06/06/2006</td>
   </tr>
   <tr class="alternateRow">
    <td>Jones</td>
    <td align="right">$15</td>
    <td align="right">11</td>
    <td align="right">15%</td>
    <td>Bubba</td>
    <td align="right">10/27/2005</td>
   </tr>
   <tr>
    <td>Supa-De-Dupa</td>
    <td align="right">$145</td>
    <td align="right">91</td>
    <td align="right">42%</td>
    <td>momma</td>
    <td align="right">12/15/1996</td>
   </tr>
   <tr class="alternateRow">
    <td>ClickClock</td>
    <td align="right">$1,213</td>
    <td align="right">23</td>
    <td align="right">2%</td>
    <td>Dada</td>
    <td align="right">1/30/1998</td>
   </tr>
   <tr>
    <td>Mrs. Robinson</td>
    <td align="right">$99</td>
    <td align="right">99</td>
    <td align="right">(-10.42%)</td>
    <td>Wife</td>
    <td align="right">07/04/1963</td>
   </tr>
   <tr class="alternateRow">
    <td>Maha</td>
    <td align="right">-$19,923.19</td>
    <td align="right">100</td>
    <td align="right">(-10.01%)</td>
    <td>Owner</td>
    <td align="right">01/02/2001</td>
   </tr>
   <tr>
    <td>Thrawl</td>
    <td align="right">$9,550</td>
    <td align="right">159</td>
    <td align="right">-10.20%</td>
    <td>Co-Owner</td>
    <td align="right">11/07/2003</td>
   </tr>
   <tr class="total">
    <td><strong>TOTAL</strong>:</td>
    <td align="right"><strong>999999</strong></td>
    <td align="right"><strong>9999999</strong></td>
    <td align="right"><strong>99</strong></td>
    <td > </td>
    <td align="right"> </td>
   </tr>
 </tbody>
</table>
</div>
</td></tr>
</table>
</body>
</html>

How to show Bootstrap table with sort icon

Use this icons with bootstrap (glyphicon):

<span class="glyphicon glyphicon-triangle-bottom"></span>
<span class="glyphicon glyphicon-triangle-top"></span>

http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_glyph_triangle-bottom&stacked=h

http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_glyph_triangle-bottom&stacked=h

C# looping through an array

Not too difficult. Just increment the counter of the for loop by 3 each iteration and then offset the indexer to get the batch of 3 at a time:

for(int i=0; i < theData.Length; i+=3)
{
    var item1 = theData[i];
    var item2 = theData[i+1];
    var item3 = theData[i+2];
}

If the length of the array wasn't garuanteed to be a multiple of three, you would need to check the upper bound with theData.Length - 2 instead.

Import python package from local directory into interpreter

You can use relative imports only from in a module that was in turn imported as part of a package -- your script or interactive interpreter wasn't, so of course from . import (which means "import from the same package I got imported from") doesn't work. import mypackage will be fine once you ensure the parent directory of mypackage is in sys.path (how you managed to get your current directory away from sys.path I don't know -- do you have something strange in site.py, or...?)

To get your current directory back into sys.path there is in fact no better way than putting it there.

BSTR to std::string (std::wstring) and vice versa

There is a c++ class called _bstr_t. It has useful methods and a collection of overloaded operators.

For example, you can easily assign from a const wchar_t * or a const char * just doing _bstr_t bstr = L"My string"; Then you can convert it back doing const wchar_t * s = bstr.operator const wchar_t *();. You can even convert it back to a regular char const char * c = bstr.operator char *(); You can then just use the const wchar_t * or the const char * to initialize a new std::wstring oe std::string.

correct configuration for nginx to localhost?

Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.

 server {
            listen       80;
            server_name  localhost;

            access_log  logs/localhost.access.log  main;

            location / {
                root /var/www/board/public;
                index index.html index.htm index.php;
            }
       }

Python: Removing spaces from list objects

String methods return the modified string.

k = [x.replace(' ', '') for x in hello]

MySQL ORDER BY multiple column ASC and DESC

Ok, I THINK I understand what you want now, and let me clarify to confirm before the query. You want 1 record for each user. For each user, you want their BEST POINTS score record. Of the best points per user, you want the one with the best average time. Once you have all users "best" values, you want the final results sorted with best points first... Almost like ranking of a competition.

So now the query. If the above statement is accurate, you need to start with getting the best point/average time per person and assigning a "Rank" to that entry. This is easily done using MySQL @ variables. Then, just include a HAVING clause to only keep those records ranked 1 for each person. Finally apply the order by of best points and shortest average time.

select
      U.UserName,
      PreSortedPerUser.Point,
      PreSortedPerUser.Avg_Time,
      @UserRank := if( @lastUserID = PreSortedPerUser.User_ID, @UserRank +1, 1 ) FinalRank,
      @lastUserID := PreSortedPerUser.User_ID
   from
      ( select
              S.user_id,
              S.point,
              S.avg_time
           from
              Scores S
           order by
              S.user_id,
              S.point DESC,
              S.Avg_Time ) PreSortedPerUser
         JOIN Users U
            on PreSortedPerUser.user_ID = U.ID,
      ( select @lastUserID := 0,
               @UserRank := 0 ) sqlvars 
   having
      FinalRank = 1
   order by
      Point Desc,
      Avg_Time

Results as handled by SQLFiddle

Note, due to the inline @variables needed to get the answer, there are the two extra columns at the end of each row. These are just "left-over" and can be ignored in any actual output presentation you are trying to do... OR, you can wrap the entire thing above one more level to just get the few columns you want like

select 
      PQ.UserName,
      PQ.Point,
      PQ.Avg_Time
   from
      ( entire query above pasted here ) as PQ

PHPmailer sending HTML CODE

just you need to pass true as an argument to IsHTML() function.

How can I hide or encrypt JavaScript code?

The only safe way to protect your code is not giving it away. With client deployment, there is no avoiding the client having access to the code.

So the short answer is: You can't do it

The longer answer is considering flash or Silverlight. Although I believe silverlight will gladly give away it's secrets with reflector running on the client.

I'm not sure if something simular exists with the flash platform.

How to run a cron job inside a docker container?

Setup a cron in parallel to a one-time job

Create a script file, say run.sh, with the job that is supposed to run periodically.

#!/bin/bash
timestamp=`date +%Y/%m/%d-%H:%M:%S`
echo "System path is $PATH at $timestamp"

Save and exit.

Use Entrypoint instead of CMD

f you have multiple jobs to kick in during docker containerization, use the entrypoint file to run them all.

Entrypoint file is a script file that comes into action when a docker run command is issued. So, all the steps that we want to run can be put in this script file.

For instance, we have 2 jobs to run:

Run once job: echo “Docker container has been started”

Run periodic job: run.sh

Create entrypoint.sh

#!/bin/bash

# Start the run once job.
echo "Docker container has been started"

# Setup a cron schedule
echo "* * * * * /run.sh >> /var/log/cron.log 2>&1
# This extra line makes it a valid cron" > scheduler.txt

crontab scheduler.txt
cron -f

Let’s understand the crontab that has been set up in the file

* * * * *: Cron schedule; the job must run every minute. You can update the schedule based on your requirement.

/run.sh: The path to the script file which is to be run periodically

/var/log/cron.log: The filename to save the output of the scheduled cron job.

2>&1: The error logs(if any) also will be redirected to the same output file used above.

Note: Do not forget to add an extra new line, as it makes it a valid cron. Scheduler.txt: the complete cron setup will be redirected to a file.

Using System/User specific environment variables in cron

My actual cron job was expecting most of the arguments as the environment variables passed to the docker run command. But, with bash, I was not able to use any of the environment variables that belongs to the system or the docker container.

Then, this came up as a walkaround to this problem:

  1. Add the following line in the entrypoint.sh
declare -p | grep -Ev 'BASHOPTS|BASH_VERSINFO|EUID|PPID|SHELLOPTS|UID' > /container.env
  1. Update the cron setup and specify-
SHELL=/bin/bash
BASH_ENV=/container.env

At last, your entrypoint.sh should look like

#!/bin/bash

# Start the run once job.
echo "Docker container has been started"

declare -p | grep -Ev 'BASHOPTS|BASH_VERSINFO|EUID|PPID|SHELLOPTS|UID' > /container.env

# Setup a cron schedule
echo "SHELL=/bin/bash
BASH_ENV=/container.env
* * * * * /run.sh >> /var/log/cron.log 2>&1
# This extra line makes it a valid cron" > scheduler.txt

crontab scheduler.txt
cron -f

Last but not the least: Create a Dockerfile

FROM ubuntu:16.04
MAINTAINER Himanshu Gupta

# Install cron
RUN apt-get update && apt-get install -y cron

# Add files
ADD run.sh /run.sh
ADD entrypoint.sh /entrypoint.sh

RUN chmod +x /run.sh /entrypoint.sh

ENTRYPOINT /entrypoint.sh

That’s it. Build and Run the Docker image!

Replace all 0 values to NA

Let me assume that your data.frame is a mix of different datatypes and not all columns need to be modified.

to modify only columns 12 to 18 (of the total 21), just do this

df[, 12:18][df[, 12:18] == 0] <- NA

How do you make an array of structs in C?

That error means that the compiler is not able to find the definition of the type of your struct before the declaration of the array of structs, since you're saying you have the definition of the struct in a header file and the error is in nbody.c then you should check if you're including correctly the header file. Check your #include's and make sure the definition of the struct is done before declaring any variable of that type.

Convert string to Python class object?

You want the class Baz, which lives in module foo.bar. With Python 2.7, you want to use importlib.import_module(), as this will make transitioning to Python 3 easier:

import importlib

def class_for_name(module_name, class_name):
    # load the module, will raise ImportError if module cannot be loaded
    m = importlib.import_module(module_name)
    # get the class, will raise AttributeError if class cannot be found
    c = getattr(m, class_name)
    return c

With Python < 2.7:

def class_for_name(module_name, class_name):
    # load the module, will raise ImportError if module cannot be loaded
    m = __import__(module_name, globals(), locals(), class_name)
    # get the class, will raise AttributeError if class cannot be found
    c = getattr(m, class_name)
    return c

Use:

loaded_class = class_for_name('foo.bar', 'Baz')

SVN undo delete before commit

To make it into a one liner you can try something like:

svn status | cut -d ' ' -f 8 | xargs svn revert

How can I force gradle to redownload dependencies?

None of the solutions above worked for me.

If you use IntelliJ, what resolved it for me was simply refreshing all Gradle projects:

enter image description here

Android Studio: /dev/kvm device permission denied

I countered the same problem and to solve this issue just type the following commands in terminal for Linux clients

   sudo apt-get install qemu-kvm

    // type your password

   sudo chmod 777 -R /dev/kvm

and after that try running simulator it'll work

How can I add some small utility functions to my AngularJS application?

Here is a simple, compact and easy to understand method I use.
First, add a service in your js.

app.factory('Helpers', [ function() {
      // Helper service body

        var o = {
        Helpers: []

        };

        // Dummy function with parameter being passed
        o.getFooBar = function(para) {

            var valueIneed = para + " " + "World!";

            return valueIneed;

          };

        // Other helper functions can be added here ...

        // And we return the helper object ...
        return o;

    }]);

Then, in your controller, inject your helper object and use any available function with something like the following:

app.controller('MainCtrl', [

'$scope',
'Helpers',

function($scope, Helpers){

    $scope.sayIt = Helpers.getFooBar("Hello");
    console.log($scope.sayIt);

}]);

Setting button text via javascript

Set the text of the button by setting the innerHTML

var b = document.createElement('button');
b.setAttribute('content', 'test content');
b.setAttribute('class', 'btn');
b.innerHTML = 'test value';

var wrapper = document.getElementById('divWrapper');
wrapper.appendChild(b);

http://jsfiddle.net/jUVpE/

Difference between __getattr__ vs __getattribute__

I find that no one mentions this difference:

__getattribute__ has a default implementation, but __getattr__ does not.

class A:
    pass
a = A()
a.__getattr__ # error
a.__getattribute__ # return a method-wrapper

This has a clear meaning: since __getattribute__ has a default implementation, while __getattr__ not, clearly python encourages users to implement __getattr__.

Angular - "has no exported member 'Observable'"

You are using RxJS 6. Just replace

import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';

by

import { Observable, of } from 'rxjs';

scp files from local to remote machine error: no such file or directory

As @Astariul said, path to the file might cause this bug.
In addition, any parent directory which contains non-ASCII character, for example Chinese, will cause this.
In that case, you should rename you parent directory

PHP syntax question: What does the question mark and colon mean?

This is the PHP ternary operator (also known as a conditional operator) - if first operand evaluates true, evaluate as second operand, else evaluate as third operand.

Think of it as an "if" statement you can use in expressions. Can be very useful in making concise assignments that depend on some condition, e.g.

$param = isset($_GET['param']) ? $_GET['param'] : 'default';

There's also a shorthand version of this (in PHP 5.3 onwards). You can leave out the middle operand. The operator will evaluate as the first operand if it true, and the third operand otherwise. For example:

$result = $x ?: 'default';

It is worth mentioning that the above code when using i.e. $_GET or $_POST variable will throw undefined index notice and to prevent that we need to use a longer version, with isset or a null coalescing operator which is introduced in PHP7:

$param = $_GET['param'] ?? 'default';

Unable to run 'adb root' on a rooted Android phone

I finally found out how to do this! Basically you need to run adb shell first and then while you're in the shell run su, which will switch the shell to run as root!

$: adb shell
$: su

The one problem I still have is that sqlite3 is not installed so the command is not recognized.

How to sort in-place using the merge sort algorithm?

There is a relatively simple implementation of in-place merge sort using Kronrod's original technique but with simpler implementation. A pictorial example that illustrates this technique can be found here: http://www.logiccoder.com/TheSortProblem/BestMergeInfo.htm.

There are also links to more detailed theoretical analysis by the same author associated with this link.

Replacing instances of a character in a string

You can do the below, to replace any char with a respective char at a given index, if you wish not to use .replace()

word = 'python'
index = 4
char = 'i'

word = word[:index] + char + word[index + 1:]
print word

o/p: pythin

Adding minutes to date time in PHP

$minutes_to_add = 5;

$time = new DateTime('2011-11-17 05:05');
$time->add(new DateInterval('PT' . $minutes_to_add . 'M'));

$stamp = $time->format('Y-m-d H:i');

The ISO 8601 standard for duration is a string in the form of P{y}Y{m1}M{d}DT{h}H{m2}M{s}S where the {*} parts are replaced by a number value indicating how long the duration is.

For example, P1Y2DT5S means 1 year, 2 days, and 5 seconds.

In the example above, we are providing PT5M (or 5 minutes) to the DateInterval constructor.

C# generics syntax for multiple type parameter constraints

void foo<TOne, TTwo>() 
   where TOne : BaseOne
   where TTwo : BaseTwo

More info here:
http://msdn.microsoft.com/en-us/library/d5x73970.aspx

How to set upload_max_filesize in .htaccess?

What to do to correct this is create a file called php.ini and save it in the same location as your .htaccess file and enter the following code instead:

upload_max_filesize = "250M"
post_max_size = "250M"

What's an easy way to read random line from a file in Unix command line?

perlfaq5: How do I select a random line from a file? Here's a reservoir-sampling algorithm from the Camel Book:

perl -e 'srand; rand($.) < 1 && ($line = $_) while <>; print $line;' file

This has a significant advantage in space over reading the whole file in. You can find a proof of this method in The Art of Computer Programming, Volume 2, Section 3.4.2, by Donald E. Knuth.

How to stop/terminate a python script from running?

you can also use the Activity Monitor to stop the py process

How to load image (and other assets) in Angular an project?

I fixed it. My actual image file name had spaces in it, and for whatever reason Angular did not like that. When I removed the spaces from my file name, assets/images/myimage.png worked.

Validate that end date is greater than start date with jQuery

First you split the values of two input box by using split function. then concat the same in reverse order. after concat nation parse it to integer. then compare two values in in if statement. eg.1>20-11-2018 2>21-11-2018

after split and concat new values for comparison 20181120 and 20181121 the after that compare the same.

var date1 = $('#datevalue1').val();
var date2 = $('#datevalue2').val();
var d1 = date1.split("-");
var d2 = date2.split("-");

d1 = d1[2].concat(d1[1], d1[0]);
d2 = d2[2].concat(d2[1], d2[0]);

if (parseInt(d1) > parseInt(d2)) {

    $('#fromdatepicker').val('');
} else {

}

How do I change JPanel inside a JFrame on the fly?

I suggest you to add both panel at frame creation, then change the visible panel by calling setVisible(true/false) on both. When calling setVisible, the parent will be notified and asked to repaint itself.

Crystal Reports - Adding a parameter to a 'Command' query

Select Projecttname, ReleaseDate, TaskName From DB_Table Where Project_Name like '%{?Pm-?Proj_Name}%' and ReleaseDate >= currentdate

Note the single-quotes and wildcard characters. I just spent 30 minutes figuring out something similar.

IntelliJ shortcut to show a popup of methods in a class that can be searched

command+fn+F12 is correct. Lacking of button fn the F12 is used adjust the volume.

Using a remote repository with non-standard port

Try this

git clone ssh://[email protected]:11111/home/git/repo.git

Creating a blocking Queue<T> in .NET?

I haven't fully explored the TPL but they might have something that fits your needs, or at the very least, some Reflector fodder to snag some inspiration from.

Hope that helps.

What version of MongoDB is installed on Ubuntu

In the terminal just write : $ mongod --version

IE8 crashes when loading website - res://ieframe.dll/acr_error.htm

Try looking for Windows Error Reporting events in the affected machine's Event Viewer, specifically for iexplore.exe. That might give you a pointer for what component is getting loaded in IE that is causing the crash. Even more precise would be to launch IE under a debugger (e.g. windbg), repro the crash and then get a call stack. If you have a bad 3rd party add-on, it should be towards the top of the call stack. Though you said that it "isn't really an option" it will be important for you to identify a possible incompatibility and either reach out to the add-on developer, or workaround the issue on your side.

generate random double numbers in c++

Here's how

double fRand(double fMin, double fMax)
{
    double f = (double)rand() / RAND_MAX;
    return fMin + f * (fMax - fMin);
}

Remember to call srand() with a proper seed each time your program starts.

[Edit] This answer is obsolete since C++ got it's native non-C based random library (see Alessandro Jacopsons answer) But, this still applies to C

How to remove the first and the last character of a string

use .replace(/.*\/(\S+)\//img,"$1")

"/installers/services/".replace(/.*\/(\S+)\//img,"$1"); //--> services

"/services/".replace(/.*\/(\S+)\//img,"$1"); //--> services

Could not find or load main class org.gradle.wrapper.GradleWrapperMain

In my case, I left out wrapper sub folder while copying gradle folder and got the same error.

Could not find or load main class org.gradle.wrapper.GradleWrapperMain

make sure you have the correct folder structure if you copy wrapper from other location.

+-- build.gradle
+-- gradle
¦   +-- wrapper
¦       +-- gradle-wrapper.jar
¦       +-- gradle-wrapper.properties
+-- gradlew
+-- gradlew.bat
+-- settings.gradle

\n or \n in php echo not print

PHP only interprets escaped characters (with the exception of the escaped backslash \\ and the escaped single quote \') when in double quotes (")

This works (results in a newline):

"\n"

This does not result in a newline:

'\n'

How do I convert strings between uppercase and lowercase in Java?

There are methods in the String class; toUppercase() and toLowerCase().

i.e.

String input = "Cricket!";
String upper = input.toUpperCase(); //stores "CRICKET!"
String lower = input.toLowerCase(); //stores "cricket!" 

This will clarify your doubt

How to use PrintWriter and File classes in Java?

You should have a clear idea of exceptions in java. In java there are checked exceptions and unchecked exceptions.

Checked exceptions are checked (not thrown,just checked) by the compiler at Compile time for the smooth execution of the program at run time.

NOTE: And in our program if their is a chance that a checked exception will rise, then we should handle that checked exception either by try catch or by throws key word.Otherwise we will get a compile time Error:

CE:Unexpected Exception java.io.FileNotFoundException;must be caught or declared to be thrown.

How to resolve: 1.Put your code in try catch block:

2.use throws keyword as shown by other guys above.

Advice:Read more about Exceptions.(I personally love this topic)

How do I format date value as yyyy-mm-dd using SSIS expression builder?

Looks like you created a separate question. I was answering your other question How to change flat file source using foreach loop container in an SSIS package? with the same answer. Anyway, here it is again.

Create two string data type variables namely DirPath and FilePath. Set the value C:\backup\ to the variable DirPath. Do not set any value to the variable FilePath.

Variables

Select the variable FilePath and select F4 to view the properties. Set the EvaluateAsExpression property to True and set the Expression property as @[User::DirPath] + "Source" + (DT_STR, 4, 1252) DATEPART("yy" , GETDATE()) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)

Expression

Get top first record from duplicate records having no unique identity

Using DISTINCT should do it:

SELECT DISTINCT id, uname, tel
FROM YourTable

Though you could really do with having a primary key on that table, a way to uniquely identify each record. I'd be considering sticking an IDENTITY column on the table

sort csv by column

import operator
sortedlist = sorted(reader, key=operator.itemgetter(3), reverse=True)

or use lambda

sortedlist = sorted(reader, key=lambda row: row[3], reverse=True)

Failed to locate the winutils binary in the hadoop binary path

I just ran into this issue while working with Eclipse. In my case, I had the correct Hadoop version downloaded (hadoop-2.5.0-cdh5.3.0.tgz), I extracted the contents and placed it directly in my C drive. Then I went to

Eclipse->Debug/Run Configurations -> Environment (tab) -> and added

variable: HADOOP_HOME

Value: C:\hadoop-2.5.0-cdh5.3.0

Could not resolve placeholder in string value

I got same error in my Micro-service, whenever you declare @Value annotation in program i.e @Value("${project.api.key}")

make sure that your application.properties file with same values should not be blank project.api.key= add some values

MostIMP :otherwise it will throw error "Error creating bean with name 'ServiceFTP': Injection of autowired dependencies"

Cannot obtain value of local or argument as it is not available at this instruction pointer, possibly because it has been optimized away

I found that I had the same problem when I was running a project and debugging by attaching to an IIS process. I also was running in Debug mode with optimizations turned off. While I thought the code compiled fine, when I detached and tried to compile, one of the references was not found. This was due to another developer here that made modifications and changed the location of the reference. The reference did not show up with the alert symbol, so I thought everything was fine until I did the compilation. Once fixing the reference and running again it worked.

Sort a list of tuples by 2nd item (integer value)

From python wiki:

>>> from operator import itemgetter, attrgetter    
>>> sorted(student_tuples, key=itemgetter(2))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]    
>>> sorted(student_objects, key=attrgetter('age'))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

sql ORDER BY multiple values in specific order?

Try:

ORDER BY x_field='F', x_field='P', x_field='A', x_field='I'

You were on the right track, but by putting x_field only on the F value, the other 3 were treated as constants and not compared against anything in the dataset.

How do you add input from user into list in Python

shopList = [] 
maxLengthList = 6
while len(shopList) < maxLengthList:
    item = input("Enter your Item to the List: ")
    shopList.append(item)
    print shopList
print "That's your Shopping List"
print shopList

android - listview get item view by position

Preferred way to change the appearance/whatever of row views once the ListView is drawn is to change something in the data ListView draws from (the array of objects that is passed into your Adapter) and make sure to account for that in your getView() function, then redraw the ListView by calling

notifyDataSetChanged();

EDIT: while there is a way to do this, if you need to do this chances are doing something wrong. While are few edge cases I can think about, generally using notifyDataSetChanged() and other built in mechanisms is a way to go.

EDIT 2: One of the common mistakes people make is trying to come up with their own way to respond to user clicking/selecting a row in the ListView, as in one of the comments to this post. There is an existing way to do this. Here's how:

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    /* Parameters
    parent:     The AdapterView where the click happened.
    view:       The view within the AdapterView that was clicked (this will be a view provided by the adapter)
    position:   The position of the view in the adapter.
    id:         The row id of the item that was clicked. */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //your code here
    }
});

ListView has a lot of build-in functionality and there is no need to reinvent the wheel for simpler cases. Since ListView extends AdapterView, you can set the same Listeners, such as OnItemClickListener as in the example above.

fill an array in C#

public static void Fill<T>(this IList<T> col, T value, int fromIndex, int toIndex)
{
    if (fromIndex > toIndex)
        throw new ArgumentOutOfRangeException("fromIndex");

    for (var i = fromIndex; i <= toIndex; i++)
        col[i] = value;
}

Something that works for all IList<T>s.

How to create Python egg file

I think you should use python wheels for distribution instead of egg now.

Wheels are the new standard of python distribution and are intended to replace eggs. Support is offered in pip >= 1.4 and setuptools >= 0.8.

2D arrays in Python

x=list()
def enter(n):
    y=list()
    for i in  range(0,n):
        y.append(int(input("Enter ")))
    return y
for i in range(0,2):
    x.insert(i,enter(2))
print (x)

here i made function to create 1-D array and inserted into another array as a array member. multiple 1-d array inside a an array, as the value of n and i changes u create multi dimensional arrays

numpy division with RuntimeWarning: invalid value encountered in double_scalars

You can use np.logaddexp (which implements the idea in @gg349's answer):

In [33]: d = np.array([[1089, 1093]])

In [34]: e = np.array([[1000, 4443]])

In [35]: log_res = np.logaddexp(-3*d[0,0], -3*d[0,1]) - np.logaddexp(-3*e[0,0], -3*e[0,1])

In [36]: log_res
Out[36]: -266.99999385580668

In [37]: res = exp(log_res)

In [38]: res
Out[38]: 1.1050349147204485e-116

Or you can use scipy.special.logsumexp:

In [52]: from scipy.special import logsumexp

In [53]: res = np.exp(logsumexp(-3*d) - logsumexp(-3*e))

In [54]: res
Out[54]: 1.1050349147204485e-116

Simple two column html layout without using tables

Well, if you want the super easiest method, just put

<div class="left">left</div>
<div class="right">right</div>

.left {
    float: left;    
}

though you may need more than that depending on what other layout requirements you have.

Downloading an entire S3 bucket?

You can do this with https://github.com/minio/mc :

mc cp -r https://s3-us-west-2.amazonaws.com/bucketName/ localdir

mc also supports sessions, resumable downloads, uploads and many more. mc supports Linux, OS X and Windows operating systems. Written in Golang and released under Apache Version 2.0.

How can I exclude $(this) from a jQuery selector?

Try using the not() method instead of the :not() selector.

$(".content a").click(function() {
    $(".content a").not(this).hide("slow");
});

Tomcat starts but home page cannot open with url http://localhost:8080

Make sure no other application using port 8080 before starting tomcat. If that's not the problem please paste tomcat log.

If you want to change tomcat's default port, go to tomcat folder and open conf folder, in which you can see server.xml. In that file you can see something like <Connector port= . Change the port value and start tomcat.

How to find list intersection?

If you convert the larger of the two lists into a set, you can get the intersection of that set with any iterable using intersection():

a = [1,2,3,4,5]
b = [1,3,5,6]
set(a).intersection(b)

How to display .svg image using swift

To render SVG file you can use Macaw. Also Macaw supports transformations, user events, animation and various effects.

You can render SVG file with zero lines of code. For more info please check this article: Render SVG file with Macaw.

DISCLAIMER: I am affiliated with this project.

delete all from table

This is deletes the table table_name.

Replace it with the name of the table, which shall be deleted.

DELETE FROM table_name;

How to get the query string by javascript?

Very Straightforward!

function parseQueryString(){
    var assoc = {};
    var keyValues = location.search.slice(1).split('&');
    var decode = function(s){
        return decodeURIComponent(s.replace(/\+/g, ' '));
    };

    for (var i = 0; i < keyValues.length; ++i) {
        var key = keyValues[i].split('=');
        if (1 < key.length) {
            assoc[decode(key[0])] = decode(key[1]);
        }
    }

    return assoc;
}

numpy: most efficient frequency counts for unique values in an array

Even though it has already been answered, I suggest a different approach that makes use of numpy.histogram. Such function given a sequence it returns the frequency of its elements grouped in bins.

Beware though: it works in this example because numbers are integers. If they where real numbers, then this solution would not apply as nicely.

>>> from numpy import histogram
>>> y = histogram (x, bins=x.max()-1)
>>> y
(array([5, 3, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       1]),
 array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.,  11.,
        12.,  13.,  14.,  15.,  16.,  17.,  18.,  19.,  20.,  21.,  22.,
        23.,  24.,  25.]))

How to update a value in a json file and save it through node.js

For those looking to add an item to a json collection

function save(item, path = './collection.json'){
    if (!fs.existsSync(path)) {
        fs.writeFile(path, JSON.stringify([item]));
    } else {
        var data = fs.readFileSync(path, 'utf8');  
        var list = (data.length) ? JSON.parse(data): [];
        if (list instanceof Array) list.push(item)
        else list = [item]  
        fs.writeFileSync(path, JSON.stringify(list));
    }
}