Programs & Examples On #Tlistview

tlistview is a VCL control that displays items in various manner. It is defined in ComCtrls.pas unit.

Get div's offsetTop positions in React

A quicker way if you are using React 16.3 and above is by creating a ref in the constructor, then attaching it to the component you wish to use with as shown below.

...
constructor(props){
   ...
   //create a ref
   this.someRefName = React.createRef();

}

onScroll(){
let offsetTop = this.someRefName.current.offsetTop;

}

render(){
...
<Component ref={this.someRefName} />

}

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

it sometimes occurs when we use a custom adapter in any activity of fragment . and we return null object i.e null view so the activity gets confused which view to load , so that is why this exception occurs

shows the position where to change the view

Add Items to ListView - Android

ListView myListView = (ListView) rootView.findViewById(R.id.myListView);
ArrayList<String> myStringArray1 = new ArrayList<String>();
myStringArray1.add("something");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);

Try it like this

public OnClickListener moreListener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        adapter = null;
        myStringArray1.add("Andrea");
        adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
        myListView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }       
};

Refresh or force redraw the fragment

let us see the below source code. Here fragment name is DirectoryOfEbooks. After completion of the background task, i am the replacing the frame with current fragment. so the fragment gets refreshed and reloads its data

    import android.app.ProgressDialog;
    import android.content.DialogInterface;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentTransaction;
    import android.support.v4.view.MenuItemCompat;
    import android.support.v7.app.AlertDialog;
    import android.support.v7.widget.DefaultItemAnimator;
    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.TextView;
    import android.widget.Toast;

    import com.github.mikephil.charting.data.LineRadarDataSet;

    import java.util.ArrayList;
    import java.util.List;


    /**
     * A simple {@link Fragment} subclass.
     */
    public class DirectoryOfEbooks extends Fragment {

        RecyclerView recyclerView;
        branchesAdapter adapter;
        LinearLayoutManager linearLayoutManager;
        Cursor c;
        FragmentTransaction fragmentTransaction;
        SQLiteDatabase db;
        List<branch_sync> directoryarraylist;

        public DirectoryOfEbooks() {
            // Required empty public constructor
        }
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {


            View view = inflater.inflate(R.layout.fragment_directory_of_ebooks, container, false);
            directoryarraylist = new ArrayList<>();
            db = getActivity().openOrCreateDatabase("notify", android.content.Context.MODE_PRIVATE, null);
            c = db.rawQuery("select * FROM branch; ", null);

            if (c.getCount() != 0) {
                c.moveToFirst();
                while (true) {
                    //String ISBN = c.getString(c.getColumnIndex("ISBN"));
                    String branch = c.getString(c.getColumnIndex("branch"));

                    branch_sync branchSync = new branch_sync(branch);
                    directoryarraylist.add(branchSync);
                    if (c.isLast())
                        break;
                    else
                        c.moveToNext();
                }

                recyclerView = (RecyclerView) view.findViewById(R.id.directoryOfEbooks);
                adapter = new branchesAdapter(directoryarraylist, this.getContext());
                adapter.setHasStableIds(true);
                recyclerView.setItemAnimator(new DefaultItemAnimator());
                System.out.println("ebooks");
                recyclerView.setHasFixedSize(true);
                linearLayoutManager = new LinearLayoutManager(this.getContext());
                recyclerView.setLayoutManager(linearLayoutManager);
                recyclerView.setAdapter(adapter);
                System.out.println(adapter.getItemCount()+"adpater count");

            }
            // Inflate the layout for this fragment
            return view;
        }
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //setContentView(R.layout.fragment_books);
            setHasOptionsMenu(true);
        }
        public void onPrepareOptionsMenu(Menu menu) {
            MenuInflater inflater = getActivity().getMenuInflater();
            inflater.inflate(R.menu.refresh, menu);
            MenuItem menuItem = menu.findItem(R.id.refresh1);
            menuItem.setVisible(true);
        }
        public boolean onOptionsItemSelected(MenuItem item) {
            if (item.getItemId() == R.id.refresh1) {
                new AlertDialog.Builder(getContext()).setMessage("Refresh takes more than a Minute").setPositiveButton("Refresh Now", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {

                        new refreshebooks().execute();
                    }
                }).setNegativeButton("Refresh Later", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).setCancelable(false).show();

            }
            return super.onOptionsItemSelected(item);
        }

    public class refreshebooks extends AsyncTask<String,String,String>{
        ProgressDialog progressDialog;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
          progressDialog=new ProgressDialog(getContext());
            progressDialog.setMessage("\tRefreshing Ebooks .....");
            progressDialog.setCancelable(false);
            progressDialog.show();
        }

        @Override
        protected String doInBackground(String... params) {
            Ebooksync syncEbooks=new Ebooksync();
            String status=syncEbooks.syncdata(getContext());
            return status;

        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if(s.equals("error")){
                progressDialog.dismiss();
                Toast.makeText(getContext(),"Refresh Failed",Toast.LENGTH_SHORT).show();
            }
            else{
                fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
                fragmentTransaction.replace(R.id.mainframe, new DirectoryOfEbooks());
                fragmentTransaction.commit();
                progressDialog.dismiss();
                adapter.notifyDataSetChanged();
                Toast.makeText(getContext(),"Refresh Successfull",Toast.LENGTH_SHORT).show();
            }

        }
    }

    }

how to show progress bar(circle) in an activity having a listview before loading the listview with data

ProgressDialog dialog = ProgressDialog.show(Example.this, "", "Loading...", true);

Creating columns in listView and add items

I didn't see anyone answer this correctly. So I'm posting it here. In order to get columns to show up you need to specify the following line.

lvRegAnimals.View = View.Details;

And then add your columns after that.

lvRegAnimals.Columns.Add("Id", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Name", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Age", -2, HorizontalAlignment.Left);

Hope this helps anyone else looking for this answer in the future.

Show ProgressDialog Android

Declare your progress dialog:

ProgressDialog progress;

When you're ready to start the progress dialog:

progress = ProgressDialog.show(this, "dialog title",
    "dialog message", true);

and to make it go away when you're done:

progress.dismiss();

Here's a little thread example for you:

// Note: declare ProgressDialog progress as a field in your class.

progress = ProgressDialog.show(this, "dialog title",
  "dialog message", true);

new Thread(new Runnable() {
  @Override
  public void run()
  {
    // do the thing that takes a long time

    runOnUiThread(new Runnable() {
      @Override
      public void run()
      {
        progress.dismiss();
      }
    });
  }
}).start();

Adding an onclicklistener to listview (android)

Try this:

    list.setOnItemSelectedListener(new OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1,
            int arg2, long arg3)
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {

    }
});

Using ListView : How to add a header view?

You can add as many headers as you like by calling addHeaderView() multiple times. You have to do it before setting the adapter to the list view.

And yes you can add header something like this way:

LayoutInflater inflater = getLayoutInflater();
ViewGroup header = (ViewGroup)inflater.inflate(R.layout.header, myListView, false);
myListView.addHeaderView(header, null, false);

ListView with OnItemClickListener

If you define your ListView programatically:

mListView.setDescendantFocusability(ListView.FOCUS_BLOCK_DESCENDANTS);

How to change color and font on ListView

If you want to use a color from colors.xml , experiment :

   public View getView(int position, View convertView, ViewGroup parent) {
        ... 
        View rowView = inflater.inflate(this.rowLayoutID, parent, false);
        rowView.setBackgroundColor(rowView.getResources().getColor(R.color.my_bg_color));
        TextView title = (TextView) rowView.findViewById(R.id.txtRowTitle);
        title.setTextColor(
            rowView.getResources().getColor(R.color.my_title_color));
        ...
     }

You can use too:

private static final int bgColor = 0xAAAAFFFF;
public View getView(int position, View convertView, ViewGroup parent) {
        ... 
        View rowView = inflater.inflate(this.rowLayoutID, parent, false);
            rowView.setBackgroundColor(bgColor);
...
}

Android app unable to start activity componentinfo

Your null pointer exception seems to be on this line:

String url = intent.getExtras().getString("userurl");

because intent.getExtras() returns null when the intent doesn't have any extras.

You have to realize that this piece of code:

Intent Main = new Intent(this, ToClass.class);
Main.putExtra("userurl", url);
startActivity(Main);

doesn't start the activity you wrote in Main.java, it will attempt to start an activity called ToClass and if that doesn't exist, your app crashes.

Also, there is no such thing as "android.intent.action.start" so the manifest should look more like:

<activity android:name=".start" android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
<activity android:name= ".Main">
</activity>

I hope this fixes some of the issues you are encountering but I strongly suggest you check out some "getting started" tutorials for android development and build up from there.

How to scroll to top of long ScrollView layout?

I faced Same Problem When i am using Scrollview inside View Flipper or Dialog that case scrollViewObject.fullScroll(ScrollView.FOCUS_UP) returns false so that case scrollViewObject.smoothScrollTo(0, 0) is Worked for me

Scroll Focus Top

How to Animate Addition or Removal of Android ListView Rows

Since Android is open source, you don't actually need to reimplement ListView's optimizations. You can grab ListView's code and try to find a way to hack in the animation, you can also open a feature request in android bug tracker (and if you decided to implement it, don't forget to contribute a patch).

FYI, the ListView source code is here.

Add new row to dataframe, at specific row-index, not appended?

Here's a solution that avoids the (often slow) rbind call:

existingDF <- as.data.frame(matrix(seq(20),nrow=5,ncol=4))
r <- 3
newrow <- seq(4)
insertRow <- function(existingDF, newrow, r) {
  existingDF[seq(r+1,nrow(existingDF)+1),] <- existingDF[seq(r,nrow(existingDF)),]
  existingDF[r,] <- newrow
  existingDF
}

> insertRow(existingDF, newrow, r)
  V1 V2 V3 V4
1  1  6 11 16
2  2  7 12 17
3  1  2  3  4
4  3  8 13 18
5  4  9 14 19
6  5 10 15 20

If speed is less important than clarity, then @Simon's solution works well:

existingDF <- rbind(existingDF[1:r,],newrow,existingDF[-(1:r),])
> existingDF
   V1 V2 V3 V4
1   1  6 11 16
2   2  7 12 17
3   3  8 13 18
4   1  2  3  4
41  4  9 14 19
5   5 10 15 20

(Note we index r differently).

And finally, benchmarks:

library(microbenchmark)
microbenchmark(
  rbind(existingDF[1:r,],newrow,existingDF[-(1:r),]),
  insertRow(existingDF,newrow,r)
)

Unit: microseconds
                                                    expr     min       lq   median       uq       max
1                       insertRow(existingDF, newrow, r) 660.131 678.3675 695.5515 725.2775   928.299
2 rbind(existingDF[1:r, ], newrow, existingDF[-(1:r), ]) 801.161 831.7730 854.6320 881.6560 10641.417

Benchmarks

As @MatthewDowle always points out to me, benchmarks need to be examined for the scaling as the size of the problem increases. Here we go then:

benchmarkInsertionSolutions <- function(nrow=5,ncol=4) {
  existingDF <- as.data.frame(matrix(seq(nrow*ncol),nrow=nrow,ncol=ncol))
  r <- 3 # Row to insert into
  newrow <- seq(ncol)
  m <- microbenchmark(
   rbind(existingDF[1:r,],newrow,existingDF[-(1:r),]),
   insertRow(existingDF,newrow,r),
   insertRow2(existingDF,newrow,r)
  )
  # Now return the median times
  mediansBy <- by(m$time,m$expr, FUN=median)
  res <- as.numeric(mediansBy)
  names(res) <- names(mediansBy)
  res
}
nrows <- 5*10^(0:5)
benchmarks <- sapply(nrows,benchmarkInsertionSolutions)
colnames(benchmarks) <- as.character(nrows)
ggplot( melt(benchmarks), aes(x=Var2,y=value,colour=Var1) ) + geom_line() + scale_x_log10() + scale_y_log10()

@Roland's solution scales quite well, even with the call to rbind:

                                                              5       50     500    5000    50000     5e+05
insertRow2(existingDF, newrow, r)                      549861.5 579579.0  789452 2512926 46994560 414790214
insertRow(existingDF, newrow, r)                       895401.0 905318.5 1168201 2603926 39765358 392904851
rbind(existingDF[1:r, ], newrow, existingDF[-(1:r), ]) 787218.0 814979.0 1263886 5591880 63351247 829650894

Plotted on a linear scale:

linear

And a log-log scale:

log-log

history.replaceState() example?

history.pushState pushes the current page state onto the history stack, and changes the URL in the address bar. So, when you go back, that state (the object you passed) are returned to you.

Currently, that is all it does. Any other page action, such as displaying the new page or changing the page title, must be done by you.

The W3C spec you link is just a draft, and browser may implement it differently. Firefox, for example, ignores the title parameter completely.

Here is a simple example of pushState that I use on my website.

(function($){
    // Use AJAX to load the page, and change the title
    function loadPage(sel, p){
        $(sel).load(p + ' #content', function(){
            document.title = $('#pageData').data('title');
        });
    }

    // When a link is clicked, use AJAX to load that page
    // but use pushState to change the URL bar
    $(document).on('click', 'a', function(e){
        e.preventDefault();
        history.pushState({page: this.href}, '', this.href);
        loadPage('#frontPage', this.href);
    });

    // This event is triggered when you visit a page in the history
    // like when yu push the "back" button
    $(window).on('popstate', function(e){
        loadPage('#frontPage', location.pathname);
        console.log(e.originalEvent.state);
    });
}(jQuery));

/usr/bin/codesign failed with exit code 1

I had the same problem but also listed in the error log was this: CSSMERR_TP_CERT_NOT_VALID_YET

Looking at the certificate in KeyChain showed a similar message. The problem was due to my Mac's system clock being set incorrectly. As soon as I set the correct region/time, the certificate was marked as valid and I could build and run my app on the iPhone

How to print matched regex pattern using awk?

Using sed can also be elegant in this situation. Example (replace line with matched group "yyy" from line):

$ cat testfile
xxx yyy zzz
yyy xxx zzz
$ cat testfile | sed -r 's#^.*(yyy).*$#\1#g'
yyy
yyy

Relevant manual page: https://www.gnu.org/software/sed/manual/sed.html#Back_002dreferences-and-Subexpressions

Filling a List with all enum values in Java

There is a constructor for ArrayList which is

ArrayList(Collection<? extends E> c) 

Now, EnumSet extends AbstractCollection so you can just do

ArrayList<Something> all = new ArrayList<Something>(enumSet)

PYTHONPATH vs. sys.path

I hate PYTHONPATH. I find it brittle and annoying to set on a per-user basis (especially for daemon users) and keep track of as project folders move around. I would much rather set sys.path in the invoke scripts for standalone projects.

However sys.path.append isn't the way to do it. You can easily get duplicates, and it doesn't sort out .pth files. Better (and more readable): site.addsitedir.

And script.py wouldn't normally be the more appropriate place to do it, as it's inside the package you want to make available on the path. Library modules should certainly not be touching sys.path themselves. Instead, you'd normally have a hashbanged-script outside the package that you use to instantiate and run the app, and it's in this trivial wrapper script you'd put deployment details like sys.path-frobbing.

What is a "thread" (really)?

Let me explain the difference between process and threads first.

A process can have {1..N} number of threads. A small explanation on virtual memory and virtual processor.

Virtual memory

Used as a swap space so that a process thinks that it is sitting on the primary memory for execution.

Virtual processor

The same concept as virtual memory except this is for processor. To a process, it will look it's the only thing that is using the processor.

OS will take care of allocating the virtual memory and virtual processor to a process and performing the swap between processes and doing execution.

All the threads within a process will share the same virtual memory. But, each thread will have their individual virtual processor assigned to them so that they can be executed individually.

Thus saving the memory as well as utilizing the CPU to its potential.

wait until all threads finish their work in java

You do

for (Thread t : new Thread[] { th1, th2, th3, th4, th5 })
    t.join()

After this for loop, you can be sure all threads have finished their jobs.

Can I update a JSF component from a JSF backing bean method?

Using standard JSF API, add the client ID to PartialViewContext#getRenderIds().

FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds().add("foo:bar");

Using PrimeFaces specific API, use PrimeFaces.Ajax#update().

PrimeFaces.current().ajax().update("foo:bar");

Or if you're not on PrimeFaces 6.2+ yet, use RequestContext#update().

RequestContext.getCurrentInstance().update("foo:bar");

If you happen to use JSF utility library OmniFaces, use Ajax#update().

Ajax.update("foo:bar");

Regardless of the way, note that those client IDs should represent absolute client IDs which are not prefixed with the NamingContainer separator character like as you would do from the view side on.

No 'Access-Control-Allow-Origin' header is present on the requested resource- AngularJS

Replace get with jsonp:

 $http.jsonp('http://mywebservice').success(function ( data ) {
    alert(data);
    });
}

error C2220: warning treated as error - no 'object' file generated

This error message is very confusing. I just fixed the other 'warnings' in my project and I really had only one (simple one):

warning C4101: 'i': unreferenced local variable

After I commented this unused i, and compiled it, the other error went away.

Get safe area inset top and bottom heights

Swift 5, Xcode 11.4

`UIApplication.shared.keyWindow` 

It will give deprecation warning. ''keyWindow' was deprecated in iOS 13.0: Should not be used for applications that support multiple scenes as it returns a key window across all connected scenes' because of connected scenes. I use this way.

extension UIView {

    var safeAreaBottom: CGFloat {
         if #available(iOS 11, *) {
            if let window = UIApplication.shared.keyWindowInConnectedScenes {
                return window.safeAreaInsets.bottom
            }
         }
         return 0
    }

    var safeAreaTop: CGFloat {
         if #available(iOS 11, *) {
            if let window = UIApplication.shared.keyWindowInConnectedScenes {
                return window.safeAreaInsets.top
            }
         }
         return 0
    }
}

extension UIApplication {
    var keyWindowInConnectedScenes: UIWindow? {
        return windows.first(where: { $0.isKeyWindow })
    }
}

Array initializing in Scala

scala> val arr = Array("Hello","World")
arr: Array[java.lang.String] = Array(Hello, World)

powershell 2.0 try catch how to access the exception

Try something like this:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    Write-Host $_.Exception.ToString()
}

The exception is in the $_ variable. You might explore $_ like this:

try {
    $w = New-Object net.WebClient
    $d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
    $_ | fl * -Force
}

I think it will give you all the info you need.

My rule: if there is some data that is not displayed, try to use -force.

What is the best way to get all the divisors of a number?

I like Greg solution, but I wish it was more python like. I feel it would be faster and more readable; so after some time of coding I came out with this.

The first two functions are needed to make the cartesian product of lists. And can be reused whnever this problem arises. By the way, I had to program this myself, if anyone knows of a standard solution for this problem, please feel free to contact me.

"Factorgenerator" now returns a dictionary. And then the dictionary is fed into "divisors", who uses it to generate first a list of lists, where each list is the list of the factors of the form p^n with p prime. Then we make the cartesian product of those lists, and we finally use Greg' solution to generate the divisor. We sort them, and return them.

I tested it and it seem to be a bit faster than the previous version. I tested it as part of a bigger program, so I can't really say how much is it faster though.

Pietro Speroni (pietrosperoni dot it)

from math import sqrt


##############################################################
### cartesian product of lists ##################################
##############################################################

def appendEs2Sequences(sequences,es):
    result=[]
    if not sequences:
        for e in es:
            result.append([e])
    else:
        for e in es:
            result+=[seq+[e] for seq in sequences]
    return result


def cartesianproduct(lists):
    """
    given a list of lists,
    returns all the possible combinations taking one element from each list
    The list does not have to be of equal length
    """
    return reduce(appendEs2Sequences,lists,[])

##############################################################
### prime factors of a natural ##################################
##############################################################

def primefactors(n):
    '''lists prime factors, from greatest to smallest'''  
    i = 2
    while i<=sqrt(n):
        if n%i==0:
            l = primefactors(n/i)
            l.append(i)
            return l
        i+=1
    return [n]      # n is prime


##############################################################
### factorization of a natural ##################################
##############################################################

def factorGenerator(n):
    p = primefactors(n)
    factors={}
    for p1 in p:
        try:
            factors[p1]+=1
        except KeyError:
            factors[p1]=1
    return factors

def divisors(n):
    factors = factorGenerator(n)
    divisors=[]
    listexponents=[map(lambda x:k**x,range(0,factors[k]+1)) for k in factors.keys()]
    listfactors=cartesianproduct(listexponents)
    for f in listfactors:
        divisors.append(reduce(lambda x, y: x*y, f, 1))
    divisors.sort()
    return divisors



print divisors(60668796879)

P.S. it is the first time I am posting to stackoverflow. I am looking forward for any feedback.

System.BadImageFormatException An attempt was made to load a program with an incorrect format

I was having problems with a new install of VS with an x64 project - for Visual Studio 2013, Visual Studio 2015 and Visual Studio 2017:

Tools
  -> Options
   -> Projects and Solutions
    -> Web Projects
     -> Check "Use the 64 bit version of IIS Express for web sites and projects"

Is there a difference between "throw" and "throw ex"?

Yes, there is a difference;

  • throw ex resets the stack trace (so your errors would appear to originate from HandleException)
  • throw doesn't - the original offender would be preserved.

    static void Main(string[] args)
    {
        try
        {
            Method2();
        }
        catch (Exception ex)
        {
            Console.Write(ex.StackTrace.ToString());
            Console.ReadKey();
        }
    }
    
    private static void Method2()
    {
        try
        {
            Method1();
        }
        catch (Exception ex)
        {
            //throw ex resets the stack trace Coming from Method 1 and propogates it to the caller(Main)
            throw ex;
        }
    }
    
    private static void Method1()
    {
        try
        {
            throw new Exception("Inside Method1");
        }
        catch (Exception)
        {
            throw;
        }
    }
    

How to enable NSZombie in Xcode?

To enable Zombie logging double-click the executable in the executables group of your Xcode project. At this point click the Arguments tab and in the Variables to be set in the environment: section, make a variable called NSZombieEnabled and set its value to YES.

Alternative to file_get_contents?

If you're trying to read XML generated from a URL without file_get_contents() then you'll probably want to have a look at cURL

Gradle sync failed: failed to find Build Tools revision 24.0.0 rc1

SDK tools required build tool version installation helped me. You just need to install required build tool version from,

SDK Manager -> SDK tool -> Show Package details -> Select required build tool version and install it.

Parcelable encountered IOException writing serializable object getactivity()

I faced Same issue, the issues was there are some inner classes with the static keyword.After removing the static keyword it started working and also the inner class should implements to Serializable

Issue scenario

class A implements Serializable{ 
  class static B{
  } 
}

Resolved By

class A implements Serializable{ 
      class B implements Serializable{
      } 
    }

How to use an arraylist as a prepared statement parameter

why making life hard-

PreparedStatement pstmt = conn.prepareStatement("select * from employee where id in ("+ StringUtils.join(arraylistParameter.iterator(),",") +)");

CSS "color" vs. "font-color"

The same way Boston came up with its street plan. They followed the cow paths already there, and built houses where the streets weren't, and after a while it was too much trouble to change.

Turn off iPhone/Safari input element rounding

On iOS 5 and later:

input {
  border-radius: 0;
}

input[type="search"] {
  -webkit-appearance: none;
}

If you must only remove the rounded corners on iOS or otherwise for some reason cannot normalize rounded corners across platforms, use input { -webkit-border-radius: 0; } property instead, which is still supported. Of course do note that Apple can choose to drop support for the prefixed property at any time, but considering their other platform-specific CSS features chances are they'll keep it around.

On legacy versions you had to set -webkit-appearance: none instead:

input {
    -webkit-appearance: none;
}

Consider defining a bean of type 'package' in your configuration [Spring-Boot]

reminder that spring doesn't scan the world , it uses targeted scanning wich means everything under the package where springbootapplication is stored. therefore this error "Consider defining a bean of type 'package' in your configuration [Spring-Boot]" may appear because you have services interfaces in a different springbootapplication package .

Gather multiple sets of columns

With the recent update to melt.data.table, we can now melt multiple columns. With that, we can do:

require(data.table) ## 1.9.5
melt(setDT(df), id=1:2, measure=patterns("^Q3.2", "^Q3.3"), 
     value.name=c("Q3.2", "Q3.3"), variable.name="loop_number")
 #    id       time loop_number         Q3.2        Q3.3
 # 1:  1 2009-01-01           1 -0.433978480  0.41227209
 # 2:  2 2009-01-02           1 -0.567995351  0.30701144
 # 3:  3 2009-01-03           1 -0.092041353 -0.96024077
 # 4:  4 2009-01-04           1  1.137433487  0.60603396
 # 5:  5 2009-01-05           1 -1.071498263 -0.01655584
 # 6:  6 2009-01-06           1 -0.048376809  0.55889996
 # 7:  7 2009-01-07           1 -0.007312176  0.69872938

You can get the development version from here.

Printing with sed or awk a line following a matching pattern

Piping some greps can do it (it runs in POSIX shell and under BusyBox):

cat my-file | grep -A1 my-regexp | grep -v -- '--' | grep -v my-regexp
  1. -v will show non-matching lines
  2. -- is printed by grep to separate each match, so we skip that too

How to solve : SQL Error: ORA-00604: error occurred at recursive SQL level 1

I was able to solve "ORA-00604: error" by Droping with purge.

DROP TABLE tablename PURGE

Difference between try-catch and throw in java

Others have already given thorough answers, but if you're looking for even more information, the Oracle Java tutorials are always a good resource. Here's the Java tutorial for Exceptions, which covers all of your questions in great detail; https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

I was facing this issue in ionic and tried many solutions but solved this by running this.

For MAC: node --max-old-space-size=4096 /usr/local/bin/ionic cordova build android --prod

For Windows: node --max-old-space-size=4096 /Users/{your user}/AppData/Roaming/npm/node_modules/ionic/bin/ionic cordova build windows --prod

How can I close a login form and show the main form without my application closing?

you should do it the other way round:

Load the mainform first and in its onload event show your loginform with showdialog() which will prevent mainform from showing until you have a result from the loginform

EDIT: As this is a login form and if you do not need any variables from your mainform (which is bad design in practice), you should really implement it in your program.cs as Davide and Cody suggested.

Difference between == and ===

In both Objective-C and Swift, the == and != operators test for value equality for number values (e.g., NSInteger, NSUInteger, int, in Objective-C and Int, UInt, etc. in Swift). For objects (NSObject/NSNumber and subclasses in Objective-C and reference types in Swift), == and != test that the objects/reference types are the same identical thing -- i.e., same hash value -- or are not the same identical thing, respectively.

let a = NSObject()
let b = NSObject()
let c = a
a == b // false
a == c // true

Swift's identity equality operators, === and !==, check referential equality -- and thus, should probably be called the referential equality operators IMO.

a === b // false
a === c // true

It's also worth pointing out that custom reference types in Swift (that do not subclass a class that conforms to Equatable) do not automatically implement the equal to operators, but the identity equality operators still apply. Also, by implementing ==, != is automatically implemented.

class MyClass: Equatable {
  let myProperty: String

  init(s: String) {
    myProperty = s
  }
}

func ==(lhs: MyClass, rhs: MyClass) -> Bool {
  return lhs.myProperty == rhs.myProperty
}

let myClass1 = MyClass(s: "Hello")
let myClass2 = MyClass(s: "Hello")
myClass1 == myClass2 // true
myClass1 != myClass2 // false
myClass1 === myClass2 // false
myClass1 !== myClass2 // true

These equality operators are not implemented for other types such as structures in either language. However, custom operators can be created in Swift, which would, for example, enable you to create an operator to check equality of a CGPoint.

infix operator <==> { precedence 130 }
func <==> (lhs: CGPoint, rhs: CGPoint) -> Bool {
  return lhs.x == rhs.x && lhs.y == rhs.y
}

let point1 = CGPoint(x: 1.0, y: 1.0)
let point2 = CGPoint(x: 1.0, y: 1.0)
point1 <==> point2 // true

SQL Server: How to check if CLR is enabled?

select *
from sys.configurations
where name = 'clr enabled'

Get Country of IP Address with PHP

Install and use PHP's GeoIP extension if you can. On debian lenny:

sudo wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
sudo gunzip GeoLiteCity.dat.gz
sudo mkdir -v /usr/share/GeoIP
sudo mv -v GeoLiteCity.dat /usr/share/GeoIP/GeoIPCity.dat

sudo apt-get install php5-geoip
# or sudo apt-get install php-geoip for PHP7

and then try it in PHP:

$ip = $_SERVER['REMOTE_ADDR'];
$country = geoip_country_name_by_name($ip);
echo 'The current user is located in: ' . $country;

returns:

The current user is located in: Cameroon

Listing available com ports with Python

one line solution with pySerial package.

python -m serial.tools.list_ports

How do I find out what version of WordPress is running?

Open the blog, Check source once the blog is open. It should have a meta tag like:

<meta name="generator" content="WordPress 2.8.4" />

How to: Create trigger for auto update modified date with SQL Server 2008

My approach:

  • define a default constraint on the ModDate column with a value of GETDATE() - this handles the INSERT case

  • have a AFTER UPDATE trigger to update the ModDate column

Something like:

CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
    UPDATE dbo.TimeEntry
    SET ModDate = GETDATE()
    WHERE ID IN (SELECT DISTINCT ID FROM Inserted)

Use latest version of Internet Explorer in the webbrowser control

var appName = System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe";

using (var Key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true))
    Key.SetValue(appName, 99999, RegistryValueKind.DWord);

According to what I read here (Controlling WebBrowser Control Compatibility:

What Happens if I Set the FEATURE_BROWSER_EMULATION Document Mode Value Higher than the IE Version on the Client?

Obviously, the browser control can only support a document mode that is less than or equal to the IE version installed on the client. Using the FEATURE_BROWSER_EMULATION key works best for enterprise line of business apps where there is a deployed and support version of the browser. In the case you set the value to a browser mode that is a higher version than the browser version installed on the client, the browser control will choose the highest document mode available.

The simplest thing is to put a very high decimal number ...

Difference between const reference and normal parameter

Firstly, there is no concept of cv-qualified references. So the terminology 'const reference' is not correct and is usually used to describle 'reference to const'. It is better to start talking about what is meant.

$8.3.2/1- "Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef (7.1.3) or of a template type argument (14.3), in which case the cv-qualifiers are ignored."

Here are the differences

$13.1 - "Only the const and volatile type-specifiers at the outermost level of the parameter type specification are ignored in this fashion; const and volatile type-specifiers buried within a parameter type specification are significant and can be used to distinguish overloaded function declarations.112). In particular, for any type T, “pointer to T,” “pointer to const T,” and “pointer to volatile T” are considered distinct parameter types, as are “reference to T,” “reference to const T,” and “reference to volatile T.”

void f(int &n){
   cout << 1; 
   n++;
}

void f(int const &n){
   cout << 2;
   //n++; // Error!, Non modifiable lvalue
}

int main(){
   int x = 2;

   f(x);        // Calls overload 1, after the call x is 3
   f(2);        // Calls overload 2
   f(2.2);      // Calls overload 2, a temporary of double is created $8.5/3
}

Remove accents/diacritics in a string in JavaScript

In NPM there is a package for this: latinize

It's a very good package to solve this issue.

Substitute a comma with a line break in a cell

Windows (unlike some other OS's, like Linux), uses CR+LF for line breaks:

  • CR = 13 = 0x0D = ^M = \r = carriage return

  • LF = 10 = 0x0A = ^J = \n = new line

The characters need to be in that order, if you want the line breaks to be consistently visible when copied to other Windows programs. So the Excel function would be:

=SUBSTITUTE(A1,",",CHAR(13) & CHAR(10))

python-dev installation error: ImportError: No module named apt_pkg

This worked for me on after updating python3.7 on ubuntu18.04

cd /usr/lib/python3/dist-packages
sudo cp apt_pkg.cpython-36m-x86_64-linux-gnu.so apt_pkg.so

How do I convert a Swift Array to a String?

Try This:

let categories = dictData?.value(forKeyPath: "listing_subcategories_id") as! NSMutableArray
                        let tempArray = NSMutableArray()
                        for dc in categories
                        {
                            let dictD = dc as? NSMutableDictionary
                            tempArray.add(dictD?.object(forKey: "subcategories_name") as! String)
                        }
                        let joinedString = tempArray.componentsJoined(by: ",")

Java file path in Linux

I think Todd is correct, but I think there's one other thing you should consider. You can reliably get the home directory from the JVM at runtime, and then you can create files objects relative to that location. It's not that much more trouble, and it's something you'll appreciate if you ever move to another computer or operating system.

File homedir = new File(System.getProperty("user.home"));
File fileToRead = new File(homedir, "java/ex.txt");

ASP.NET MVC How to pass JSON object from View to Controller as Parameter

This answer is a follow up to DaRKoN_'s answer that utilized the object filter:

[ObjectFilter(Param = "postdata", RootType = typeof(ObjectToSerializeTo))]
    public JsonResult ControllerMethod(ObjectToSerializeTo postdata) { ... }

I was having a problem figuring out how to send multiple parameters to an action method and have one of them be the json object and the other be a plain string. I'm new to MVC and I had just forgotten that I already solved this problem with non-ajaxed views.

What I would do if I needed, say, two different objects on a view. I would create a ViewModel class. So say I needed the person object and the address object, I would do the following:

public class SomeViewModel()
{
     public Person Person { get; set; }
     public Address Address { get; set; }
}

Then I would bind the view to SomeViewModel. You can do the same thing with JSON.

[ObjectFilter(Param = "jsonViewModel", RootType = typeof(JsonViewModel))] // Don't forget to add the object filter class in DaRKoN_'s answer.
public JsonResult doJsonStuff(JsonViewModel jsonViewModel)
{
     Person p = jsonViewModel.Person;
     Address a = jsonViewModel.Address;
     // Do stuff
     jsonViewModel.Person = p;
     jsonViewModel.Address = a;
     return Json(jsonViewModel);
}

Then in the view you can use a simple call with JQuery like this:

var json = { 
    Person: { Name: "John Doe", Sex: "Male", Age: 23 }, 
    Address: { Street: "123 fk st.", City: "Redmond", State: "Washington" }
};

$.ajax({
     url: 'home/doJsonStuff',
     type: 'POST',
     contentType: 'application/json',
     dataType: 'json',
     data: JSON.stringify(json), //You'll need to reference json2.js
     success: function (response)
     {
          var person = response.Person;
          var address = response.Address;
     }
});

How to use `replace` of directive definition?

As the documentation states, 'replace' determines whether the current element is replaced by the directive. The other option is whether it is just added to as a child basically. If you look at the source of your plnkr, notice that for the second directive where replace is false that the div tag is still there. For the first directive it is not.

First result:

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

Second result:

<div myd2=""><span>directive template2</span></div>

Soft hyphen in HTML (<wbr> vs. &shy;)

Sometimes web browsers seems to be more forgiving if you use the Unicode string &#173; rather than the &shy; entity.

A better way to check if a path exists or not in PowerShell

To check if a Path exists to a directory, use this one:

$pathToDirectory = "c:\program files\blahblah\"
if (![System.IO.Directory]::Exists($pathToDirectory))
{
 mkdir $path1
}

To check if a Path to a file exists use what @Mathias suggested:

[System.IO.File]::Exists($pathToAFile)

plot is not defined

If you want to use a function form a package or module in python you have to import and reference them. For example normally you do the following to draw 5 points( [1,5],[2,4],[3,3],[4,2],[5,1]) in the space:

import matplotlib.pyplot
matplotlib.pyplot.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
matplotlib.pyplot.show()

In your solution

from matplotlib import*

This imports the package matplotlib and "plot is not defined" means there is no plot function in matplotlib you can access directly, but instead if you import as

from matplotlib.pyplot import *
plot([1,2,3,4,5],[5,4,3,2,1],"bx")
show()

Now you can use any function in matplotlib.pyplot without referencing them with matplotlib.pyplot.

I would recommend you to name imports you have, in this case you can prevent disambiguation and future problems with the same function names. The last and clean version of above example looks like:

import matplotlib.pyplot as plt
plt.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
plt.show()

How to access the elements of a 2D array?

If you have

a=[[1,1],[2,1],[3,1]]
b=[[1,2],[2,2],[3,2]]

Then

a[1][1]

Will work fine. It points to the second column, second row just like you wanted.

I'm not sure what you did wrong.

To multiply the cells in the third column you can just do

c = [a[2][i] * b[2][i] for i in range(len(a[2]))] 

Which will work for any number of rows.

Edit: The first number is the column, the second number is the row, with your current layout. They are both numbered from zero. If you want to switch the order you can do

a = zip(*a)

or you can create it that way:

a=[[1, 2, 3], [1, 1, 1]]

Is there a Newline constant defined in Java like Environment.Newline in C#?

Be aware that this property isn't as useful as many people think it is. Just because your app is running on a Windows machine, for example, doesn't mean the file it's reading will be using Windows-style line separators. Many web pages contain a mixture of "\n" and "\r\n", having been cobbled together from disparate sources. When you're reading text as a series of logical lines, you should always look for all three of the major line-separator styles: Windows ("\r\n"), Unix/Linux/OSX ("\n") and pre-OSX Mac ("\r").

When you're writing text, you should be more concerned with how the file will be used than what platform you're running on. For example, if you expect people to read the file in Windows Notepad, you should use "\r\n" because it only recognizes the one kind of separator.

Why this "Implicit declaration of function 'X'"?

summation and your other functions are defined after they're used in main, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.

You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.

Either move the function bodies before main, or include method signatures before main, e.g.:

#include <stdio.h>

int summation(int *, int *, int *);

int main()
{
    // ...

Is it better to return null or empty collection?

Think always in favor of your clients (which are using your api):

Returning 'null' very often makes problems with clients not handling null checks correctly, which causes a NullPointerException during runtime. I have seen cases where such a missing null-check forced a priority production issue (a client used foreach(...) on a null value). During testing the problem did not occur, because the data operated on was slightly different.

Ajax success function

The answer given above can't solve my problem.So I change async into false to get the alert message.

jQuery.ajax({
            type:"post",
            dataType:"json",
            async: false,
            url: myAjax.ajaxurl,
            data: {action: 'submit_data', info: info},
            success: function(data) {
                alert("Data was succesfully captured");
            },
        });

Should a RESTful 'PUT' operation return something

I used RESTful API in my services, and here is my opinion: First we must get to a common view: PUT is used to update an resource not create or get.

I defined resources with: Stateless resource and Stateful resource:

  • Stateless resources For these resources, just return the HttpCode with empty body, it's enough.

  • Stateful resources For example: the resource's version. For this kind of resources, you must provide the version when you want to change it, so return the full resource or return the version to the client, so the client need't to send a get request after the update action.

But, for a service or system, keep it simple, clearly, easy to use and maintain is the most important thing.

How to upgrade Angular CLI to the latest version

In my case, I have installed angular-cli locally using npm install --save-dev angular-cli. So, when I use command npm install -g @angular/cli, it generates error saying that "Your global Angular CLI version (1.7.3) is greater than your local version (1.4.9)". Please note that angular-cli, @angular/cli and @angular/cli@latest are two different cli's. What solves this is uninstall all cli and then install latest angular cli using npm install -g @angular/cli@latest

How to save a bitmap on internal storage

You might be able to use the following for decoding, compressing and saving an image:

     @Override
     public void onClick(View view) {
                onItemSelected1();
                InputStream image_stream = null;
                try {
                    image_stream = getContentResolver().openInputStream(myUri);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

                Bitmap image= BitmapFactory.decodeStream(image_stream );
                // path to sd card
                File path=Environment.getExternalStorageDirectory();
                //create a file
                File  dir=new File(path+"/ComDec/");
                dir.mkdirs();
                Date date=new Date();
                File file=new File(dir,date+".jpg");

                OutputStream out=null;
                try{
                    out=new FileOutputStream(file);
                    image.compress(format,size,out);
                    out.flush();
                    out.close();


                    MediaStore.Images.Media.insertImage(getContentResolver(), image," yourTitle "," yourDescription");

                    image=null;


                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                Toast.makeText(SecondActivity.this,"Image Save Successfully",Toast.LENGTH_LONG).show();
            }
        });

How to auto-format code in Eclipse?

We can make it by :
Ctrl+i or Ctrl+Shift+F

How can I undo git reset --hard HEAD~1?

Example of IRL case:

$ git fsck --lost-found

Checking object directories: 100% (256/256), done.
Checking objects: 100% (3/3), done.
dangling blob 025cab9725ccc00fbd7202da543f556c146cb119
dangling blob 84e9af799c2f5f08fb50874e5be7fb5cb7aa7c1b
dangling blob 85f4d1a289e094012819d9732f017c7805ee85b4
dangling blob 8f654d1cd425da7389d12c17dd2d88d318496d98
dangling blob 9183b84bbd292dcc238ca546dab896e073432933
dangling blob 1448ee51d0ea16f259371b32a557b60f908d15ee
dangling blob 95372cef6148d980ab1d7539ee6fbb44f5e87e22
dangling blob 9b3bf9fb1ee82c6d6d5ec9149e38fe53d4151fbd
dangling blob 2b21002ca449a9e30dbb87e535fbd4e65bac18f7
dangling blob 2fff2f8e4ea6408ac84a8560477aa00583002e66
dangling blob 333e76340b59a944456b4befd0e007c2e23ab37b
dangling blob b87163c8def315d40721e592f15c2192a33816bb
dangling blob c22aafb90358f6bf22577d1ae077ad89d9eea0a7
dangling blob c6ef78dd64c886e9c9895e2fc4556e69e4fbb133
dangling blob 4a71f9ff8262701171d42559a283c751fea6a201
dangling blob 6b762d368f44ddd441e5b8eae6a7b611335b49a2
dangling blob 724d23914b48443b19eada79c3eb1813c3c67fed
dangling blob 749ffc9a412e7584245af5106e78167b9480a27b
dangling commit f6ce1a403399772d4146d306d5763f3f5715cb5a    <- it's this one

$ git show f6ce1a403399772d4146d306d5763f3f5715cb5a

commit f6ce1a403399772d4146d306d5763f3f5715cb5a
Author: Stian Gudmundsen Høiland <[email protected]>
Date:   Wed Aug 15 08:41:30 2012 +0200

    *MY COMMIT MESSAGE IS DISPLAYED HERE*

diff --git a/Some.file b/Some.file
new file mode 100644
index 0000000..15baeba
--- /dev/null
+++ b/Some.file
*THE WHOLE COMMIT IS DISPLAYED HERE*

$ git rebase f6ce1a403399772d4146d306d5763f3f5715cb5a

First, rewinding head to replay your work on top of it...
Fast-forwarded master to f6ce1a403399772d4146d306d5763f3f5715cb5a.

What is the difference between __str__ and __repr__?

On page 358 of the book Python scripting for computational science by Hans Petter Langtangen, it clearly states that

  • The __repr__ aims at a complete string representation of the object;
  • The __str__ is to return a nice string for printing.

So, I prefer to understand them as

  • repr = reproduce
  • str = string (representation)

from the user's point of view although this is a misunderstanding I made when learning python.

A small but good example is also given on the same page as follows:

Example

In [38]: str('s')
Out[38]: 's'

In [39]: repr('s')
Out[39]: "'s'"

In [40]: eval(str('s'))
Traceback (most recent call last):

  File "<ipython-input-40-abd46c0c43e7>", line 1, in <module>
    eval(str('s'))

  File "<string>", line 1, in <module>

NameError: name 's' is not defined


In [41]: eval(repr('s'))
Out[41]: 's'

When do Java generics require <? extends T> instead of <T> and is there any downside of switching?

It boils down to:

Class<? extends Serializable> c1 = null;
Class<java.util.Date> d1 = null;
c1 = d1; // compiles
d1 = c1; // wont compile - would require cast to Date

You can see the Class reference c1 could contain a Long instance (since the underlying object at a given time could have been List<Long>), but obviously cannot be cast to a Date since there is no guarantee that the "unknown" class was Date. It is not typsesafe, so the compiler disallows it.

However, if we introduce some other object, say List (in your example this object is Matcher), then the following becomes true:

List<Class<? extends Serializable>> l1 = null;
List<Class<java.util.Date>> l2 = null;
l1 = l2; // wont compile
l2 = l1; // wont compile

...However, if the type of the List becomes ? extends T instead of T....

List<? extends Class<? extends Serializable>> l1 = null;
List<? extends Class<java.util.Date>> l2 = null;
l1 = l2; // compiles
l2 = l1; // won't compile

I think by changing Matcher<T> to Matcher<? extends T>, you are basically introducing the scenario similar to assigning l1 = l2;

It's still very confusing having nested wildcards, but hopefully that makes sense as to why it helps to understand generics by looking at how you can assign generic references to each other. It's also further confusing since the compiler is inferring the type of T when you make the function call (you are not explicitly telling it was T is).

How do I convert NSInteger to NSString datatype?

NSNumber may be good for you in this case.

NSString *inStr = [NSString stringWithFormat:@"%d", 
                    [NSNumber numberWithInteger:[month intValue]]];

In javascript, how do you search an array for a substring match

I think this may help you. I had a similar issue. If your array looks like this:

var array = ["page1","1973","Jimmy"]; 

You can do a simple "for" loop to return the instance in the array when you get a match.

var c; 
for (i = 0; i < array.length; i++) {
if (array[i].indexOf("page") > -1){ 
c = i;}
} 

We create an empty variable, c to host our answer. We then loop through the array to find where the array object (e.g. "page1") matches our indexOf("page"). In this case, it's 0 (the first result)

Happy to expand if you need further support.

Where do I put image files, css, js, etc. in Codeigniter?

No one says that you need to modify the .htacces and add the directory in the rewrite condition. I've created a directory "public" in the root directory alongside with "system", "application", "index.php". and edited the .htaccess file like this:

RewriteCond $1 !^(index\.php|public|robots\.txt)

Now you have to just call <?php echo base_url()."/public/yourdirectory/yuorfile";?> You can add subdirectory inside "public" dir as you like.

Show image using file_get_contents

Small edit to @seengee answer: In order to work, you need curly braces around the variable, otherwise you'll get an error.

header("Content-type: {$imginfo['mime']}");

Angular 5 - Copy to clipboard

As of Angular Material v9, it now has a clipboard CDK

Clipboard | Angular Material

It can be used as simply as

<button [cdkCopyToClipboard]="This goes to Clipboard">Copy this</button>

PUT and POST getting 405 Method Not Allowed Error for Restful Web Services

I same thing happen with me, If your code is correct and then also give 405 error. this error due to some authorization problem. go to authorization menu and change to "Inherit auth from parent".

Authorization Type options menu Authorization Inherit auth from parent selected

How are software license keys generated?

I've not got any experience with what people actually do to generate CD keys, but (assuming you're not wanting to go down the road of online activation) here are a few ways one could make a key:

  • Require that the number be divisible by (say) 17. Trivial to guess, if you have access to many keys, but the majority of potential strings will be invalid. Similar would be requiring that the checksum of the key match a known value.

  • Require that the first half of the key, when concatenated with a known value, hashes down to the second half of the key. Better, but the program still contains all the information needed to generate keys as well as to validate them.

  • Generate keys by encrypting (with a private key) a known value + nonce. This can be verified by decrypting using the corresponding public key and verifying the known value. The program now has enough information to verify the key without being able to generate keys.

These are still all open to attack: the program is still there and can be patched to bypass the check. Cleverer might be to encrypt part of the program using the known value from my third method, rather than storing the value in the program. That way you'd have to find a copy of the key before you could decrypt the program, but it's still vulnerable to being copied once decrypted and to having one person take their legit copy and use it to enable everyone else to access the software.

Autoresize View When SubViews are Added

Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.

You should read Working with Auto Layout Programmatically and Visual Format Language.

You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.

How to form tuple column from two columns in Pandas

Get comfortable with zip. It comes in handy when dealing with column data.

df['new_col'] = list(zip(df.lat, df.long))

It's less complicated and faster than using apply or map. Something like np.dstack is twice as fast as zip, but wouldn't give you tuples.

Use curly braces to initialize a Set in Python

From Python 3 documentation (the same holds for python 2.7):

Curly braces or the set() function can be used to create sets. Note: to create an empty set you have to use set(), not {}; the latter creates an empty dictionary, a data structure that we discuss in the next section.

in python 2.7:

>>> my_set = {'foo', 'bar', 'baz', 'baz', 'foo'}
>>> my_set
set(['bar', 'foo', 'baz'])

Be aware that {} is also used for map/dict:

>>> m = {'a':2,3:'d'}
>>> m[3]
'd'
>>> m={}
>>> type(m)
<type 'dict'> 

One can also use comprehensive syntax to initialize sets:

>>> a = {x for x in """didn't know about {} and sets """ if x not in 'set' }
>>> a
set(['a', ' ', 'b', 'd', "'", 'i', 'k', 'o', 'n', 'u', 'w', '{', '}'])

Shrinking navigation bar when scrolling down (bootstrap3)

I am using this code for my project

$(window).scroll ( function() {
    if ($(document).scrollTop() > 50) {
        document.getElementById('your-div').style.height = '100px'; //For eg
    } else {
        document.getElementById('your-div').style.height = '150px';
    }    
}
);

Probably this will help

What is the difference between re.search and re.match?

match is much faster than search, so instead of doing regex.search("word") you can do regex.match((.*?)word(.*?)) and gain tons of performance if you are working with millions of samples.

This comment from @ivan_bilan under the accepted answer above got me thinking if such hack is actually speeding anything up, so let's find out how many tons of performance you will really gain.

I prepared the following test suite:

import random
import re
import string
import time

LENGTH = 10
LIST_SIZE = 1000000

def generate_word():
    word = [random.choice(string.ascii_lowercase) for _ in range(LENGTH)]
    word = ''.join(word)
    return word

wordlist = [generate_word() for _ in range(LIST_SIZE)]

start = time.time()
[re.search('python', word) for word in wordlist]
print('search:', time.time() - start)

start = time.time()
[re.match('(.*?)python(.*?)', word) for word in wordlist]
print('match:', time.time() - start)

I made 10 measurements (1M, 2M, ..., 10M words) which gave me the following plot:

match vs. search regex speedtest line plot

The resulting lines are surprisingly (actually not that surprisingly) straight. And the search function is (slightly) faster given this specific pattern combination. The moral of this test: Avoid overoptimizing your code.

mySQL :: insert into table, data from another table?

INSERT INTO preliminary_image (style_id,pre_image_status,file_extension,reviewer_id,
uploader_id,is_deleted,last_updated) 

SELECT '4827499',pre_image_status,file_extension,reviewer_id,
uploader_id,'0',last_updated FROM preliminary_image WHERE style_id=4827488

Analysis

We can use above query if we want to copy data from one table to another table in mysql

  1. Here source and destination table are same, we can use different tables also.
  2. Few columns we are not copying like style_id and is_deleted so we selected them hard coded from another table
  3. Table we used in source also contains auto increment field so we left that column and it get inserted automatically with execution of query.

Execution results

1 queries executed, 1 success, 0 errors, 0 warnings

Query: insert into preliminary_image (style_id,pre_image_status,file_extension,reviewer_id,uploader_id,is_deleted,last_updated) select ...

5 row(s) affected

Execution Time : 0.385 sec Transfer Time : 0 sec Total Time : 0.386 sec

How to process POST data in Node.js?

On form fields like these

   <input type="text" name="user[name]" value="MyName">
   <input type="text" name="user[email]" value="[email protected]">

some of the above answers will fail because they only support flat data.

For now I am using the Casey Chu answer but with the "qs" instead of the "querystring" module. This is the module "body-parser" uses as well. So if you want nested data you have to install qs.

npm install qs --save

Then replace the first line like:

//var qs = require('querystring');
var qs = require('qs'); 

function (request, response) {
    if (request.method == 'POST') {
        var body = '';

        request.on('data', function (data) {
            body += data;

            // Too much POST data, kill the connection!
            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
            if (body.length > 1e6)
                request.connection.destroy();
        });

        request.on('end', function () {
            var post = qs.parse(body);
            console.log(post.user.name); // should work
            // use post['blah'], etc.
        });
    }
}

How to export/import PuTTy sessions list?

For those of you who need to import Putty from offline registry file e.g. when you are recovering from crashed system or simply moving to a new machine and grabbing data off that old drive there is one more solution worth mentioning:

http://www.nirsoft.net/utils/registry_file_offline_export.html

This great and free console application will export the entire registry or only a specific registry key. In my case i simply copied the registry file from an old drive to the same directory as the exporter tool and then i used following command and syntax in CMD window run as administrator:

RegFileExport.exe NTUSER.DAT putty.reg "HKEY_CURRENT_USER\Software\SimonTatham"

After importing the .reg file and starting Putty everything was there. Simple and efficient.

How to open every file in a folder

you should try using os.walk

yourpath = 'path'

import os
for root, dirs, files in os.walk(yourpath, topdown=False):
    for name in files:
        print(os.path.join(root, name))
        stuff
    for name in dirs:
        print(os.path.join(root, name))
        stuff

How to create query parameters in Javascript?

ES2017 (ES8)

Making use of Object.entries(), which returns an array of object's [key, value] pairs. For example, for {a: 1, b: 2} it would return [['a', 1], ['b', 2]]. It is not supported (and won't be) only by IE.

Code:

const buildURLQuery = obj =>
      Object.entries(obj)
            .map(pair => pair.map(encodeURIComponent).join('='))
            .join('&');

Example:

buildURLQuery({name: 'John', gender: 'male'});

Result:

"name=John&gender=male"

update listview dynamically with adapter

If you create your own adapter, there is one notable abstract function:

public void registerDataSetObserver(DataSetObserver observer) {
    ...
}

You can use the given observers to notify the system to update:

private ArrayList<DataSetObserver> observers = new ArrayList<DataSetObserver>();

public void registerDataSetObserver(DataSetObserver observer) {
    observers.add(observer);
}
public void notifyDataSetChanged(){
    for (DataSetObserver observer: observers) {
        observer.onChanged();
    }
}

Though aren't you glad there are things like the SimpleAdapter and ArrayAdapter and you don't have to do all that?

Ternary operator in AngularJS templates

There it is : ternary operator got added to angular parser in 1.1.5! see the changelog

Here is a fiddle showing new ternary operator used in ng-class directive.

ng-class="boolForTernary ? 'blue' : 'red'"

Check if property has attribute

To update and/or enhance the answer by @Hans Passant I would separate the retrieval of the property into an extension method. This has the added benefit of removing the nasty magic string in the method GetProperty()

public static class PropertyHelper<T>
{
    public static PropertyInfo GetProperty<TValue>(
        Expression<Func<T, TValue>> selector)
    {
        Expression body = selector;
        if (body is LambdaExpression)
        {
            body = ((LambdaExpression)body).Body;
        }
        switch (body.NodeType)
        {
            case ExpressionType.MemberAccess:
                return (PropertyInfo)((MemberExpression)body).Member;
            default:
                throw new InvalidOperationException();
        }
    }
}

Your test is then reduced to two lines

var property = PropertyHelper<MyClass>.GetProperty(x => x.MyProperty);
Attribute.IsDefined(property, typeof(MyPropertyAttribute));

SQL Server : GROUP BY clause to get comma-separated values

SELECT  [ReportId], 
        SUBSTRING(d.EmailList,1, LEN(d.EmailList) - 1) EmailList
FROM
        (
            SELECT DISTINCT [ReportId]
            FROM Table1
        ) a
        CROSS APPLY
        (
            SELECT [Email] + ', ' 
            FROM Table1 AS B 
            WHERE A.[ReportId] = B.[ReportId]
            FOR XML PATH('')
        ) D (EmailList) 

SQLFiddle Demo

Remove the legend on a matplotlib figure

If you want to plot a Pandas dataframe and want to remove the legend, add legend=None as parameter to the plot command.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df2 = pd.DataFrame(np.random.randn(10, 5))
df2.plot(legend=None)
plt.show()

What is the minimum I have to do to create an RPM file?

Similarly, I needed to create an rpm with just a few files. Since these files were source controlled, and because it seemed silly, I didn't want to go through taring them up just to have rpm untar them. I came up with the following:

  1. Set up your environment:

    mkdir -p ~/rpm/{BUILD,RPMS}

    echo '%_topdir %(echo "$HOME")/rpm' > ~/.rpmmacros

  2. Create your spec file, foobar.spec, with the following contents:

    Summary: Foo to the Bar
    Name: foobar
    Version: 0.1
    Release: 1
    Group: Foo/Bar
    License: FooBarPL
    Source: %{expand:%%(pwd)}
    BuildRoot: %{_topdir}/BUILD/%{name}-%{version}-%{release}
    
    %description
    %{summary}
    
    %prep
    rm -rf $RPM_BUILD_ROOT
    mkdir -p $RPM_BUILD_ROOT/usr/bin
    mkdir -p $RPM_BUILD_ROOT/etc
    cd $RPM_BUILD_ROOT
    cp %{SOURCEURL0}/foobar ./usr/bin/
    cp %{SOURCEURL0}/foobar.conf ./etc/
    
    %clean
    rm -r -f "$RPM_BUILD_ROOT"
    
    %files
    %defattr(644,root,root)
    %config(noreplace) %{_sysconfdir}/foobar.conf
    %defattr(755,root,root)
    %{_bindir}/foobar
    
  3. Build your rpm: rpmbuild -bb foobar.spec

There's a little hackery there specifying the 'source' as your current directory, but it seemed far more elegant then the alternative, which was to, in my case, write a separate script to create a tarball, etc, etc.

Note: In my particular situation, my files were arranged in folders according to where they needed to go, like this:

./etc/foobar.conf
./usr/bin/foobar

and so the prep section became:

%prep
rm -rf $RPM_BUILD_ROOT
mkdir -p $RPM_BUILD_ROOT
cd $RPM_BUILD_ROOT
tar -cC %{SOURCEURL0} --exclude 'foobar.spec' -f - ./ | tar xf -

Which is a little cleaner.

Also, I happen to be on a RHEL5.6 with rpm versions 4.4.2.3, so your mileage may vary.

Javascript/jQuery detect if input is focused

Using jQuery's .is( ":focus" )

$(".status").on("click","textarea",function(){
        if ($(this).is( ":focus" )) {
            // fire this step
        }else{
                    $(this).focus();
            // fire this step
    }

FailedPreconditionError: Attempting to use uninitialized in Tensorflow

With tensorflow version >3.2 you may use this command:

x1 = tf.Variable(5)
y1 = tf.Variable(3)

z1 = x1 + y1

init = tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as sess:
    init.run()
    print(sess.run(z1))

The output: 8 will be displayed.

How does a Linux/Unix Bash script know its own PID?

use $BASHPID or $$

See the [manual][1] for more information, including differences between the two.

TL;DRTFM

  • $$ Expands to the process ID of the shell.
    • In a () subshell, it expands to the process ID of the invoking shell, not the subshell.
  • $BASHPID Expands to the process ID of the current Bash process (new to bash 4).

Illegal Character when trying to compile java code

http://en.wikipedia.org/wiki/Byte_order_mark

The byte order mark (BOM) is a Unicode character used to signal the endianness (byte order) of a text file or stream. Its code point is U+FEFF. BOM use is optional, and, if used, should appear at the start of the text stream. Beyond its specific use as a byte-order indicator, the BOM character may also indicate which of the several Unicode representations the text is encoded in.

The BOM is a funky-looking character that you sometimes find at the start of unicode streams, giving a clue what the encoding is. It's usually handles invisibly by the string-handling stuff in Java, so you must have confused it somehow, but without seeing your code, it's hard to see where.

You might be able to fix it trivially by manually stripping the BOM from the string before feeding it to javac. It probably qualifies as whitespace, so try calling trim() on the input String, and feeding the output of that to javac.

How to represent the double quotes character (") in regex?

Firstly, double quote character is nothing special in regex - it's just another character, so it doesn't need escaping from the perspective of regex.

However, because java uses double quotes to delimit String constants, if you want to create a string in java with a double quote in it, you must escape them.

This code will test if your String matches:

if (str.matches("\".*\"")) {
    // this string starts and end with a double quote
}

Note that you don't need to add start and end of input markers (^ and $) in the regex, because matches() requires that the whole input be matched to return true - ^ and $ are implied.

How to call a shell script from python code?

Use the subprocess module as mentioned above.

I use it like this:

subprocess.call(["notepad"])

What is the difference between function and procedure in PL/SQL?

In dead simple way it makes this meaning.

Functions :

These subprograms return a single value; mainly used to compute and return a value.

Procedure :

These subprograms do not return a value directly; mainly used to perform an action.

Example Program:

CREATE OR REPLACE PROCEDURE greetings

BEGIN 

dbms_output.put_line('Hello World!');

END ;
/

Executing a Standalone Procedure :

A standalone procedure can be called in two ways:

• Using the EXECUTE keyword • Calling the name of procedure from a PL/SQL block

The procedure can also be called from another PL/SQL block:

BEGIN 
greetings;
END;
/

Function:

CREATE OR REPLACE FUNCTION totalEmployees 
RETURN number IS
total number(3) := 0;
BEGIN 
SELECT count(*) into total 
FROM employees;
RETURN total; 
END;
/

Following program calls the function totalCustomers from an another block

DECLARE 
c number(3);
BEGIN 
c := totalEmployees();
dbms_output.put_line('Total no. of Employees: ' || c);
END;
/

Is there a native jQuery function to switch elements?

I've made a function which allows you to move multiple selected options up or down

$('#your_select_box').move_selected_options('down');
$('#your_select_boxt').move_selected_options('up');

Dependencies:

$.fn.reverse = [].reverse;
function swapWith() (Paolo Bergantino)

First it checks whether the first/last selected option is able to move up/down. Then it loops through all the elements and calls

swapWith(element.next() or element.prev())

jQuery.fn.move_selected_options = function(up_or_down) {
  if(up_or_down == 'up'){
      var first_can_move_up = $("#" + this.attr('id') + ' option:selected:first').prev().size();
      if(first_can_move_up){
          $.each($("#" + this.attr('id') + ' option:selected'), function(index, option){
              $(option).swapWith($(option).prev());
          });
      }
  } else {
      var last_can_move_down = $("#" + this.attr('id') + ' option:selected:last').next().size();
      if(last_can_move_down){
        $.each($("#" + this.attr('id') + ' option:selected').reverse(), function(index, option){
            $(option).swapWith($(option).next());
        });
      }
  }
  return $(this);
}

'tuple' object does not support item assignment

PIL pixels are tuples, and tuples are immutable. You need to construct a new tuple. So, instead of the for loop, do:

pixels = [(pixel[0] + 20, pixel[1], pixel[2]) for pixel in pixels]
image.putdata(pixels)

Also, if the pixel is already too red, adding 20 will overflow the value. You probably want something like min(pixel[0] + 20, 255) or int(255 * (pixel[0] / 255.) ** 0.9) instead of pixel[0] + 20.

And, to be able to handle images in lots of different formats, do image = image.convert("RGB") after opening the image. The convert method will ensure that the pixels are always (r, g, b) tuples.

List all environment variables from the command line

Simply run set from cmd.

Displays, sets, or removes environment variables. Used without parameters, set displays the current environment settings.

How to define a default value for "input type=text" without using attribute 'value'?

this is working for me

<input defaultValue="1000" type="text" />

or

let x = document.getElementById("myText").defaultValue; 

Select subset of columns in data.table R

Option using dplyr

require(dplyr)
dt<-as.data.frame(matrix(runif(10*10),10,10))
dt <- select(dt, -V1, -V2, -V3, -V4)
cor(dt)

Catch KeyError in Python

You should consult the documentation of whatever library is throwing the exception, to see how to get an error message out of its exceptions.

Alternatively, a good way to debug this kind of thing is to say:

except Exception, e:
    print dir(e)

to see what properties e has - you'll probably find it has a message property or similar.

Is Tomcat running?

I always do

tail -f logs/catalina.out

When I see there

INFO: Server startup in 77037 ms

then I know the server is up.

Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship

You could also disable the cascade delete convention in global scope of your application by doing this:

modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>()
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>()

Save file/open file dialog box, using Swing & Netbeans GUI editor

saving in any format is very much possible. Check following- http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html

2ndly , What exactly you are expecting the save dialog to work , it works like that, Opening a doc file is very much possible- http://srikanthtechnologies.com/blog/openworddoc.html

Simple Deadlock Examples

public class DeadlockProg {

    /**
     * @Gowtham Chitimi Reddy IIT(BHU);
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        final Object ob1 = new Object();
        final Object ob2 = new Object();
        Thread t1 = new Thread(){
            public void run(){
                synchronized(ob1){
                    try{
                        Thread.sleep(100);
                    }
                    catch(InterruptedException e){
                        System.out.println("Error catched");
                    }
                    synchronized(ob2){

                    }
                }

            }
        };
        Thread t2 = new Thread(){
            public void run(){
                synchronized(ob2){
                    try{
                        Thread.sleep(100);
                    }
                    catch(InterruptedException e){
                        System.out.println("Error catched");
                    }
                    synchronized(ob1){                      
                    }
                }               
            }
        };
        t1.start();
        t2.start();
    }

}

How to quit a java app from within the program

You can use System.exit() for this purpose.

According to oracle's Java 8 documentation:

public static void exit(int status)

Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.

This method calls the exit method in class Runtime. This method never returns normally.

The call System.exit(n) is effectively equivalent to the call:

Runtime.getRuntime().exit(n)

How to solve the “failed to lazily initialize a collection of role” Hibernate exception

it was the problem i recently faced which i solved with using

<f:attribute name="collectionType" value="java.util.ArrayList" />

more detailed decription here and this saved my day.

Java 8 stream map on entry set

Here is a shorter solution by AbacusUtil

Stream.of(input).toMap(e -> e.getKey().substring(subLength), 
                       e -> AttributeType.GetByName(e.getValue()));

How can I make a float top with CSS?

The only way to do this with CSS only is by using CSS 3 which is not going to work on every browser (only the latest generation like FF 3.5, Opera, Safari, Chrome).

Indeed with CSS 3 there's this awesome property : column-count that you can use like so :

#myContent{
  column-count: 2;
  column-gap: 20px;
  height: 350px;
}

If #myContent is wrapping your other divs.

More info here : http://www.quirksmode.org/css/multicolumn.html

As you can read there, there are serious limitations in using this. In the example above, it will only add up to one another column if the content overflows. in mozilla you can use the column-width property that allows you to divide the content in as many columns as needed.

Otherwise you'll have to distribute the content between different divs in Javascript or in the backend.

Get a random boolean in python?

Found a faster method:

$ python -m timeit -s "from random import getrandbits" "not getrandbits(1)"
10000000 loops, best of 3: 0.222 usec per loop
$ python -m timeit -s "from random import random" "True if random() > 0.5 else False"
10000000 loops, best of 3: 0.0786 usec per loop
$ python -m timeit -s "from random import random" "random() > 0.5"
10000000 loops, best of 3: 0.0579 usec per loop

Find Oracle JDBC driver in Maven repository

You can use Nexus to manage 3rd party dependencies as well as dependencies in standard maven repositories.

OrderBy descending in Lambda expression?

Try this:

List<int> list = new List<int>();
list.Add(1);
list.Add(5);
list.Add(4);
list.Add(3);
list.Add(2);

foreach (var item in list.OrderByDescending(x => x))
{
    Console.WriteLine(item);                
}

Select DISTINCT individual columns in django?

One way to get the list of distinct column names from the database is to use distinct() in conjunction with values().

In your case you can do the following to get the names of distinct categories:

q = ProductOrder.objects.values('Category').distinct()
print q.query # See for yourself.

# The query would look something like
# SELECT DISTINCT "app_productorder"."category" FROM "app_productorder"

There are a couple of things to remember here. First, this will return a ValuesQuerySet which behaves differently from a QuerySet. When you access say, the first element of q (above) you'll get a dictionary, NOT an instance of ProductOrder.

Second, it would be a good idea to read the warning note in the docs about using distinct(). The above example will work but all combinations of distinct() and values() may not.

PS: it is a good idea to use lower case names for fields in a model. In your case this would mean rewriting your model as shown below:

class ProductOrder(models.Model):
    product  = models.CharField(max_length=20, primary_key=True)
    category = models.CharField(max_length=30)
    rank = models.IntegerField()

How can I solve the error 'TS2532: Object is possibly 'undefined'?

With the release of TypeScript 3.7, optional chaining (the ? operator) is now officially available.

As such, you can simplify your expression to the following:

const data = change?.after?.data();

You may read more about it from that version's release notes, which cover other interesting features released on that version.

Run the following to install the latest stable release of TypeScript.

npm install typescript

That being said, Optional Chaining can be used alongside Nullish Coalescing to provide a fallback value when dealing with null or undefined values

const data = change?.after?.data() ?? someOtherData();

How to read file from res/raw by name

You can read files in raw/res using getResources().openRawResource(R.raw.myfilename).

BUT there is an IDE limitation that the file name you use can only contain lower case alphanumeric characters and dot. So file names like XYZ.txt or my_data.bin will not be listed in R.

How to ignore the certificate check when ssl

Just incidentally, this is a the least verbose way of turning off all certificate validation in a given app that I know of:

ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true;

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

Uncaught TypeError: Cannot set property 'value' of null

h_url=document.getElementById("u") is null here

There is no element exist with id as u

How do I set up access control in SVN?

The best way is to set up Apache and to set the access through it. Check the svn book for help. If you don't want to use Apache, you can also do minimalistic access control using svnserve.

Converting a sentence string to a string array of words in Java

Try this:

String[] stringArray = Pattern.compile("ian").split(
"This is a sample sentence"
.replaceAll("[^\\p{Alnum}]+", "") //this will remove all non alpha numeric chars
);

for (int j=0; i<stringArray .length; j++) {
  System.out.println(i + " \"" + stringArray [j] + "\"");
}

PySpark: withColumn() with two conditions and three outcomes

You'll want to use a udf as below

from pyspark.sql.types import IntegerType
from pyspark.sql.functions import udf

def func(fruit1, fruit2):
    if fruit1 == None or fruit2 == None:
        return 3
    if fruit1 == fruit2:
        return 1
    return 0

func_udf = udf(func, IntegerType())
df = df.withColumn('new_column',func_udf(df['fruit1'], df['fruit2']))

Set environment variables on Mac OS X Lion

I took the idiot route. Added these to the end of /etc/profile

for environment in `find /etc/environments.d -type f`
do
     . $environment
done

created a folder /etc/environments create a file in it called "oracle" or "whatever" and added the stuff I needed set globally to it.

/etc$ cat /etc/environments.d/Oracle

export PATH=$PATH:/Library/Oracle/instantclient_11_2
export DYLD_LIBRARY_PATH=/Library/Oracle/instantclient_11_2
export SQLPATH=/Library/Oracle/instantclient_11_2
export PATH=$PATH:/Library/Oracle/instantclient_11_2
export TNS_ADMIN=/Library/Oracle/instantclient_11_2/network/admin

Use CSS to make a span not clickable

Not with CSS. You could do it with JavaScript easily, though, by canceling the default event handling for those elements. In jQuery:

$('a span:nth-child(2)').click(function(event) { event.preventDefault(); });

Writing JSON object to a JSON file with fs.writeFileSync

When sending data to a web server, the data has to be a string (here). You can convert a JavaScript object into a string with JSON.stringify(). Here is a working example:

var fs = require('fs');

var originalNote = {
  title: 'Meeting',
  description: 'Meeting John Doe at 10:30 am'
};

var originalNoteString = JSON.stringify(originalNote);

fs.writeFileSync('notes.json', originalNoteString);

var noteString = fs.readFileSync('notes.json');

var note = JSON.parse(noteString);

console.log(`TITLE: ${note.title} DESCRIPTION: ${note.description}`);

Hope it could help.

OkHttp Post Body as JSON

Just use JSONObject.toString(); method. And have a look at OkHttp's tutorial:

public static final MediaType JSON
    = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json); // new
  // RequestBody body = RequestBody.create(JSON, json); // old
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}

How to get old Value with onchange() event in text box

A dirty trick I somtimes use, is hiding variables in the 'name' attribute (that I normally don't use for other purposes):

select onFocus=(this.name=this.value) onChange=someFunction(this.name,this.value)><option...

Somewhat unexpectedly, both the old and the new value is then submitted to someFunction(oldValue,newValue)

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

The right way to add further configurations to the Spring Boot peconfigured ObjectMapper is to define a Jackson2ObjectMapperBuilderCustomizer. Else you are overwriting Springs configuration, which you do not want to lose.

 @Configuration
public class MyJacksonConfigurer implements Jackson2ObjectMapperBuilderCustomizer {
    @Override
    public void customize(Jackson2ObjectMapperBuilder builder) {
        builder.deserializerByType(LocalDate.class, new MyOwnJsonLocalDateTimeDeserializer());
    }
}

Change variable name in for loop using R

Another option is using eval and parse, as in

d = 5
for (i in 1:10){
     eval(parse(text = paste('a', 1:10, ' = d + rnorm(3)', sep='')[i]))
}

In Javascript, how do I check if an array has duplicate values?

If you have an ES2015 environment (as of this writing: io.js, IE11, Chrome, Firefox, WebKit nightly), then the following will work, and will be fast (viz. O(n)):

function hasDuplicates(array) {
    return (new Set(array)).size !== array.length;
}

If you only need string values in the array, the following will work:

function hasDuplicates(array) {
    var valuesSoFar = Object.create(null);
    for (var i = 0; i < array.length; ++i) {
        var value = array[i];
        if (value in valuesSoFar) {
            return true;
        }
        valuesSoFar[value] = true;
    }
    return false;
}

We use a "hash table" valuesSoFar whose keys are the values we've seen in the array so far. We do a lookup using in to see if that value has been spotted already; if so, we bail out of the loop and return true.


If you need a function that works for more than just string values, the following will work, but isn't as performant; it's O(n2) instead of O(n).

function hasDuplicates(array) {
    var valuesSoFar = [];
    for (var i = 0; i < array.length; ++i) {
        var value = array[i];
        if (valuesSoFar.indexOf(value) !== -1) {
            return true;
        }
        valuesSoFar.push(value);
    }
    return false;
}

The difference is simply that we use an array instead of a hash table for valuesSoFar, since JavaScript "hash tables" (i.e. objects) only have string keys. This means we lose the O(1) lookup time of in, instead getting an O(n) lookup time of indexOf.

How to compare arrays in JavaScript?

var er = [{id:"23",name:"23222"}, {id:"222",name:"23222222"}];
var er2 = [{id:"23",name:"23222"}, {id:"222",name:"23222222"}];

var result = (JSON.stringify(er) == JSON.stringify(er2)); // true

It works json objects well if the order of the property of each entry is not changed.

var er = [{name:"23222",id:"23"}, {id:"222",name:"23222222"}];
var er2 = [{id:"23",name:"23222"}, {id:"222",name:"23222222"}];

var result = (JSON.stringify(er) == JSON.stringify(er2)); // false  

But there is only one property or value in each entry of the array, this will work fine.

Check if an element is present in a Bash array

array=("word" "two words") # let's look for "two words"

using grep and printf:

(printf '%s\n' "${array[@]}" | grep -x -q "two words") && <run_your_if_found_command_here>

using for:

(for e in "${array[@]}"; do [[ "$e" == "two words" ]] && exit 0; done; exit 1) && <run_your_if_found_command_here>

For not_found results add || <run_your_if_notfound_command_here>

Upgrading PHP on CentOS 6.5 (Final)

  1. Verify current version of PHP Type in the following to see the current PHP version:

    php -v

    Should output something like:

    PHP 5.3.3 (cli) (built: Jul 9 2015 17:39:00) Copyright (c) 1997-2010 The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies

  2. Install the Remi and EPEL RPM repositories

If you haven’t already done so, install the Remi and EPEL repositories

wget https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm && rpm -Uvh epel-release-latest-6.noarch.rpm



wget http://rpms.famillecollet.com/enterprise/remi-release-6.rpm && rpm -Uvh remi-release-6*.rpm

Enable the REMI repository globally:

nano /etc/yum.repos.d/remi.repo

Under the section that looks like [remi] make the following changes:

[remi]
name=Remi's RPM repository for Enterprise Linux 6 - $basearch
#baseurl=http://rpms.remirepo.net/enterprise/6/remi/$basearch/
mirrorlist=http://rpms.remirepo.net/enterprise/6/remi/mirror
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-remi

Also, under the section that looks like [remi-php55] make the following changes:

[remi-php56]
name=Remi's PHP 5.6 RPM repository for Enterprise Linux 6 - $basearch
#baseurl=http://rpms.remirepo.net/enterprise/6/php56/$basearch/
mirrorlist=http://rpms.remirepo.net/enterprise/6/php56/mirror
# WARNING: If you enable this repository, you must also enable "remi"
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-remi

Type CTRL-O to save and CTRL-X to close the editor

  1. Upgrade PHP 5.3 to PHP 5.6 Now we can upgrade PHP. Simply type in the following command:

    yum -y upgrade php*

Once the update has completed, let’s verify that you have PHP 5.6 installed:

php -v

Should see output similar to the following:

PHP 5.6.14 (cli) (built: Sep 30 2015 14:07:43) 
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies

Android - get children inside a View?

Here is a suggestion: you can get the ID (specified e.g. by android:id="@+id/..My Str..) which was generated by R by using its given name (e.g. My Str). A code snippet using getIdentifier() method would then be:

public int getIdAssignedByR(Context pContext, String pIdString)
{
    // Get the Context's Resources and Package Name
    Resources resources = pContext.getResources();
    String packageName  = pContext.getPackageName();

    // Determine the result and return it
    int result = resources.getIdentifier(pIdString, "id", packageName);
    return result;
}

From within an Activity, an example usage coupled with findViewById would be:

// Get the View (e.g. a TextView) which has the Layout ID of "UserInput"
int rID = getIdAssignedByR(this, "UserInput")
TextView userTextView = (TextView) findViewById(rID);

Rails filtering array of objects by attribute value

have you tried eager loading?

@attachments = Job.includes(:attachments).find(1).attachments

How to get element's width/height within directives and component?

You can use ElementRef as shown below,

DEMO : https://plnkr.co/edit/XZwXEh9PZEEVJpe0BlYq?p=preview check browser's console.

import { Directive,Input,Outpu,ElementRef,Renderer} from '@angular/core';

@Directive({
  selector:"[move]",
  host:{
    '(click)':"show()"
  }
})

export class GetEleDirective{

  constructor(private el:ElementRef){

  }
  show(){
    console.log(this.el.nativeElement);

    console.log('height---' + this.el.nativeElement.offsetHeight);  //<<<===here
    console.log('width---' + this.el.nativeElement.offsetWidth);    //<<<===here
  }
}

Same way you can use it within component itself wherever you need it.

How to use OpenFileDialog to select a folder?

this should be the most obvious and straight forward way

using (var dialog = new System.Windows.Forms.FolderBrowserDialog())
{

   System.Windows.Forms.DialogResult result = dialog.ShowDialog();

   if(result == System.Windows.Forms.DialogResult.OK)
   {
      selectedFolder = dialog.SelectedPath;
   }

}

How do I get a class instance of generic type T?

I wanted to pass T.class to a method which make use of Generics

The method readFile reads a .csv file specified by the fileName with fullpath. There can be csv files with different contents hence i need to pass the model file class so that i can get the appropriate objects. Since this is reading csv file i wanted to do in a generic way. For some reason or other none of the above solutions worked for me. I need to use Class<? extends T> type to make it work. I use opencsv library for parsing the CSV files.

private <T>List<T> readFile(String fileName, Class<? extends T> type) {

    List<T> dataList = new ArrayList<T>();
    try {
        File file = new File(fileName);

        Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        Reader headerReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

        CSVReader csvReader = new CSVReader(headerReader);
        // create csv bean reader
        CsvToBean<T> csvToBean = new CsvToBeanBuilder(reader)
                .withType(type)
                .withIgnoreLeadingWhiteSpace(true)
                .build();

        dataList = csvToBean.parse();
    }
    catch (Exception ex) {
        logger.error("Error: ", ex);
    }

    return dataList;
}

This is how the readFile method is called

List<RigSurfaceCSV> rigSurfaceCSVDataList = readSurfaceFile(surfaceFileName, RigSurfaceCSV.class);

What is CMake equivalent of 'configure --prefix=DIR && make all install '?

It is considered bad practice to invoke the actual generator (e.g. via make) if using CMake. It is highly recommended to do it like this:

  1. Configure phase:

    cmake -Hfoo -B_builds/foo/debug -G"Unix Makefiles" -DCMAKE_BUILD_TYPE=Debug -DCMAKE_DEBUG_POSTFIX=d -DCMAKE_INSTALL_PREFIX=/usr
    
  2. Build and Install phases

    cmake --build _builds/foo/debug --config Debug --target install
    

When following this approach, the generator can be easily switched (e.g. -GNinja for Ninja) without having to remember any generator-specific commands.

How to track down a "double free or corruption" error

I know this is a very old thread, but it is the top google search for this error, and none of the responses mention a common cause of the error.

Which is closing a file you've already closed.

If you're not paying attention and have two different functions close the same file, then the second one will generate this error.

Add a dependency in Maven

You'll have to do this in two steps:

1. Give your JAR a groupId, artifactId and version and add it to your repository.

If you don't have an internal repository, and you're just trying to add your JAR to your local repository, you can install it as follows, using any arbitrary groupId/artifactIds:

mvn install:install-file -DgroupId=com.stackoverflow... -DartifactId=yourartifactid... -Dversion=1.0 -Dpackaging=jar -Dfile=/path/to/jarfile

You can also deploy it to your internal repository if you have one, and want to make this available to other developers in your organization. I just use my repository's web based interface to add artifacts, but you should be able to accomplish the same thing using mvn deploy:deploy-file ....

2. Update dependent projects to reference this JAR.

Then update the dependency in the pom.xml of the projects that use the JAR by adding the following to the element:

<dependencies>
    ...
    <dependency>
        <groupId>com.stackoverflow...</groupId>
        <artifactId>artifactId...</artifactId>
        <version>1.0</version>
    </dependency>
    ...
</dependencies>

Why won't my PHP app send a 404 error?

Another solution, based on @Kitet's.

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
header("Status: 404 Not Found");

$_SERVER['REDIRECT_STATUS'] = 404;
//If you don't know which web page is in use, use any page that doesn't exists
$handle = curl_init('http://'. $_SERVER["HTTP_HOST"] .'/404missing.html');
curl_exec($handle);

If you are programming a website that hosted in a server you do not have control, you will not know which file is the "404missing.html". However you can still do this.

In this way, you provided exactly the same outcome of a normal 404 page on the same server. An observer will not be able to distinguish between an existing PHP page returns 404 and a non-existing page.

Maven home (M2_HOME) not being picked up by IntelliJ IDEA

If M2_HOME is configured to point to the Maven home directory then:

  1. Go to File -> Settings
  2. Search for Maven
  3. Select Runner
  4. Insert in the field VM Options the following string:

    Dmaven.multiModuleProjectDirectory=$M2_HOME
    

Click Apply and OK

Examples of good gotos in C or C++

Heres one trick I've heard of people using. I've never seen it in the wild though. And it only applies to C because C++ has RAII to do this more idiomatically.

void foo()
{
    if (!doA())
        goto exit;
    if (!doB())
        goto cleanupA;
    if (!doC())
        goto cleanupB;

    /* everything has succeeded */
    return;

cleanupB:
    undoB();
cleanupA:
    undoA();
exit:
    return;
}

'Framework not found' in Xcode

Please after adding both framework also open each Bolts and Parse framework and add Parse and Bolts to the project then problem will be solve

Removing multiple keys from a dictionary safely

Why not:

entriestoremove = (2,5,1)
for e in entriestoremove:
    if d.has_key(e):
        del d[e]

I don't know what you mean by "smarter way". Surely there are other ways, maybe with dictionary comprehensions:

entriestoremove = (2,5,1)
newdict = {x for x in d if x not in entriestoremove}

Postman: How to make multiple requests at the same time

If you are only doing GET requests and you need another simple solution from within your Chrome browser, just install the "Open Multiple URLs" extension:

https://chrome.google.com/webstore/detail/open-multiple-urls/oifijhaokejakekmnjmphonojcfkpbbh?hl=en

I've just ran 1500 url's at once, did lag google a bit but it works.

Create Excel file in Java

Flat files do not allow providing meta information.

I would suggest writing out a HTML table containing the information you need, and let Excel read it instead. You can then use <b> tags to do what you ask for.

How to retrieve the hash for the current commit in Git?

On git bash, simply run $ git log -1

you will see, these lines following your command.

commit d25c95d88a5e8b7e15ba6c925a1631a5357095db .. (info about your head)

d25c95d88a5e8b7e15ba6c925a1631a5357095db, is your SHA for last commit.

Material effect on button with background color

If you are interested in ImageButton you can try this simple thing :

<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@android:drawable/ic_button"
    android:background="?attr/selectableItemBackgroundBorderless"
/>

Find distance between two points on map using Google Map API V2

simple util function to calculate distance between two geopoints:

public static long getDistanceMeters(double lat1, double lng1, double lat2, double lng2) {

    double l1 = toRadians(lat1);
    double l2 = toRadians(lat2);
    double g1 = toRadians(lng1);
    double g2 = toRadians(lng2);

    double dist = acos(sin(l1) * sin(l2) + cos(l1) * cos(l2) * cos(g1 - g2));
    if(dist < 0) {
        dist = dist + Math.PI;
    }

    return Math.round(dist * 6378100);
}

How to allocate aligned memory only using the standard library?

You could also try posix_memalign() (on POSIX platforms, of course).

dyld: Library not loaded: @rpath/libswiftCore.dylib

I solved by deleting the derived data and this time it worked correctly. Tried with Xcode 7.3.1GM

How To Run PHP From Windows Command Line in WAMPServer

The following solution is specifically for wamp environments:

This foxed me for a little while, tried all the other suggestions, $PATH etc even searched the windows registry looking for clues:

The GUI (wampmanager) indicates I have version 7 selected and yes if I phpinfo() in a page in the browser it will tell me its version 7.x.x yet php -v in the command prompt reports a 5.x.x

If you right click on the wampmanager head to icon->tools->delete unused versions and remove the old version, let it restart the services then the command prompt will return a 7.x.x

This solution means you no longer have the old version if you want to switch between php versions but there is a configuration file in C:\wamp64\wampmanager.conf which appears to specify the version to use with CLI (the parameter is called phpCliVersion). I changed it, restarted the server ... thought I had solved it but no effect perhaps I was a little impatient so I have a feeling there may be some mileage in that.

Hope that helps someone

PHP float with 2 decimal places: .00

You can use this simple function. number_format ()

    $num = 2214.56;

    // default english notation
    $english_format = number_format($num);
    // 2,215

    // French notation
    $format_francais = number_format($num, 2, ',', ' ');
    // 2 214,56

    $num1 = 2234.5688;

   // English notation with thousands separator
    $english_format_number = number_format($num1,2);
    // 2,234.57

    // english notation without thousands separator
    $english_format_number2 = number_format($num1, 2, '.', '');
    // 2234.57

How to calculate combination and permutation in R?

You can use the combinat package with R 2.13:

install.packages("combinat")
require(combinat)
permn(3)
combn(3, 2)

If you want to know the number of combination/permutations, then check the size of the result, e.g.:

length(permn(3))
dim(combn(3,2))[2]

How to use Lambda in LINQ select statement

Lambda Expression result

var storesList = context.Stores.Select(x => new { Value= x.name,Text= x.ID }).ToList();

How to convert wstring into string?

In my case, I have to use multibyte character (MBCS), and I want to use std::string and std::wstring. And can't use c++11. So I use mbstowcs and wcstombs.

I make same function with using new, delete [], but it is slower then this.

This can help How to: Convert Between Various String Types

EDIT

However, in case of converting to wstring and source string is no alphabet and multi byte string, it's not working. So I change wcstombs to WideCharToMultiByte.

#include <string>

std::wstring get_wstr_from_sz(const char* psz)
{
    //I think it's enough to my case
    wchar_t buf[0x400];
    wchar_t *pbuf = buf;
    size_t len = strlen(psz) + 1;

    if (len >= sizeof(buf) / sizeof(wchar_t))
    {
        pbuf = L"error";
    }
    else
    {
        size_t converted;
        mbstowcs_s(&converted, buf, psz, _TRUNCATE);
    }

    return std::wstring(pbuf);
}

std::string get_string_from_wsz(const wchar_t* pwsz)
{
    char buf[0x400];
    char *pbuf = buf;
    size_t len = wcslen(pwsz)*2 + 1;

    if (len >= sizeof(buf))
    {
        pbuf = "error";
    }
    else
    {
        size_t converted;
        wcstombs_s(&converted, buf, pwsz, _TRUNCATE);
    }

    return std::string(pbuf);
}

EDIT to use 'MultiByteToWideChar' instead of 'wcstombs'

#include <Windows.h>
#include <boost/shared_ptr.hpp>
#include "string_util.h"

std::wstring get_wstring_from_sz(const char* psz)
{
    int res;
    wchar_t buf[0x400];
    wchar_t *pbuf = buf;
    boost::shared_ptr<wchar_t[]> shared_pbuf;

    res = MultiByteToWideChar(CP_ACP, 0, psz, -1, buf, sizeof(buf)/sizeof(wchar_t));

    if (0 == res && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
    {
        res = MultiByteToWideChar(CP_ACP, 0, psz, -1, NULL, 0);

        shared_pbuf = boost::shared_ptr<wchar_t[]>(new wchar_t[res]);

        pbuf = shared_pbuf.get();

        res = MultiByteToWideChar(CP_ACP, 0, psz, -1, pbuf, res);
    }
    else if (0 == res)
    {
        pbuf = L"error";
    }

    return std::wstring(pbuf);
}

std::string get_string_from_wcs(const wchar_t* pcs)
{
    int res;
    char buf[0x400];
    char* pbuf = buf;
    boost::shared_ptr<char[]> shared_pbuf;

    res = WideCharToMultiByte(CP_ACP, 0, pcs, -1, buf, sizeof(buf), NULL, NULL);

    if (0 == res && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
    {
        res = WideCharToMultiByte(CP_ACP, 0, pcs, -1, NULL, 0, NULL, NULL);

        shared_pbuf = boost::shared_ptr<char[]>(new char[res]);

        pbuf = shared_pbuf.get();

        res = WideCharToMultiByte(CP_ACP, 0, pcs, -1, pbuf, res, NULL, NULL);
    }
    else if (0 == res)
    {
        pbuf = "error";
    }

    return std::string(pbuf);
}

Add Keypair to existing EC2 instance

On your local machine, run command:

ssh-keygen -t rsa -C "SomeAlias"

After that command runs, a file ending in *.pub will be generated. Copy the contents of that file.

On the Amazon machine, edit ~/.ssh/authorized_keys and paste the contents of the *.pub file (and remove any existing contents first).

You can then SSH using the other file that was generated from the ssh-keygen command (the private key).

How do I download a file from the internet to my linux server with Bash

Using wget

wget -O /tmp/myfile 'http://www.google.com/logo.jpg'

or curl:

curl -o /tmp/myfile 'http://www.google.com/logo.jpg'

How to call an async method from a getter or setter?

I think that we can await for the value just returning first null and then get the real value, so in the case of Pure MVVM (PCL project for instance) I think the following is the most elegant solution:

private IEnumerable myList;
public IEnumerable MyList
{
  get
    { 
      if(myList == null)
         InitializeMyList();
      return myList;
     }
  set
     {
        myList = value;
        NotifyPropertyChanged();
     }
}

private async void InitializeMyList()
{
   MyList = await AzureService.GetMyList();
}

How do you add swap to an EC2 instance?

Swap should take place on the Instance Storage (ephemeral) disk and not an EBS device. Swapping will cause a lot of IO and will increase cost on EBS. EBS is also slower than the Instance Store and the Instance Store comes free with certain types of EC2 Instances.

It will usually be mounted to /mnt but if not run

sudo mount /dev/xvda2 /mnt

To then create a swap file on this device do the following for a 4GB swapfile

sudo dd if=/dev/zero of=/mnt/swapfile bs=1M count=4096

Make sure no other user can view the swap file

sudo chown root:root /mnt/swapfile
sudo chmod 600 /mnt/swapfile

Make and Flag as swap

sudo mkswap /mnt/swapfile
sudo swapon /mnt/swapfile

Add/Make sure the following are in your /etc/fstab

/dev/xvda2      /mnt    auto    defaults,nobootwait,comment=cloudconfig 0   2
/mnt/swapfile swap swap defaults 0 0

lastly enable swap

sudo swapon -a

Scanner is never closed

I am assuming you are using java 7, thus you get a compiler warning, when you don't close the resource you should close your scanner usually in a finally block.

Scanner scanner = null;
try {
    scanner = new Scanner(System.in);
    //rest of the code
}
finally {
    if(scanner!=null)
        scanner.close();
}

Or even better: use the new Try with resource statement:

try(Scanner scanner = new Scanner(System.in)){
    //rest of your code
}

input[type='text'] CSS selector does not apply to default-type text inputs?

try this

 input[type='text']
 {
   background:red !important;
 }

Valid content-type for XML, HTML and XHTML documents

HTML: text/html, full-stop.

XHTML: application/xhtml+xml, or only if following HTML compatbility guidelines, text/html. See the W3 Media Types Note.

XML: text/xml, application/xml (RFC 2376).

There are also many other media types based around XML, for example application/rss+xml or image/svg+xml. It's a safe bet that any unrecognised but registered ending in +xml is XML-based. See the IANA list for registered media types ending in +xml.

(For unregistered x- types, all bets are off, but you'd hope +xml would be respected.)

Where can I find the Tomcat 7 installation folder on Linux AMI in Elastic Beanstalk?

As of October 3, 2012, a new "Elastic Beanstalk for Java with Apache Tomcat 7" Linux x64 AMI deployed with the Sample Application has the install here:

/etc/tomcat7/

The /etc/tomcat7/tomcat7.conf file has the following settings:

# Where your java installation lives
JAVA_HOME="/usr/lib/jvm/jre"

# Where your tomcat installation lives
CATALINA_BASE="/usr/share/tomcat7"
CATALINA_HOME="/usr/share/tomcat7"
JASPER_HOME="/usr/share/tomcat7"
CATALINA_TMPDIR="/var/cache/tomcat7/temp"

How can I copy the content of a branch to a new local branch?

git branch copyOfMyBranch MyBranch

This avoids the potentially time-consuming and unnecessary act of checking out a branch. Recall that a checkout modifies the "working tree", which could take a long time if it is large or contains large files (images or videos, for example).

Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?

I thought Activity was deprecated

No.

So for API Level 22 (with a minimum support for API Level 15 or 16), what exactly should I use both to host the components, and for the components themselves? Are there uses for all of these, or should I be using one or two almost exclusively?

Activity is the baseline. Every activity inherits from Activity, directly or indirectly.

FragmentActivity is for use with the backport of fragments found in the support-v4 and support-v13 libraries. The native implementation of fragments was added in API Level 11, which is lower than your proposed minSdkVersion values. The only reason why you would need to consider FragmentActivity specifically is if you want to use nested fragments (a fragment holding another fragment), as that was not supported in native fragments until API Level 17.

AppCompatActivity is from the appcompat-v7 library. Principally, this offers a backport of the action bar. Since the native action bar was added in API Level 11, you do not need AppCompatActivity for that. However, current versions of appcompat-v7 also add a limited backport of the Material Design aesthetic, in terms of the action bar and various widgets. There are pros and cons of using appcompat-v7, well beyond the scope of this specific Stack Overflow answer.

ActionBarActivity is the old name of the base activity from appcompat-v7. For various reasons, they wanted to change the name. Unless some third-party library you are using insists upon an ActionBarActivity, you should prefer AppCompatActivity over ActionBarActivity.

So, given your minSdkVersion in the 15-16 range:

  • If you want the backported Material Design look, use AppCompatActivity

  • If not, but you want nested fragments, use FragmentActivity

  • If not, use Activity

Just adding from comment as note: AppCompatActivity extends FragmentActivity, so anyone who needs to use features of FragmentActivity can use AppCompatActivity.

Is there a way to create and run javascript in Chrome?

if you don't want to create an explicitly a js file but still want to test your javascript code, you can use snippets to run your JS code.

Follow the steps here:

  1. Open Dev Tools
  2. Go to Sources Tab
  3. Under Sources tab go to snippets, + New snippet
  4. Past your JS code in the editor then run command + enter in Mac. You should see the output in console if you are using console.log or similar to test. You can edit the current web page that you have open or run scripts, load more javascript files. (Just note: this snippets are not stored on as a js file, unless you explicitly did, on your computer so if you remove chrome you will lose all your snippets);
  5. You also have a option to save as your snippet if you right click on your snippet.

code javascript using snippets in dev tools

How to enable copy paste from between host machine and virtual machine in vmware, virtual machine is ubuntu

the mremote option offers more automation and almost replicates the vmware workstation graphical experience plus major benefits: NO DPI (guest resolution) hassle no copy pose hassle Automation = starting vms and suspending them automatically plus more if you look deeper

Sass nth-child nesting

I'd be careful about trying to get too clever here. I think it's confusing as it is and using more advanced nth-child parameters will only make it more complicated. As for the background color I'd just set that to a variable.

Here goes what I came up with before I realized trying to be too clever might be a bad thing.

#romtest {
 $bg: #e5e5e5;
 .detailed {
    th {
      &:nth-child(-2n+6) {
        background-color: $bg;
      }
    }
    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        background-color: $bg;
      }
      &.last {
        &:nth-child(-2n+4){
          background-color: $bg;
        }
      }
    }
  }
}

and here is a quick demo: http://codepen.io/anon/pen/BEImD

----EDIT----

Here's another approach to avoid retyping background-color:

#romtest {
  %highlight {
    background-color: #e5e5e5; 
  }
  .detailed {
    th {
      &:nth-child(-2n+6) {
        @extend %highlight;
      }
    }

    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        @extend %highlight;
      }
      &.last {
        &:nth-child(-2n+4){
          @extend %highlight;
        }
      }
    }
  }
}

Printing a char with printf

This is supposed to print the ASCII value of the character, as %d is the escape sequence for an integer. So the value given as argument of printf is taken as integer when printed.

char ch = 'a';
printf("%d", ch);

Same holds for printf("%d", '\0');, where the NULL character is interpreted as the 0 integer.

Finally, sizeof('\n') is 4 because in C, this notation for characters stands for the corresponding ASCII integer. So '\n' is the same as 10 as an integer.

It all depends on the interpretation you give to the bytes.

Error: invalid operands of types ‘const char [35]’ and ‘const char [2]’ to binary ‘operator+’

Consider this:

std::string str = "Hello " + "world"; // bad!

Both the rhs and the lhs for operator + are char*s. There is no definition of operator + that takes two char*s (in fact, the language doesn't permit you to write one). As a result, on my compiler this produces a "cannot add two pointers" error (yours apparently phrases things in terms of arrays, but it's the same problem).

Now consider this:

std::string str = "Hello " + std::string("world"); // ok

There is a definition of operator + that takes a const char* as the lhs and a std::string as the rhs, so now everyone is happy.

You can extend this to as long a concatenation chain as you like. It can get messy, though. For example:

std::string str = "Hello " + "there " + std::string("world"); // no good!

This doesn't work because you are trying to + two char*s before the lhs has been converted to std::string. But this is fine:

std::string str = std::string("Hello ") + "there " + "world"; // ok

Because once you've converted to std::string, you can + as many additional char*s as you want.

If that's still confusing, it may help to add some brackets to highlight the associativity rules and then replace the variable names with their types:

((std::string("Hello ") + "there ") + "world");
((string + char*) + char*)

The first step is to call string operator+(string, char*), which is defined in the standard library. Replacing those two operands with their result gives:

((string) + char*)

Which is exactly what we just did, and which is still legal. But try the same thing with:

((char* + char*) + string)

And you're stuck, because the first operation tries to add two char*s.

Moral of the story: If you want to be sure a concatenation chain will work, just make sure one of the first two arguments is explicitly of type std::string.

A cron job for rails: best practices?

I use backgroundrb.

http://backgroundrb.rubyforge.org/

I use it to run scheduled tasks as well as tasks that take too long for the normal client/server relationship.

How can I select checkboxes using the Selenium Java WebDriver?

You can use the following code:

List<WebElement> checkbox = driver.findElements(By.name("vehicle"));
((WebElement) checkbox.get(0)).click();

My HTML code was as follows:

<.input type="checkbox" name="vehicle" value="Bike">I have a bike<br/>
<.input type="checkbox" name="vehicle" value="Car">I have a car<br/>

What's Mongoose error Cast to ObjectId failed for value XXX at path "_id"?

I had the same error, but in a different situation than in the question, but maybe it will be useful to someone.

The problem was adding buckles:

Wrong:

    const gamesArray = [myId];

    const player = await Player.findByIdAndUpdate(req.player._id, {
         gamesId: [gamesArray]
    }, { new: true }

Correct:

    const gamesArray = [myId];

    const player = await Player.findByIdAndUpdate(req.player._id, {
         gamesId: gamesArray
    }, { new: true }

Python reading from a file and saving to utf-8

You can also get through it by the code below:

file=open(completefilepath,'r',encoding='utf8',errors="ignore")
file.read()

What does $(function() {} ); do?

$(function() { ... });

is just jQuery short-hand for

$(document).ready(function() { ... });

What it's designed to do (amongst other things) is ensure that your function is called once all the DOM elements of the page are ready to be used.

However, I don't think that's the problem you're having - can you clarify what you mean by 'Somehow, some functions are cannot be called and I have to call those function inside' ? Maybe post some code to show what's not working as expected ?

Edit: Re-reading your question, it could be that your function is running before the page has finished loaded, and therefore won't execute properly; putting it in $(function) would indeed fix that!

Bootstrap Collapse not Collapsing

jQuery is required ;-)

DEMO

<html>
<head>
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <!-- THIS LINE -->
    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
</head>
<body>

<div class="panel-group" id="accordion">
    <div class="panel panel-default">
        <div class="panel-heading">
            <h4 class="panel-title">
                <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
                    Collapsible Group Item #1
                </a>
            </h4>
        </div>
        <div id="collapseOne" class="panel-collapse collapse in">
            <div class="panel-body">
                Anim pariatur cliche reprehenderit
            </div>
        </div>
    </div>
</div>

</body>
</html>

How can I upload fresh code at github?

git init
git add .
git commit -m "Initial commit"

After this, make a new GitHub repository and follow on-screen instructions.

How to set a hidden value in Razor

While I would have gone with Piotr's answer (because it's all in one line), I was surprised that your sample is closer to your solution than you think. From what you have, you simply assign the model value before you use the Html helper method.

@{Model.RequiredProperty = "default";}
@Html.HiddenFor(model => model.RequiredProperty)

Render HTML string as real HTML in a React component

If you have control over where the string containing html is coming from (ie. somewhere in your app), you can benefit from the new <Fragment> API, doing something like:

import React, {Fragment} from 'react'

const stringsSomeWithHtml = {
  testOne: (
    <Fragment>
      Some text <strong>wrapped with strong</strong>
    </Fragment>
  ),
  testTwo: `This is just a plain string, but it'll print fine too`,
}

...

render() {
  return <div>{stringsSomeWithHtml[prop.key]}</div>
}

XSLT getting last element

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

(//element[@name='D'])[last()]

How can I hide select options with JavaScript? (Cross browser)

Hiding an <option> element is not in the spec. But you can disable them, which should work cross-browser.

$('option.hide').prop('disabled', true);

http://www.w3.org/TR/html401/interact/forms.html#h-17.6

How to reload .bashrc settings without logging out and back in again?

Assuming an interactive shell, and you'd like to keep your current command history and also load /etc/profile (which loads environment data including /etc/bashrc and on Mac OS X loads paths defined in /etc/paths.d/ via path_helper), append your command history and do an exec of bash with the login ('-l') option:

history -a && exec bash -l

How to get the file name from a full path using JavaScript?

Little function to include in your project to determine the filename from a full path for Windows as well as GNU/Linux & UNIX absolute paths.

/**
 * @param {String} path Absolute path
 * @return {String} File name
 * @todo argument type checking during runtime
 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf
 * @example basename('/home/johndoe/github/my-package/webpack.config.js') // "webpack.config.js"
 * @example basename('C:\\Users\\johndoe\\github\\my-package\\webpack.config.js') // "webpack.config.js"
 */
function basename(path) {
  let separator = '/'

  const windowsSeparator = '\\'

  if (path.includes(windowsSeparator)) {
    separator = windowsSeparator
  }

  return path.slice(path.lastIndexOf(separator) + 1)
}

Deserializing JSON to .NET object using Newtonsoft (or LINQ to JSON maybe?)

If you just need to get a few items from the JSON object, I would use Json.NET's LINQ to JSON JObject class. For example:

JToken token = JObject.Parse(stringFullOfJson);

int page = (int)token.SelectToken("page");
int totalPages = (int)token.SelectToken("total_pages");

I like this approach because you don't need to fully deserialize the JSON object. This comes in handy with APIs that can sometimes surprise you with missing object properties, like Twitter.

Documentation: Serializing and Deserializing JSON with Json.NET and LINQ to JSON with Json.NET

combining results of two select statements

Probably you use Microsoft SQL Server which support Common Table Expressions (CTE) (see http://msdn.microsoft.com/en-us/library/ms190766.aspx) which are very friendly for query optimization. So I suggest you my favor construction:

WITH GetNumberOfPlans(Id,NumberOfPlans) AS (
    SELECT tableA.Id, COUNT(tableC.Id)
    FROM tableC
        RIGHT OUTER JOIN tableA ON tableC.tableAId = tableA.Id
    GROUP BY tableA.Id
),GetUserInformation(Id,Name,Owner,ImageUrl,
                     CompanyImageUrl,NumberOfUsers) AS (
    SELECT tableA.Id, tableA.Name, tableB.Username AS Owner, tableB.ImageUrl,
        tableB.CompanyImageUrl,COUNT(tableD.UserId),p.NumberOfPlans
    FROM tableA
        INNER JOIN tableB ON tableB.Id = tableA.Owner
        RIGHT OUTER JOIN tableD ON tableD.tableAId = tableA.Id
    GROUP BY tableA.Name, tableB.Username, tableB.ImageUrl, tableB.CompanyImageUrl
)
SELECT u.Id,u.Name,u.Owner,u.ImageUrl,u.CompanyImageUrl
    ,u.NumberOfUsers,p.NumberOfPlans
FROM GetUserInformation AS u
    INNER JOIN GetNumberOfPlans AS p ON p.Id=u.Id

After some experiences with CTE you will be find very easy to write code using CTE and you will be happy with the performance.

NSDictionary - Need to check whether dictionary contains key-value pair or not

Just ask it for the objectForKey:@"b". If it returns nil, no object is set at that key.

if ([xyz objectForKey:@"b"]) {
    NSLog(@"There's an object set for key @\"b\"!");
} else {
    NSLog(@"No object set for key @\"b\"");
}

Edit: As to your edited second question, it's simply NSUInteger mCount = [xyz count];. Both of these answers are documented well and easily found in the NSDictionary class reference ([1] [2]).

How to perform a for-each loop over all the files under a specified path?

Here is a better way to loop over files as it handles spaces and newlines in file names:

#!/bin/bash

find . -type f -iname "*.txt" -print0 | while IFS= read -r -d $'\0' line; do
    echo "$line"
    ls -l "$line"    
done

Regular expression for not allowing spaces in the input field

If you're using some plugin which takes string and use construct Regex to create Regex Object i:e new RegExp()

Than Below string will work

'^\\S*$'

It's same regex @Bergi mentioned just the string version for new RegExp constructor

How to import existing *.sql files in PostgreSQL 8.4?

Always preferred using a connection service file (lookup/google 'psql connection service file')

Then simply:

psql service={yourservicename} < {myfile.sql}

Where yourservicename is a section name from the service file.

how to parse xml to java object?

One thing that is really important to understand considering you have an XML file as :

<customer id="100">
    <Age>29</Age>
    <NAME>mkyong</NAME>
</customer>

I am sorry to inform you but :

@XmlElement
public void setAge(int age) {
    this.age = age;
}

will not help you, as it tries to look for "age" instead of "Age" element name from the XML.

I encourage you to manually specify the element name matching the one in the XML file :

@XmlElement(name="Age")
public void setAge(int age) {
    this.age = age;
}

And if you have for example :

@XmlRootElement
@XmlAccessorType (XmlAccessType.FIELD)
public class Customer {
...

It means it will use java beans by default, and at this time if you specify that you must not set another

@XmlElement(name="NAME")

annotation above a setter method for an element <NAME>..</NAME> it will fail saying that there cannot be two elements on one single variables.

I hope that it helps.

Maximum number of threads per process in Linux?

Use nbio non-blocking i/o library or whatever, if you need more threads for doing I/O calls that block

Is there a way to crack the password on an Excel VBA Project?

VBA Project Passwords on Access, Excel, Powerpoint, or Word documents (2007, 2010, 2013 or 2016 versions with extensions .ACCDB .XLSM .XLTM .DOCM .DOTM .POTM .PPSM) can be easily removed.

It's simply a matter of changing the filename extension to .ZIP, unzipping the file, and using any basic Hex Editor (like XVI32) to "break" the existing password, which "confuses" Office so it prompts for a new password next time the file is opened.

A summary of the steps:

  • rename the file so it has a .ZIP extension.
  • open the ZIP and go to the XL folder.
  • extract vbaProject.bin and open it with a Hex Editor
  • "Search & Replace" to "replace all" changing DPB to DPX.
  • Save changes, place the .bin file back into the zip, return it to it's normal extension and open the file like normal.
  • ALT+F11 to enter the VB Editor and right-click in the Project Explorer to choose VBA Project Properties.
  • On the Protection tab, Set a new password.
  • Click OK, Close the file, Re-open it, hit ALT+F11.
  • Enter the new password that you set.

At this point you can remove the password completely if you choose to.

Complete instructions with a step-by-step video I made "way back when" are on YouTube here.

It's kind of shocking that this workaround has been out there for years, and Microsoft hasn't fixed the issue.


The moral of the story?

Microsoft Office VBA Project passwords are not to be relied upon for security of any sensitive information. If security is important, use third-party encryption software.

Get the Year/Month/Day from a datetime in php?

Check out the manual: http://www.php.net/manual/en/datetime.format.php

<?php
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>

Will output: 2000-01-01 00:00:00

Convert string to JSON Object

Enclose the string in single quote it should work. Try this.

var jsonObj = '{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}';
var obj = $.parseJSON(jsonObj);

Demo

Assert that a method was called in a Python unit test

I'm not aware of anything built-in. It's pretty simple to implement:

class assertMethodIsCalled(object):
    def __init__(self, obj, method):
        self.obj = obj
        self.method = method

    def called(self, *args, **kwargs):
        self.method_called = True
        self.orig_method(*args, **kwargs)

    def __enter__(self):
        self.orig_method = getattr(self.obj, self.method)
        setattr(self.obj, self.method, self.called)
        self.method_called = False

    def __exit__(self, exc_type, exc_value, traceback):
        assert getattr(self.obj, self.method) == self.called,
            "method %s was modified during assertMethodIsCalled" % self.method

        setattr(self.obj, self.method, self.orig_method)

        # If an exception was thrown within the block, we've already failed.
        if traceback is None:
            assert self.method_called,
                "method %s of %s was not called" % (self.method, self.obj)

class test(object):
    def a(self):
        print "test"
    def b(self):
        self.a()

obj = test()
with assertMethodIsCalled(obj, "a"):
    obj.b()

This requires that the object itself won't modify self.b, which is almost always true.

Passing parameters to click() & bind() event in jquery?

var someParam = xxxxxxx;

commentbtn.click(function(){

    alert(someParam );
});

Emulate/Simulate iOS in Linux

You might want to try screenfly. It worked great for me.

How to destroy Fragment?

It's used in Kotlin

appCompatActivity?.getSupportFragmentManager()?.popBackStack()