Programs & Examples On #Project settings

C - split string into an array of strings

Since you've already looked into strtok just continue down the same path and split your string using space (' ') as a delimiter, then use something as realloc to increase the size of the array containing the elements to be passed to execvp.

See the below example, but keep in mind that strtok will modify the string passed to it. If you don't want this to happen you are required to make a copy of the original string, using strcpy or similar function.

char    str[]= "ls -l";
char ** res  = NULL;
char *  p    = strtok (str, " ");
int n_spaces = 0, i;


/* split string and append tokens to 'res' */

while (p) {
  res = realloc (res, sizeof (char*) * ++n_spaces);

  if (res == NULL)
    exit (-1); /* memory allocation failed */

  res[n_spaces-1] = p;

  p = strtok (NULL, " ");
}

/* realloc one extra element for the last NULL */

res = realloc (res, sizeof (char*) * (n_spaces+1));
res[n_spaces] = 0;

/* print the result */

for (i = 0; i < (n_spaces+1); ++i)
  printf ("res[%d] = %s\n", i, res[i]);

/* free the memory allocated */

free (res);

res[0] = ls
res[1] = -l
res[2] = (null)

Can you target <br /> with css?

br { padding: 1px 8px; border-bottom: 1px dashed #000 }

renders as below in IE8... not a lot of use in just one browser though.

IE 8 screenshot

(N.B. I'm using IE 8.0.7100 (on Win7 RC) if that makes any difference)

Also,

br:after { content: "..." }  
br { content: "" }`

or,

br:after {
    border: 1px none black;
    border-bottom-style: dashed;
    content: "";
    padding: 0 6px 0;
}

br { content: "" }

gives a dashed line in Chrome 2 / Safari 4b but loses the line break which (unless anyone can come up with a way to reintroduce that) makes it less than useless.

e.g.
IE8 test, Chrome/Safari test and another

Check if element at position [x] exists in the list

if(list.ElementAtOrDefault(2) != null)
{
   // logic
}

ElementAtOrDefault() is part of the System.Linq namespace.

Although you have a List, so you can use list.Count > 2.

Jquery sortable 'change' event element position

UPDATED: 26/08/2016 to use the latest jquery and jquery ui version plus bootstrap to style it.

$(function() {
    $('#sortable').sortable({
        start: function(event, ui) {
            var start_pos = ui.item.index();
            ui.item.data('start_pos', start_pos);
        },
        change: function(event, ui) {
            var start_pos = ui.item.data('start_pos');
            var index = ui.placeholder.index();
            if (start_pos < index) {
                $('#sortable li:nth-child(' + index + ')').addClass('highlights');
            } else {
                $('#sortable li:eq(' + (index + 1) + ')').addClass('highlights');
            }
        },
        update: function(event, ui) {
            $('#sortable li').removeClass('highlights');
        }
    });
});

Install Android App Bundle on device

Use (on Linux): cd android ./gradlew assemblyRelease|assemblyDebug

An unsigned APK is generated for each case (for debug or testing)

NOTE: On Windows, replace gradle executable for gradlew.bat

How to printf "unsigned long" in C?

For int %d

For long int %ld

For long long int %lld

For unsigned long long int %llu

Is it ok having both Anacondas 2.7 and 3.5 installed in the same time?

Anaconda is made for the purpose you are asking. It is also an environment manager. It separates out environments. It was made because stable and legacy packages were not supported with newer/unstable versions of host languages; therefore a software was required that could separate and manage these versions on the same machine without the need to reinstall or uninstall individual host programming languages/environments.

You can find creation/deletion of environments in the Anaconda documentation.

Hope this helped.

How do I check if PHP is connected to a database already?

before... (I mean somewhere in some other file you're not sure you've included)

$db = mysql_connect()

later...

if (is_resource($db)) {
// connected
} else {
$db = mysql_connect();
}

Control cannot fall through from one case label

You can do more than just fall through in C#, but you must utilize the "dreaded" goto statement. For example:

switch (whatever)
{
  case 2:
    Result.Write( "Subscribe" );
    break;
  case 1:
    Result.Write( "Un" );
    goto case 2;
}

Customize list item bullets using CSS

This method moves the disc out of the text flow where the original disc was, but is adjustable.

ul{
    list-style-type: none;
    
    li{ 
        position: relative;
      }
    li:before {
        position: absolute;
        top: .1rem;
        left: -.8em;
        content: '\2022';
        font-size: 1.2rem;
    }
}

Convert object array to hash map, indexed by an attribute value of the Object

Using ES6 spread + Object.assign:

array = [{key: 'a', value: 'b', redundant: 'aaa'}, {key: 'x', value: 'y', redundant: 'zzz'}]

const hash = Object.assign({}, ...array.map(s => ({[s.key]: s.value})));

console.log(hash) // {a: b, x: y}

Python's equivalent of && (logical-and) in an if-statement

Two comments:

  • Use and and or for logical operations in Python.
  • Use 4 spaces to indent instead of 2. You will thank yourself later because your code will look pretty much the same as everyone else's code. See PEP 8 for more details.

Count number of iterations in a foreach loop

count($Contents);

or

sizeof($Contents);

Make: how to continue after a command fails?

make -k (or --keep-going on gnumake) will do what you are asking for, I think.

You really ought to find the del or rm line that is failing and add a -f to it to keep that error from happening to others though.

How to create strings containing double quotes in Excel formulas?

Three double quotes: " " " x " " " = "x" Excel will auto change to one double quote. e.g.:

=CONCATENATE("""x"""," hi")  

= "x" hi

How to get all the values of input array element jquery

Use:

function getvalues(){
var inps = document.getElementsByName('pname[]');
for (var i = 0; i <inps.length; i++) {
var inp=inps[i];
    alert("pname["+i+"].value="+inp.value);
}
}

Here is Demo.

HTML form with two submit buttons and two "target" attributes

Simple and easy to understand, this will send the name of the button that has been clicked, then will branch off to do whatever you want. This can reduce the need for two targets. Less pages...!

<form action="twosubmits.php" medthod ="post">
<input type = "text" name="text1">

<input type="submit"  name="scheduled" value="Schedule Emails">
<input type="submit"  name="single" value="Email Now">
</form>

twosubmits.php

<?php
if (empty($_POST['scheduled'])) {
// do whatever or collect values needed
die("You pressed single");
}

if (empty($_POST['single'])) {
// do whatever or collect values needed
die("you pressed scheduled");
}
?>

Add a property to a JavaScript object using a variable as the name?

With the advent of ES2015 Object.assign and computed property names the OP's code boils down to:

var obj = Object.assign.apply({}, $(itemsFromDom).map((i, el) => ({[el.id]: el.value})));

How to get Android crash logs?

Base on this POST, use this class as replacement of "TopExceptionHandler"

class TopExceptionHandler implements Thread.UncaughtExceptionHandler {
private Thread.UncaughtExceptionHandler defaultUEH;
private Activity app = null;
private String line;

public TopExceptionHandler(Activity app) {
    this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
    this.app = app;
}

public void uncaughtException(Thread t, Throwable e) {




    StackTraceElement[] arr = e.getStackTrace();
    String report = e.toString()+"\n\n";
    report += "--------- Stack trace ---------\n\n";
    for (int i=0; i<arr.length; i++) {
        report += "    "+arr[i].toString()+"\n";
    }
    report += "-------------------------------\n\n";

    // If the exception was thrown in a background thread inside
    // AsyncTask, then the actual exception can be found with getCause

    report += "--------- Cause ---------\n\n";
    Throwable cause = e.getCause();
    if(cause != null) {
        report += cause.toString() + "\n\n";
        arr = cause.getStackTrace();
        for (int i=0; i<arr.length; i++) {
            report += "    "+arr[i].toString()+"\n";
        }
    }
    report += "-------------------------------\n\n";

    try {
        FileOutputStream trace = app.openFileOutput("stack.trace",
                Context.MODE_PRIVATE);
        trace.write(report.getBytes());
        trace.close();



        Intent i = new Intent(Intent.ACTION_SEND);
        i.setType("message/rfc822");
        i.putExtra(Intent.EXTRA_EMAIL  , new String[]{"[email protected]"});
        i.putExtra(Intent.EXTRA_SUBJECT, "crash report azar");
        String body = "Mail this to [email protected]: " + "\n" + trace + "\n";
        i.putExtra(Intent.EXTRA_TEXT   , body);
        try {
            startActivity(Intent.createChooser(i, "Send mail..."));
        } catch (android.content.ActivityNotFoundException ex) {
           // Toast.makeText(MyActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
        }






      //  ReaderScopeActivity.this.startActivity(Intent.createChooser(sendIntent, "Title:"));

        //ReaderScopeActivity.this.deleteFile("stack.trace");

    } catch(IOException ioe) {
        // ...
    }

    defaultUEH.uncaughtException(t, e);
}

private void startActivity(Intent chooser) {
}

}

.....

in same java class file (Activity) .....

Public class MainActivity.....

.....

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Thread.setDefaultUncaughtExceptionHandler(new TopExceptionHandler(this));

.....

Add a custom attribute to a Laravel / Eloquent model on load?

you can use setAttribute function in Model to add a custom attribute

Is there any way to start with a POST request using Selenium?

One very practical way to do this is to create a dummy start page for your tests that is simply a form with POST that has a single "start test" button and a bunch of <input type="hidden"... elements with the appropriate post data.

For example you might create a SeleniumTestStart.html page with these contents:

<body>
  <form action="/index.php" method="post">
    <input id="starttestbutton" type="submit" value="starttest"/>
    <input type="hidden" name="stageid" value="stage-you-need-your-test-to-start-at"/>
  </form>
</body>

In this example, index.php is where your normal web app is located.

The Selenium code at the start of your tests would then include:

open /SeleniumTestStart.html
clickAndWait starttestbutton

This is very similar to other mock and stub techniques used in automated testing. You are just mocking the entry point to the web app.

Obviously there are some limitations to this approach:

  1. data cannot be too large (e.g. image data)
  2. security might be an issue so you need to make sure that these test files don't end up on your production server
  3. you may need to make your entry points with something like php instead of html if you need to set cookies before the Selenium test gets going
  4. some web apps check the referrer to make sure someone isn't hacking the app - in this case this approach probably won't work - you may be able to loosen this checking in a dev environment so it allows referrers from trusted hosts (not self, but the actual test host)

Please consider reading my article about the Qualities of an Ideal Test

Break statement in javascript array map method

That's not possible using the built-in Array.prototype.map. However, you could use a simple for-loop instead, if you do not intend to map any values:

var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
  if (myArray[i] < 10) {
    hasValueLessThanTen = true;
    break;
  }
}

Or, as suggested by @RobW, use Array.prototype.some to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:

var hasValueLessThanTen = myArray.some(function (val) { 
  return val < 10;
});

Best way to get the max value in a Spark dataframe column

First add the import line:

from pyspark.sql.functions import min, max

To find the min value of age in the dataframe:

df.agg(min("age")).show()

+--------+
|min(age)|
+--------+
|      29|
+--------+

To find the max value of age in the dataframe:

df.agg(max("age")).show()

+--------+
|max(age)|
+--------+
|      77|
+--------+

Writelines writes lines without newline, Just fills the file

As others have mentioned, and counter to what the method name would imply, writelines does not add line separators. This is a textbook case for a generator. Here is a contrived example:

def item_generator(things):
    for item in things:
        yield item
        yield '\n'

def write_things_to_file(things):
    with open('path_to_file.txt', 'wb') as f:
        f.writelines(item_generator(things))

Benefits: adds newlines explicitly without modifying the input or output values or doing any messy string concatenation. And, critically, does not create any new data structures in memory. IO (writing to a file) is when that kind of thing tends to actually matter. Hope this helps someone!

Getting the encoding of a Postgres database

If you want to get database encodings:

psql  -U postgres -h somehost --list

You'll see something like:

List of databases
           Name         |  Owner   | Encoding
------------------------+----------+----------
db1                     | postgres | UTF8

TypeError: $.browser is undefined

I did solved using this jquery for Github

<script src="http://code.jquery.com/jquery-migrate-1.0.0.js"></script>

Please Refer this link for more info. https://github.com/Studio-42/elFinder/issues/469

How to catch integer(0)?

if ( length(a <- which(1:3 == 5) ) ) print(a)  else print("nothing returned for 'a'") 
#[1] "nothing returned for 'a'"

On second thought I think any is more beautiful than length(.):

 if ( any(a <- which(1:3 == 5) ) ) print(a)  else print("nothing returned for 'a'") 
 if ( any(a <- 1:3 == 5 ) ) print(a)  else print("nothing returned for 'a'") 

Create a simple HTTP server with Java?

I just added a public repo with a ready to run out of the box server using Jetty and JDBC to get your project started.

Pull from github here: https://github.com/waf04/WAF-Simple-JAVA-HTTP-MYSQL-Server.git

How do I format date and time on ssrs report?

If you want date and time separate then use below expressions: Date and Time Expression

Expression1 for current date : =formatdatetime(today) its return date is = 11/15/2016

Expression2 for current time : =CDate(Now).ToString("hh:mm tt") its return time is = 3:44 PM

This report printed on Expression1 at Expression2

Output will be : Output of Both Expression

This report printed on 11/15/2016 at 3:44 PM

Select the top N values by group

If there were a tie at the fourth position for mtcars$mpg then this should return all the ties:

top_mpg <- mtcars[ mtcars$mpg >= mtcars$mpg[order(mtcars$mpg, decreasing=TRUE)][4] , ]

> top_mpg
                mpg cyl disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4 78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4 75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4 71.1  65 4.22 1.835 19.90  1  1    4    1
Lotus Europa   30.4   4 95.1 113 3.77 1.513 16.90  1  1    5    2

Since there is a tie at the 3-4 position you can test it by changing 4 to a 3, and it still returns 4 items. This is logical indexing and you might need to add a clause that removes the NA's or wrap which() around the logical expression. It's not much more difficult to do this "by" cyl:

 Reduce(rbind,  by(mtcars, mtcars$cyl, 
        function(d) d[ d$mpg >= d$mpg[order(d$mpg, decreasing=TRUE)][4] , ]) )
#-------------
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128          32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic       30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla    33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Lotus Europa      30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2
Mazda RX4         21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Ferrari Dino      19.7   6 145.0 175 3.62 2.770 15.50  0  1    5    6
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Merc 450SE        16.4   8 275.8 180 3.07 4.070 17.40  0  0    3    3
Merc 450SL        17.3   8 275.8 180 3.07 3.730 17.60  0  0    3    3
Pontiac Firebird  19.2   8 400.0 175 3.08 3.845 17.05  0  0    3    2

Incorporating my suggestion to @Ista:

Reduce(rbind,  by(mtcars, mtcars$cyl, function(d) d[ d$mpg <= sort( d$mpg )[3] , ]) )

How to list the tables in a SQLite database file that was opened with ATTACH?

Via a union all, combine all tables into one list.

select name
from sqlite_master 
where type='table'

union all 

select name 
from sqlite_temp_master 
where type='table'

Redirect from an HTML page

I found a problem while working with a jQuery Mobile application, where in some cases my Meta header tag wouldn't achieve a redirection properly (jQuery Mobile doesn't read headers automatically for each page so putting JavaScript there is also ineffective unless wrapping it in complexity). I found the easiest solution in this case was to put the JavaScript redirection directly into the body of the document, as follows:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta http-equiv="refresh" content="0;url=myURL" />
    </head>

    <body>
        <p>You are not logged in!</p>
        <script language="javascript">
            window.location = "myURL";
        </script>
    </body>
</html>

This seems to work in every case for me.

Efficient way of having a function only execute once in a loop

Assuming there is some reason why myFunction() can't be called before the loop

from itertools import count
for i in count():
    if i==0:
        myFunction()

Begin, Rescue and Ensure in Ruby?

Yes, ensure ensures that the code is always evaluated. That's why it's called ensure. So, it is equivalent to Java's and C#'s finally.

The general flow of begin/rescue/else/ensure/end looks like this:

begin
  # something which might raise an exception
rescue SomeExceptionClass => some_variable
  # code that deals with some exception
rescue SomeOtherException => some_other_variable
  # code that deals with some other exception
else
  # code that runs only if *no* exception was raised
ensure
  # ensure that this code always runs, no matter what
  # does not change the final value of the block
end

You can leave out rescue, ensure or else. You can also leave out the variables in which case you won't be able to inspect the exception in your exception handling code. (Well, you can always use the global exception variable to access the last exception that was raised, but that's a little bit hacky.) And you can leave out the exception class, in which case all exceptions that inherit from StandardError will be caught. (Please note that this does not mean that all exceptions are caught, because there are exceptions which are instances of Exception but not StandardError. Mostly very severe exceptions that compromise the integrity of the program such as SystemStackError, NoMemoryError, SecurityError, NotImplementedError, LoadError, SyntaxError, ScriptError, Interrupt, SignalException or SystemExit.)

Some blocks form implicit exception blocks. For example, method definitions are implicitly also exception blocks, so instead of writing

def foo
  begin
    # ...
  rescue
    # ...
  end
end

you write just

def foo
  # ...
rescue
  # ...
end

or

def foo
  # ...
ensure
  # ...
end

The same applies to class definitions and module definitions.

However, in the specific case you are asking about, there is actually a much better idiom. In general, when you work with some resource which you need to clean up at the end, you do that by passing a block to a method which does all the cleanup for you. It's similar to a using block in C#, except that Ruby is actually powerful enough that you don't have to wait for the high priests of Microsoft to come down from the mountain and graciously change their compiler for you. In Ruby, you can just implement it yourself:

# This is what you want to do:
File.open('myFile.txt', 'w') do |file|
  file.puts content
end

# And this is how you might implement it:
def File.open(filename, mode='r', perm=nil, opt=nil)
  yield filehandle = new(filename, mode, perm, opt)
ensure
  filehandle&.close
end

And what do you know: this is already available in the core library as File.open. But it is a general pattern that you can use in your own code as well, for implementing any kind of resource cleanup (à la using in C#) or transactions or whatever else you might think of.

The only case where this doesn't work, if acquiring and releasing the resource are distributed over different parts of the program. But if it is localized, as in your example, then you can easily use these resource blocks.


BTW: in modern C#, using is actually superfluous, because you can implement Ruby-style resource blocks yourself:

class File
{
    static T open<T>(string filename, string mode, Func<File, T> block)
    {
        var handle = new File(filename, mode);
        try
        {
            return block(handle);
        }
        finally
        {
            handle.Dispose();
        }
    }
}

// Usage:

File.open("myFile.txt", "w", (file) =>
{
    file.WriteLine(contents);
});

Disable back button in react navigation

i think it is simple just add headerLeft : null , i am using react-native cli, so this is the example :

static navigationOptions = {
    headerLeft : null
};

Bootstrap Collapse not Collapsing

bootstrap.js is using jquery library so you need to add jquery library before bootstrap js.

so please add it jquery library like

Note : Please maintain order of js file. html page use top to bottom approach for compilation

<head>
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <script src="http://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>

How can I exclude multiple folders using Get-ChildItem -exclude?

may be in your case you could reach this with the following:

    mv excluded_dir ..\
    ls -R 
    mv ..\excluded_dir .

How to generate a random alpha-numeric string

Using Dollar should be as simple as:

// "0123456789" + "ABCDE...Z"
String validCharacters = $('0', '9').join() + $('A', 'Z').join();

String randomString(int length) {
    return $(validCharacters).shuffle().slice(length).toString();
}

@Test
public void buildFiveRandomStrings() {
    for (int i : $(5)) {
        System.out.println(randomString(12));
    }
}

It outputs something like this:

DKL1SBH9UJWC
JH7P0IT21EA5
5DTI72EO6SFU
HQUMJTEBNF7Y
1HCR6SKYWGT7

Android: How to programmatically access the device serial number shown in the AVD manager (API Version 8)

From Android P, defining the READ_PHONE_STATE permission in AndroidManifest only, will not work. We have to actually request for the permission. Below code works for me:

@RequiresApi(api = Build.VERSION_CODES.P)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 101);
    }
}

@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected void onResume() {
    super.onResume();
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    Log.d(TAG,Build.getSerial());
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case 101:
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
        } else {
            //not granted
        }
        break;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

Add this permissions in AndroidManifest.xml

<uses-permission android:name = "android.permission.INTERNET"/>
<uses-permission android:name = "android.permission.READ_PHONE_STATE" />

Hope this helps.

Thank You, MJ

ActionBarActivity: cannot be resolved to a type

This way work for me with Eclipse in Android developer tool from Google -righ click - property - java build path - add external JAR

point to: android-support-v7-appcompat.jar in /sdk/extras/android/support/v7/appcompat/libs

Then

import android.support.v7.app.ActionBarActivity;

Entity Framework Migrations renaming tables and columns

I just tried the same in EF6 (code first entity rename). I simply renamed the class and added a migration using the package manager console and voila, a migration using RenameTable(...) was automatically generated for me. I have to admit that I made sure the only change to the entity was renaming it so no new columns or renamed columns so I cannot be certain if this is an EF6 thing or just that EF was (always) able to detect such simple migrations.

Mac OS X and multiple Java versions

I am using Mac OS X 10.9.5. This is how I manage multiple JDK/JRE on my machine when I need one version to run application A and use another version for application B.

I created the following script after getting some help online.

#!bin/sh
function setjdk() {
  if [ $# -ne 0 ]; then
   removeFromPath '/Library/Java/JavaVirtualMachines/'
   if [ -n "${JAVA_HOME+x}" ]; then
    removeFromPath $JAVA_HOME
   fi
   export JAVA_HOME=/Library/Java/JavaVirtualMachines/$1/Contents/Home
   export PATH=$JAVA_HOME/bin:$PATH
  fi
 }
 function removeFromPath() {
  export PATH=$(echo $PATH | sed -E -e "s;:$1;;" -e "s;$1:?;;")
 }
#setjdk jdk1.8.0_60.jdk
setjdk jdk1.7.0_15.jdk

I put the above script in .profile file. Just open terminal, type vi .profile, append the script with the above snippet and save it. Once your out type source .profile, this will run your profile script without you having to restart the terminal. Now type java -version it should show 1.7 as your current version. If you intend to change it to 1.8 then comment the line setjdk jdk1.7.0_15.jdk and uncomment the line setjdk jdk1.8.0_60.jdk. Save the script and run it again with source command. I use this mechanism to manage multiple versions of JDK/JRE when I have to compile 2 different Maven projects which need different java versions.

Unable to show a Git tree in terminal

How can you get the tree-like view of commits in terminal?

git log --graph --oneline --all

is a good start.

You may get some strange letters. They are ASCII codes for colors and structure. To solve this problem add the following to your .bashrc:

export LESS="-R"

such that you do not need use Tig's ASCII filter by

git log --graph --pretty=oneline --abbrev-commit | tig   // Masi needed this 

The article text-based graph from Git-ready contains other options:

git log --graph --pretty=oneline --abbrev-commit

git log graph

Regarding the article you mention, I would go with Pod's answer: ad-hoc hand-made output.


Jakub Narebski mentions in the comments tig, a ncurses-based text-mode interface for git. See their releases.
It added a --graph option back in 2007.

How to make google spreadsheet refresh itself every 1 minute?

If you are only looking for a refresh rate for the GOOGLEFINANCE function, keep in mind that data delays can be up to 20 minutes (per Google Finance Disclaimer).

Single-symbol refresh rate (using GoogleClock)

Here is a modified version of the refresh action, taking the data delay into consideration, to save on unproductive refresh cycles.

=GoogleClock(GOOGLEFINANCE(symbol,"datadelay"))

For example, with:

  • SYMBOL: GOOG
  • DATA DELAY: 15 (minutes)

then

=GoogleClock(GOOGLEFINANCE("GOOG","datadelay"))

Results in a dynamic data-based refresh rate of:

=GoogleClock(15)

Multi-symbol refresh rate (using GoogleClock)

If your sheet contains a number of rows of symbols, you could add a datadelay column for each symbol and use the lowest value, for example:

=GoogleClock(MIN(dataDelayValuesNamedRange))

Where dataDelayValuesNamedRange is the absolute reference or named reference of the range of cells that contain the data delay values for each symbol (assuming these values are different).

Without GoogleClock()

The GoogleClock() function was removed in 2014 and replaced with settings setup for refreshing sheets. At present, I have confirmed that replacement settings is only on available in Sheets from when accessed from a desktop browser, not the mobile app (I'm using Google's mobile Sheets app updated 2016-03-14).

(This part of the answer is based on, and portions copied from, Google Docs Help)

To change how often "some" Google Sheets functions update:

  1. Open a spreadsheet. Click File > Spreadsheet settings.
  2. In the RECALCULATION section, choose a setting from the drop-down menu.
  3. Setting options are:
    • On change
    • On change and every minute
    • On change and every hour
  4. Click SAVE SETTINGS.

NOTE External data functions recalculate at the following intervals:

  • ImportRange: 30 minutes
  • ImportHtml, ImportFeed, ImportData, ImportXml: 1 hour
  • GoogleFinance: 2 minutes

The references in earlier sections to the display and use of the datadelay attribute still apply, as well as the concepts for more efficient coding of sheets.

On a positive note, the new refresh option continues to be refreshed by Google servers regardless of whether you have the sheet loaded or not. That's a positive for shared sheets for sure; even more so for Google Apps Scripts (GAS), where GAS is used in workflow code or referenced data is used as a trigger for an event.

[*] in my understanding so far (I am currently testing this)

How are VST Plugins made?

I wrote up a HOWTO for VST development on C++ with Visual Studio awhile back which details the steps necessary to create a basic plugin for the Windows platform (the Mac version of this article is forthcoming). On Windows, a VST plugin is just a normal DLL, but there are a number of "gotchas", and you need to build the plugin using some specific compiler/linker switches or else it won't be recognized by some hosts.

As for the Mac, a VST plugin is just a bundle with the .vst extension, though there are also a few settings which must be configured correctly in order to generate a valid plugin. You can also download a set of Xcode VST plugin project templates I made awhile back which can help you to write a working plugin on that platform.

As for AudioUnits, Apple has provided their own project templates which are included with Xcode. Apple also has very good tutorials and documentation online:

I would also highly recommend checking out the Juce Framework, which has excellent support for creating cross-platform VST/AU plugins. If you're going open-source, then Juce is a no-brainer, but you will need to pay licensing fees for it if you plan on releasing your work without source code.

Different names of JSON property during serialization and deserialization

This was not what I was expecting as a solution (though it is a legitimate use case). My requirement was to allow an existing buggy client (a mobile app which already released) to use alternate names.

The solution lies in providing a separate setter method like this:

@JsonSetter( "r" )
public void alternateSetRed( byte red ) {
    this.red = red;
}

Create a pointer to two-dimensional array

You want a pointer to the first element, so;

static uint8_t l_matrix[10][20];

void test(){
   uint8_t *matrix_ptr = l_matrix[0]; //wrong idea 
}

Alternative for frames in html5 using iframes

While I agree with everyone else, if you are dead set on using frames anyway, you can just do index.html in XHTML and then do the contents of the frames in HTML5.

SQL SELECT WHERE field contains words

SELECT * FROM MyTable WHERE 
Column1 LIKE '%word1%'
AND Column1 LIKE '%word2%'
AND Column1 LIKE  '%word3%'

Changed OR to AND based on edit to question.

How do I get a list of locked users in an Oracle database?

This suits the requirement:

select username, account_status, EXPIRY_DATE from dba_users where 
username='<username>';

Output:

USERNAME        ACCOUNT_STATUS                   EXPIRY_DA
--------------------------------------------------------------------------------
SYSTEM          EXPIRED                          13-NOV-17

How can I count the number of elements of a given value in a matrix?

assume w contains week numbers ([1:7])

n = histc(M,w)

if you do not know the range of numbers in M:

n = histc(M,unique(M))

It is such as a SQL Group by command!

How do you clear your Visual Studio cache on Windows Vista?

The accepted answer gave two locations:

here

C:\Documents and Settings\Administrator\Local Settings\Temp\VWDWebCache

and possibly here

C:\Documents and Settings\Administrator\Local Settings\Application Data\Microsoft\WebsiteCache

Did you try those?

Edited to add

On my Windows Vista machine, it's located in

%Temp%\VWDWebCache

and in

%LocalAppData%\Microsoft\WebsiteCache

From your additional information (regarding team edition) this comes from Clear Client TFS Cache:

Clear Client TFS Cache

Visual Studio and Team Explorer provide a caching mechanism which can get out of sync. If I have multiple instances of a single TFS which can be connected to from a single Visual Studio client, that client can become confused.

To solve it..

For Windows Vista delete contents of this folder

%LocalAppData%\Microsoft\Team Foundation\1.0\Cache

How to embed small icon in UILabel

You could use a UITextField with the leftView property and then set the enabled property to NO

Or use a UIButton and setImage:forControlState

Python sys.argv lists and indexes

As explained in the different asnwers already, sys.argv contains the command line arguments that called your Python script.

However, Python comes with libraries that help you parse command line arguments very easily. Namely, the new standard argparse. Using argparse would spare you the need to write a lot of boilerplate code.

Convert a Unix timestamp to time in JavaScript

I'd think about using a library like momentjs.com, that makes this really simple:

Based on a Unix timestamp:

var timestamp = moment.unix(1293683278);
console.log( timestamp.format("HH/mm/ss") );

Based on a MySQL date string:

var now = moment("2010-10-10 12:03:15");
console.log( now.format("HH/mm/ss") );

Telling gcc directly to link a library statically

It is possible of course, use -l: instead of -l. For example -l:libXYZ.a to link with libXYZ.a. Notice the lib written out, as opposed to -lXYZ which would auto expand to libXYZ.

date() method, "A non well formed numeric value encountered" does not want to format a date passed in $_POST

From the documentation for strtotime():

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

In your date string, you have 12-16-2013. 16 isn't a valid month, and hence strtotime() returns false.

Since you can't use DateTime class, you could manually replace the - with / using str_replace() to convert the date string into a format that strtotime() understands:

$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16

Java HTTPS client certificate authentication

I've connected to bank with two-way SSL (client and server certificate) with Spring Boot. So describe here all my steps, hope it helps someone (simplest working solution, I've found):

  1. Generate sertificate request:

    • Generate private key:

      openssl genrsa -des3 -passout pass:MY_PASSWORD -out user.key 2048
      
    • Generate certificate request:

      openssl req -new -key user.key -out user.csr -passin pass:MY_PASSWORD
      

    Keep user.key (and password) and send certificate request user.csr to bank for my sertificate

  2. Receive 2 certificate: my client root certificate clientId.crt and bank root certificate: bank.crt

  3. Create Java keystore (enter key password and set keystore password):

    openssl pkcs12 -export -in clientId.crt -inkey user.key -out keystore.p12 -name clientId -CAfile ca.crt -caname root
    

    Don't pay attention on output: unable to write 'random state'. Java PKCS12 keystore.p12 created.

  4. Add into keystore bank.crt (for simplicity I've used one keystore):

    keytool -import -alias banktestca -file banktestca.crt -keystore keystore.p12 -storepass javaops
    

    Check keystore certificates by:

    keytool -list -keystore keystore.p12
    
  5. Ready for Java code:) I've used Spring Boot RestTemplate with add org.apache.httpcomponents.httpcore dependency:

    @Bean("sslRestTemplate")
    public RestTemplate sslRestTemplate() throws Exception {
      char[] storePassword = appProperties.getSslStorePassword().toCharArray();
      URL keyStore = new URL(appProperties.getSslStore());
    
      SSLContext sslContext = new SSLContextBuilder()
            .loadTrustMaterial(keyStore, storePassword)
      // use storePassword twice (with key password do not work)!!
            .loadKeyMaterial(keyStore, storePassword, storePassword) 
            .build();
    
      // Solve "Certificate doesn't match any of the subject alternative names"
      SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
    
      CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
      HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(client);
      RestTemplate restTemplate = new RestTemplate(factory);
      // restTemplate.setMessageConverters(List.of(new Jaxb2RootElementHttpMessageConverter()));
      return restTemplate;
    }
    

What does the star operator mean, in a function call?

One small point: these are not operators. Operators are used in expressions to create new values from existing values (1+2 becomes 3, for example. The * and ** here are part of the syntax of function declarations and calls.

How to use pagination on HTML tables?

As far as I can see it on the website of that paginations plugin, the plugin itself doesn't do the actual pagination. The only thing it does is display a row of numbers, and display the correct buttons depending on the page you're on.

However, to actually paginate, you have to write the appropriate Javascript yourself. This should be placed in stead of this Javascript:

function test(pageNumber)
{

  var page="#page-id-"+pageNumber;
  $('.select').hide()
  $(page).show()

}

Which is code I'm guessing you've copy-pasted from somewhere but at the moment doesn't really do anything. If you don't know Javascript, going with another library that actually does pagination of a table is something you probably want to do.

How to unzip a file in Powershell?

Using expand-archive but auto-creating directories named after the archive:

function unzip ($file) {
    $dirname = (Get-Item $file).Basename
    New-Item -Force -ItemType directory -Path $dirname
    expand-archive $file -OutputPath $dirname -ShowProgress
}

How to convert OutputStream to InputStream?

Old post but might help others, Use this way:

OutputStream out = new ByteArrayOutputStream();
...
out.write();
...
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(out.toString().getBytes()));

What does "res.render" do, and what does the html file look like?

What does res.render do and what does the html file look like?

res.render() function compiles your template (please don't use ejs), inserts locals there, and creates html output out of those two things.


Answering Edit 2 part.

// here you set that all templates are located in `/views` directory
app.set('views', __dirname + '/views');

// here you set that you're using `ejs` template engine, and the
// default extension is `ejs`
app.set('view engine', 'ejs');

// here you render `orders` template
response.render("orders", {orders: orders_json});

So, the template path is views/ (first part) + orders (second part) + .ejs (third part) === views/orders.ejs


Anyway, express.js documentation is good for what it does. It is API reference, not a "how to use node.js" book.

How do I programmatically change file permissions?

Apache ant chmod (not very elegant, adding it for completeness) credit shared with @msorsky

    Chmod chmod = new Chmod();
    chmod.setProject(new Project());
    FileSet mySet = new FileSet();
    mySet.setDir(new File("/my/path"));
    mySet.setIncludes("**");
    chmod.addFileset(mySet);
    chmod.setPerm("+w");
    chmod.setType(new FileDirBoth());
    chmod.execute();

What exactly does an #if 0 ..... #endif block do?

It's identical to commenting out the block, except with one important difference: Nesting is not a problem. Consider this code:

foo();
bar(x, y); /* x must not be NULL */
baz();

If I want to comment it out, I might try:

/*
foo();
bar(x, y); /* x must not be NULL */
baz();
*/

Bzzt. Syntax error! Why? Because block comments do not nest, and so (as you can see from SO's syntax highlighting) the */ after the word "NULL" terminates the comment, making the baz call not commented out, and the */ after baz a syntax error. On the other hand:

#if 0
foo();
bar(x, y); /* x must not be NULL */
baz();
#endif

Works to comment out the entire thing. And the #if 0s will nest with each other, like so:

#if 0
pre_foo();
#if 0
foo();
bar(x, y); /* x must not be NULL */
baz();
#endif
quux();
#endif

Although of course this can get a bit confusing and become a maintenance headache if not commented properly.

How can I run a PHP script inside a HTML file?

Simply you cant !! but you have some possbile options :

1- Excute php page as external page.

2- write your html code inside the php page itself.

3- use iframe to include the php within the html page.

to be more specific , unless you wanna edit your htaccess file , you may then consider this:

http://php.about.com/od/advancedphp/p/html_php.htm

Java - Search for files in a directory

With **Java 8* there is an alternative that use streams and lambdas:

public static void recursiveFind(Path path, Consumer<Path> c) {
  try (DirectoryStream<Path> newDirectoryStream = Files.newDirectoryStream(path)) {
    StreamSupport.stream(newDirectoryStream.spliterator(), false)
                 .peek(p -> {
                   c.accept(p);
                   if (p.toFile()
                        .isDirectory()) {
                     recursiveFind(p, c);
                   }
                 })
                 .collect(Collectors.toList());
  } catch (IOException e) {
    e.printStackTrace();
  }
}

So this will print all the files recursively:

recursiveFind(Paths.get("."), System.out::println);

And this will search for a file:

recursiveFind(Paths.get("."), p -> { 
  if (p.toFile().getName().toString().equals("src")) {
    System.out.println(p);
  }
});

remove white space from the end of line in linux

This might work for you (GNU sed):

sed -ri  '/\s+$/s///' file

This looks for whitespace at the end of the line and and if present removes it.

Python coding standards/best practices

I follow it extremely rigorously. The only god before PEP-8 is existing code bases.

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

The official tutorial may be of some use to you.


Class Package Subclass
(same pkg)
Subclass
(diff pkg)
World
public + + + + +
protected + + + +
no modifier + + +
private +

+ : accessible
blank : not accessible

gradient descent using python and numpy

Following @thomas-jungblut implementation in python, i did the same for Octave. If you find something wrong please let me know and i will fix+update.

Data comes from a txt file with the following rows:

1 10 1000
2 20 2500
3 25 3500
4 40 5500
5 60 6200

think about it as a very rough sample for features [number of bedrooms] [mts2] and last column [rent price] which is what we want to predict.

Here is the Octave implementation:

%
% Linear Regression with multiple variables
%

% Alpha for learning curve
alphaNum = 0.0005;

% Number of features
n = 2;

% Number of iterations for Gradient Descent algorithm
iterations = 10000

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% No need to update after here
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

DATA = load('CHANGE_WITH_DATA_FILE_PATH');

% Initial theta values
theta = ones(n + 1, 1);

% Number of training samples
m = length(DATA(:, 1));

% X with one mor column (x0 filled with '1's)
X = ones(m, 1);
for i = 1:n
  X = [X, DATA(:,i)];
endfor

% Expected data must go always in the last column  
y = DATA(:, n + 1)

function gradientDescent(x, y, theta, alphaNum, iterations)
  iterations = [];
  costs = [];

  m = length(y);

  for iteration = 1:10000
    hypothesis = x * theta;

    loss = hypothesis - y;

    % J(theta)    
    cost = sum(loss.^2) / (2 * m);

    % Save for the graphic to see if the algorithm did work
    iterations = [iterations, iteration];
    costs = [costs, cost];

    gradient = (x' * loss) / m; % /m is for the average

    theta = theta - (alphaNum * gradient);
  endfor    

  % Show final theta values
  display(theta)

  % Show J(theta) graphic evolution to check it worked, tendency must be zero
  plot(iterations, costs);

endfunction

% Execute gradient descent
gradientDescent(X, y, theta, alphaNum, iterations);

Code snippet or shortcut to create a constructor in Visual Studio

As mentioned by many, "ctor" and double TAB works in Visual Studio 2017, but it only creates the constructor with none of the attributes.

To auto-generate with attributes (if there are any), just click on an empty line below them and press Ctrl + .. It'll display a small pop-up from which you can select the "Generate Constructor..." option.

Jenkins - how to build a specific branch

This is extension of answer provided by Ranjith

I would suggest, you to choose a choice-parameter build, and specify the branches that you would like to build. Active Choice Parameter

And after that, you can specify branches to build. Branch to Build

Now, when you would build your project, you would be provided with "Build with Parameters, where you can choose the branch to build"

You can also write a groovy script to fetch all your branches to in active choice parameter.

Getting first and last day of the current month

An alternative way is to use DateTime.DaysInMonth to get the number of days in the current month as suggested by @Jade

Since we know the first day of the month will always 1 we can use it as default for the first day with the current Month & year as current.year,current.Month,1.

var now = DateTime.Now; // get the current DateTime 

//Get the number of days in the current month
int daysInMonth = DateTime.DaysInMonth (now.Year, now.Month); 
    
//First day of the month is always 1
var firstDay = new DateTime(now.Year,now.Month,1); 
    
//Last day will be similar to the number of days calculated above
var lastDay = new DateTime(now.Year,now.Month,daysInMonth);

//So
rdpStartDate.SelectedDate = firstDay;
rdpEndDate.SelectedDate = lastDay; 

Make xargs execute the command once for each line of input

In your example, the point of piping the output of find to xargs is that the standard behavior of find's -exec option is to execute the command once for each found file. If you're using find, and you want its standard behavior, then the answer is simple - don't use xargs to begin with.

How to delete an element from a Slice in Golang

Remove one element from the Slice (this is called 're-slicing'):

package main

import (
    "fmt"
)

func RemoveIndex(s []int, index int) []int {
    return append(s[:index], s[index+1:]...)
}

func main() {
    all := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
    fmt.Println(all) //[0 1 2 3 4 5 6 7 8 9]
    all = RemoveIndex(all, 5)
    fmt.Println(all) //[0 1 2 3 4 6 7 8 9]
}

How to convert date to timestamp?

function getTimeStamp() {
       var now = new Date();
       return ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + " " + now.getHours() + ':'
                     + ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : (now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now
                     .getSeconds()) : (now.getSeconds())));
}

MATLAB - multiple return values from a function?

Change the function that you get one single Result=[array, listp, freep]. So there is only one result to be displayed

How to turn a string formula into a "real" formula

Just for fun, I found an interesting article here, to use a somehow hidden evaluate function that does exist in Excel. The trick is to assign it to a name, and use the name in your cells, because EVALUATE() would give you an error msg if used directly in a cell. I tried and it works! You can use it with a relative name, if you want to copy accross rows if a sheet.

Open new popup window without address bars in firefox & IE

Firefox 3.0 and higher have disabled setting location by default. resizable and status are also disabled by default. You can verify this by typing `about:config' in your address bar and filtering by "dom". The items of interest are:

  • dom.disable_window_open_feature.location
  • dom.disable_window_open_feature.resizable
  • dom.disable_window_open_feature.status

You can get further information at the Mozilla Developer site. What this basically means, though, is that you won't be able to do what you want to do.

One thing you might want to do (though it won't solve your problem), is put quotes around your window feature parameters, like so:

window.open('/pageaddress.html','winname','directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=400,height=350');

Redirecting to a relative URL in JavaScript

I'm trying to redirect my current web site to other section on the same page, using JavaScript. This follow code work for me:

location.href='/otherSection'

Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'

I found it, I was trying to compile my app which is using facebook sdk. I was made that like augst 2016. When I try to open it today i got same error. I had that line in my gradle " compile 'com.facebook.android:facebook-android-sdk:4.+' " and I went https://developers.facebook.com/docs/android/change-log-4x this page and i found the sdk version while i was running this app succesfully and it was 4.14.1 then I changed that line to " compile 'com.facebook.android:facebook-android-sdk:4.14.1' " and it worked.

Creating instance list of different objects

I see that all of the answers suggest using a list filled with Object classes and then explicitly casting the desired class, and I personally don't like that kind of approach.

What works better for me is to create an interface which contains methods for retrieving or storing data from/to certain classes I want to put in a list. Have those classes implement that new interface, add the methods from the interface into them and then you can fill the list with interface objects - List<NewInterface> newInterfaceList = new ArrayList<>() thus being able to extract the desired data from the objects in a list without having the need to explicitly cast anything.

You can also put a comparator in the interface if you need to sort the list.

How do I format a number in Java?

There are two approaches in the standard library. One is to use java.text.DecimalFormat. The other more cryptic methods (String.format, PrintStream.printf, etc) based around java.util.Formatter should keep C programmers happy(ish).

What does "use strict" do in JavaScript, and what is the reasoning behind it?

When adding "use strict";, the following cases will throw a SyntaxError before the script is executing:

  • Paving the way for future ECMAScript versions, using one of the newly reserved keywords (in prevision for ECMAScript 6): implements, interface, let, package, private, protected, public, static, and yield.

  • Declaring function in blocks

    if(a<b){ function f(){} }
    
  • Octal syntax

    var n = 023;
    
  • this point to the global object.

     function f() {
          "use strict";
          this.a = 1;
     };
     f(); 
    
  • Declaring twice the same name for a property name in an object literal

     {a: 1, b: 3, a: 7} 
    

    This is no longer the case in ECMAScript 6 (bug 1041128).

  • Declaring two function arguments with the same name function

    f(a, b, b){}
    
  • Setting a value to an undeclared variable

    function f(x){
       "use strict";
       var a = 12;
       b = a + x*35; // error!
    }
    f();
    
  • Using delete on a variable name delete myVariable;

  • Using eval or arguments as variable or function argument name

    "use strict";
    arguments++;
    var obj = { set p(arguments) { } };
    try { } catch (arguments) { }
    function arguments() { } 
    

Sources:

How I add Headers to http.get or http.post in Typescript and angular 2?

I have used below code in Angular 9. note that it is using http class instead of normal httpClient.

  1. so import Headers from the module, otherwise Headers will be mistaken by typescript headers interface and gives error

    import {Http, Headers, RequestOptionsArgs } from "@angular/http";

  2. and in your method use following sample code and it is breaked down for easier understanding.

    let customHeaders = new Headers({ Authorization: "Bearer " + localStorage.getItem("token")});
    const requestOptions: RequestOptionsArgs = { headers: customHeaders };
    return this.http.get("/api/orders", requestOptions);
    

Scala best way of turning a Collection into a Map-by-key?

Another solution (might not work for all types)

import scala.collection.breakOut
val m:Map[P, T] = c.map(t => (t.getP, t))(breakOut)

this avoids the creation of the intermediary list, more info here: Scala 2.8 breakOut

Different ways of clearing lists

Clearing a list in place will affect all other references of the same list.

For example, this method doesn't affect other references:

>>> a = [1, 2, 3]
>>> b = a
>>> a = []
>>> print(a)
[]
>>> print(b)
[1, 2, 3]

But this one does:

>>> a = [1, 2, 3]
>>> b = a
>>> del a[:]      # equivalent to   del a[0:len(a)]
>>> print(a)
[]
>>> print(b)
[]
>>> a is b
True

You could also do:

>>> a[:] = []

How to make CSS3 rounded corners hide overflow in Chrome/Opera

Nevermind everyone, I managed to solve the problem by adding an additional div between the wrapper and box.

CSS

#wrapper {
    position: absolute;
}

#middle {
    border-radius: 100px;
    overflow: hidden; 
}

#box {
    width: 300px; height: 300px;
    background-color: #cde;
}

HTML

<div id="wrapper">
    <div id="middle">
        <div id="box"></div>
    </div>
</div>

Thanks everyone who helped!

? http://jsfiddle.net/5fwjp/

Phone mask with jQuery and Masked Input Plugin

Here is a jQuery phone number mask. No plugin required. Format can be adjusted to your needs.

Updated JSFiddle.

HTML

<form id="example-form" name="my-form">
    <input id="phone-number" name="phone-number" type="text" placeholder="(XXX) XXX-XXXX">
</form>

JavaScript

$('#phone-number', '#example-form')

.keydown(function (e) {
    var key = e.which || e.charCode || e.keyCode || 0;
    $phone = $(this);

    // Don't let them remove the starting '('
    if ($phone.val().length === 1 && (key === 8 || key === 46)) {
        $phone.val('('); 
        return false;
    } 
    // Reset if they highlight and type over first char.
    else if ($phone.val().charAt(0) !== '(') {
        $phone.val('('+$phone.val()); 
    }

    // Auto-format- do not expose the mask as the user begins to type
    if (key !== 8 && key !== 9) {
        if ($phone.val().length === 4) {
            $phone.val($phone.val() + ')');
        }
        if ($phone.val().length === 5) {
            $phone.val($phone.val() + ' ');
        }           
        if ($phone.val().length === 9) {
            $phone.val($phone.val() + '-');
        }
    }

    // Allow numeric (and tab, backspace, delete) keys only
    return (key == 8 || 
            key == 9 ||
            key == 46 ||
            (key >= 48 && key <= 57) ||
            (key >= 96 && key <= 105)); 
})

.bind('focus click', function () {
    $phone = $(this);

    if ($phone.val().length === 0) {
        $phone.val('(');
    }
    else {
        var val = $phone.val();
        $phone.val('').val(val); // Ensure cursor remains at the end
    }
})

.blur(function () {
    $phone = $(this);

    if ($phone.val() === '(') {
        $phone.val('');
    }
});

MySQL Workbench: How to keep the connection alive

I was getting this error 2013 and none of the above preference changes did anything to fix the problem. I restarted mysql service and the problem went away.

function to return a string in java

Your code is fine. There's no problem with returning Strings in this manner.

In Java, a String is a reference to an immutable object. This, coupled with garbage collection, takes care of much of the potential complexity: you can simply pass a String around without worrying that it would disapper on you, or that someone somewhere would modify it.

If you don't mind me making a couple of stylistic suggestions, I'd modify the code like so:

public String time_to_string(long t) // time in milliseconds
{
    if (t < 0)
    {
        return "-";
    }
    else
    {
        int secs = (int)(t/1000);
        int mins = secs/60;
        secs = secs - (mins * 60);
        return String.format("%d:%02d", mins, secs);
    }
}

As you can see, I've pushed the variable declarations as far down as I could (this is the preferred style in C++ and Java). I've also eliminated ans and have replaced the mix of string concatenation and String.format() with a single call to String.format().

How to use wget in php?

wget

wget is a linux command, not a PHP command, so to run this you woud need to use exec, which is a PHP command for executing shell commands.

exec("wget --http-user=[user] --http-password=[pass] http://www.example.com/file.xml");

This can be useful if you are downloading a large file - and would like to monitor the progress, however when working with pages in which you are just interested in the content, there are simple functions for doing just that.

The exec function is enabled by default, but may be disabled in some situations. The configuration options for this reside in your php.ini, to enable, remove exec from the disabled_functions config string.

alternative

Using file_get_contents we can retrieve the contents of the specified URL/URI. When you just need to read the file into a variable, this would be the perfect function to use as a replacement for curl - follow the URI syntax when building your URL.

// standard url
$content = file_get_contents("http://www.example.com/file.xml");

// or with basic auth
$content = file_get_contents("http://user:[email protected]/file.xml");

As noted by Sean the Bean - you may also need to change allow_url_fopen to true in your php.ini to allow the use of a URL in this method, however, this should be true by default.

If you want to then store that file locally, there is a function file_put_contents to write that into a file, combined with the previous, this could emulate a file download:

file_put_contents("local_file.xml", $content);

How to sort an array in Bash

I am not convinced that you'll need an external sorting program in Bash.

Here is my implementation for the simple bubble-sort algorithm.

function bubble_sort()
{   #
    # Sorts all positional arguments and echoes them back.
    #
    # Bubble sorting lets the heaviest (longest) element sink to the bottom.
    #
    local array=($@) max=$(($# - 1))
    while ((max > 0))
    do
        local i=0
        while ((i < max))
        do
            if [ ${array[$i]} \> ${array[$((i + 1))]} ]
            then
                local t=${array[$i]}
                array[$i]=${array[$((i + 1))]}
                array[$((i + 1))]=$t
            fi
            ((i += 1))
        done
        ((max -= 1))
    done
    echo ${array[@]}
}

array=(a c b f 3 5)
echo " input: ${array[@]}"
echo "output: $(bubble_sort ${array[@]})"

This shall print:

 input: a c b f 3 5
output: 3 5 a b c f

How to find duplicate records in PostgreSQL

In your case, because of the constraint you need to delete the duplicated records.

  1. Find the duplicated rows
  2. Organize them by created_at date - in this case I'm keeping the oldest
  3. Delete the records with USING to filter the right rows
WITH duplicated AS ( 
    SELECT id,
        count(*) 
    FROM products 
    GROUP BY id 
    HAVING count(*) > 1), 
ordered AS ( 
    SELECT p.id, 
        created_at, 
        rank() OVER (partition BY p.id ORDER BY p.created_at) AS rnk 
    FROM products o 
    JOIN     duplicated d ON d.id = p.id ), 
products_to_delete AS ( 
    SELECT id, 
        created_at 
    FROM   ordered 
    WHERE  rnk = 2
) 
DELETE 
FROM products 
USING products_to_delete 
WHERE products.id = products_to_delete.id 
    AND products.created_at = products_to_delete.created_at;

How do I force make/GCC to show me the commands?

To invoke a dry run:

make -n

This will show what make is attempting to do.

Hide axis values but keep axis tick labels in matplotlib

If you use the matplotlib object-oriented approach, this is a simple task using ax.set_xticklabels() and ax.set_yticklabels():

import matplotlib.pyplot as plt

# Create Figure and Axes instances
fig,ax = plt.subplots(1)

# Make your plot, set your axes labels
ax.plot(sim_1['t'],sim_1['V'],'k')
ax.set_ylabel('V')
ax.set_xlabel('t')

# Turn off tick labels
ax.set_yticklabels([])
ax.set_xticklabels([])

plt.show()

How to use clock() in C++

clock() returns the number of clock ticks since your program started. There is a related constant, CLOCKS_PER_SEC, which tells you how many clock ticks occur in one second. Thus, you can test any operation like this:

clock_t startTime = clock();
doSomeOperation();
clock_t endTime = clock();
clock_t clockTicksTaken = endTime - startTime;
double timeInSeconds = clockTicksTaken / (double) CLOCKS_PER_SEC;

What does the return keyword do in a void method in Java?

The keyword simply pops a frame from the call stack returning the control to the line following the function call.

String contains - ignore case

You can use

org.apache.commons.lang3.StringUtils.containsIgnoreCase(CharSequence str,
                                     CharSequence searchStr);

Checks if CharSequence contains a search CharSequence irrespective of case, handling null. Case-insensitivity is defined as by String.equalsIgnoreCase(String).

A null CharSequence will return false.

This one will be better than regex as regex is always expensive in terms of performance.

For official doc, refer to : StringUtils.containsIgnoreCase

Update :

If you are among the ones who

  • don't want to use Apache commons library
  • don't want to go with the expensive regex/Pattern based solutions,
  • don't want to create additional string object by using toLowerCase,

you can implement your own custom containsIgnoreCase using java.lang.String.regionMatches

public boolean regionMatches(boolean ignoreCase,
                             int toffset,
                             String other,
                             int ooffset,
                             int len)

ignoreCase : if true, ignores case when comparing characters.

public static boolean containsIgnoreCase(String str, String searchStr)     {
    if(str == null || searchStr == null) return false;

    final int length = searchStr.length();
    if (length == 0)
        return true;

    for (int i = str.length() - length; i >= 0; i--) {
        if (str.regionMatches(true, i, searchStr, 0, length))
            return true;
    }
    return false;
}

How to create a css rule for all elements except one class?

The negation pseudo-class seems to be what you are looking for.

table:not(.dojoxGrid) {color:red;}

It's not supported by = IE8 though.

git-upload-pack: command not found, when cloning remote Git repo

Like Johan pointed out many times its .bashrc that's needed:

ln -s .bash_profile .bashrc

MATLAB error: Undefined function or method X for input arguments of type 'double'

You get this error when the function isn't on the MATLAB path or in pwd.

First, make sure that you are able to find the function using:

>> which divrat
c:\work\divrat\divrat.m

If it returns:

>> which divrat
'divrat' not found.

It is not on the MATLAB path or in PWD.

Second, make sure that the directory that contains divrat is on the MATLAB path using the PATH command. It may be that a directory that you thought was on the path isn't actually on the path.

Finally, make sure you aren't using a "private" directory. If divrat is in a directory named private, it will be accessible by functions in the parent directory, but not from the MATLAB command line:

>> foo

ans =

     1

>> divrat(1,1)
??? Undefined function or method 'divrat' for input arguments of type 'double'.

>> which -all divrat
c:\work\divrat\private\divrat.m  % Private to divrat

Java correct way convert/cast object to Double

You can't cast an object to a Double if the object is not a Double.

Check out the API.

particularly note

valueOf(double d);

and

valueOf(String s);

Those methods give you a way of getting a Double instance from a String or double primitive. (Also not the constructors; read the documentation to see how they work) The object you are trying to convert naturally has to give you something that can be transformed into a double.

Finally, keep in mind that Double instances are immutable -- once created you can't change them.

What is the difference between supervised learning and unsupervised learning?

In simple words.. :) It's my understanding, feel free to correct. Supervised learning is, we know what we are predicting on the basis of provided data. So we have a column in the dataset which needs to be predicated. Unsupervised learning is, we try to extract meaning out of the provided dataset. We don't have clarity on what to be predicted. So question is why we do this?.. :) Answer is - the outcome of Unsupervised learning is groups/clusters(similar data together). So if we receive any new data then we associate that with the identified cluster/group and understand it's features.

I hope it will help you.

Contain an image within a div?

#container img{
 height:100%;
 width:100%;   
}

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

Introduction: I have encountered such problem when was testing my fist network app. I created: Client and Server then I ran client and suddenly exception was thrown, indeed it blocks the connection, because the port is not being listened!

Error: My port was not listened by the server, because server was down.

Solution: Run the Server first, so the port will be listened by server and once client tries to connect the server will handle that.

How can I view array structure in JavaScript with alert()?

pass your js array to the function below and it will do the same as php print_r() function

 alert(print_r(your array));  //call it like this

function print_r(arr,level) {
var dumped_text = "";
if(!level) level = 0;

//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += "    ";

if(typeof(arr) == 'object') { //Array/Hashes/Objects 
    for(var item in arr) {
        var value = arr[item];

        if(typeof(value) == 'object') { //If it is an array,
            dumped_text += level_padding + "'" + item + "' ...\n";
            dumped_text += print_r(value,level+1);
        } else {
            dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
        }
    }
} else { //Stings/Chars/Numbers etc.
    dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}

C++: Where to initialize variables in constructor

Option 1 allows you to use a place specified exactly for explicitly initializing member variables.

How to $watch multiple variable change in angular

Angular 1.3 provides $watchGroup specifically for this purpose:

https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watchGroup

This seems to provide the same ultimate result as a standard $watch on an array of expressions. I like it because it makes the intention clearer in the code.

Java constructor/method with optional parameters?

Java doesn't have the concept of optional parameters with default values either in constructors or in methods. You're basically stuck with overloading. However, you chain constructors easily so you don't need to repeat the code:

public Foo(int param1, int param2)
{
    this.param1 = param1;
    this.param2 = param2;
}

public Foo(int param1)
{
    this(param1, 2);
}

When to use StringBuilder in Java

The problem with String concatenation is that it leads to copying of the String object with all the associated cost. StringBuilder is not threadsafe and is therefore faster than StringBuffer, which used to be the preferred choice before Java 5. As a rule of thumb, you should not do String concatenation in a loop, which will be called often. I guess doing a few concatenations here and there will not hurt you as long as you are not talking about hundreds and this of course depends on your performance requirements. If you are doing real time stuff, you should be very careful.

What is the most efficient way to store a list in the Django models?

Would this relationship not be better expressed as a one-to-many foreign key relationship to a Friends table? I understand that myFriends are just strings but I would think that a better design would be to create a Friend model and have MyClass contain a foreign key realtionship to the resulting table.

How do I get the App version and build number using Swift?

For Swift 3.0 NSBundle doesn't work, Following code works perfectly.

let versionNumberString =
      Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString")
          as! String

and for just the build number, it is:

let buildNumberString =
      Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion")
          as! String

Confusingly 'CFBundleVersion' is the build number as entered in Xcode on General->Identity.

Markdown and image alignment

Simplest is to wrap the image in a center tag, like so ...

<center>![Alt test](http://upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png)</center>

Anything to do with Markdown can be tested here - http://daringfireball.net/projects/markdown/dingus

Sure, <center> may be deprecated, but it's simple and it works!

android: changing option menu items programmatically

You can do something simple like I did. Just change the text to what is needed when the menu item is touched. I needed to turn the sound off and on, plus the ability to perform an action by touching it. Here is my code:

    @Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
    case R.id.audioOn:
        audioOn = !audioOn;
        if (audioOn)
            item.setTitle("Audio Off");
        else
            item.setTitle("Audio On");
        return true;

    case R.id.touchOn:
        touchOn = !touchOn;
        if (touchOn)
            item.setTitle("Touch Off");
        else
            item.setTitle("Touch On");
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

audioOn and touchOn are booleans checked in other parts of the code. Hope this helps.

Undo git stash pop that results in merge conflict

Instructions here are a little complicated so I'm going to offer something more straightforward:

  1. git reset HEAD --hard Abandon all changes to the current branch

  2. ... Perform intermediary work as necessary

  3. git stash pop Re-pop the stash again at a later date when you're ready

Adding 1 hour to time variable

You can try this code:

$time = '10:09';

echo date( 'H:i', strtotime( '+1 hour' , strtotime($time) ) );

Possible reason for NGINX 499 error codes

This doesn't answer the OPs question, but since I ended up here after searching furiously for an answer, I wanted to share what we discovered.

In our case, it turns out these 499s are expected. When users use the type-ahead feature in some search boxes, for example, we see something like this in the logs.

GET /api/search?q=h [Status 499] 
GET /api/search?q=he [Status 499]
GET /api/search?q=hel [Status 499]
GET /api/search?q=hell [Status 499]
GET /api/search?q=hello [Status 200]

So in our case I think its safe to use proxy_ignore_client_abort on which was suggested in a previous answer. Thanks for that!

Enable Hibernate logging

Your log4j.properties file should be on the root level of your capitolo2.ear (not in META-INF), that is, here:

MyProject
¦   build.xml
¦   
+---build
¦   ¦   capitolo2-ejb.jar
¦   ¦   capitolo2-war.war
¦   ¦   JBoss4.dpf
¦   ¦   log4j.properties

Div show/hide media query

It sounds like you may be wanting to access the viewport of the device. You can do this by inserting this meta tag in your header.

<meta name="viewport" content="width=device-width, initial-scale=1.0">

http://www.w3schools.com/css/css_rwd_viewport.asp

How to determine if string contains specific substring within the first X characters

You can also use regular expressions (less readable though)

string regex = "^.{0,7}abc";

System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(regex);
string Value1 = "sssddabcgghh";

Console.WriteLine(reg.Match(Value1).Success);

Express.js - app.listen vs server.listen

Express is basically a wrapper of http module that is created for the ease of the developers in such a way that..

  1. They can set up middlewares to respond to HTTP Requests (easily) using express.
  2. They can dynamically render HTML Pages based on passing arguments to templates using express.
  3. They can also define routing easily using express.

Unknown Column In Where Clause

Either:

SELECT u_name AS user_name
FROM   users
WHERE  u_name = "john";

or:

SELECT user_name
from
(
SELECT u_name AS user_name
FROM   users
)
WHERE  u_name = "john";

The latter ought to be the same as the former if the RDBMS supports predicate pushing into the in-line view.

Get text of label with jquery

try document.getElementById('<%=Label1.ClientID%>').text or innerHTML OTHERWISE LOAD JQUERY SCRIPT AND put your code as it is....

How to pause javascript code execution for 2 seconds

You can use setTimeout to do this

function myFunction() {
    // your code to run after the timeout
}

// stop for sometime if needed
setTimeout(myFunction, 5000);

Custom method names in ASP.NET Web API

In case you're using ASP.NET 5 with ASP.NET MVC 6, most of these answers simply won't work because you'll normally let MVC create the appropriate route collection for you (using the default RESTful conventions), meaning that you won't find any Routes.MapRoute() call to edit at will.

The ConfigureServices() method invoked by the Startup.cs file will register MVC with the Dependency Injection framework built into ASP.NET 5: that way, when you call ApplicationBuilder.UseMvc() later in that class, the MVC framework will automatically add these default routes to your app. We can take a look of what happens behind the hood by looking at the UseMvc() method implementation within the framework source code:

public static IApplicationBuilder UseMvc(
    [NotNull] this IApplicationBuilder app,
    [NotNull] Action<IRouteBuilder> configureRoutes)
{
    // Verify if AddMvc was done before calling UseMvc
    // We use the MvcMarkerService to make sure if all the services were added.
    MvcServicesHelper.ThrowIfMvcNotRegistered(app.ApplicationServices);

    var routes = new RouteBuilder
    {
        DefaultHandler = new MvcRouteHandler(),
        ServiceProvider = app.ApplicationServices
    };

    configureRoutes(routes);

    // Adding the attribute route comes after running the user-code because
    // we want to respect any changes to the DefaultHandler.
    routes.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(
        routes.DefaultHandler,
        app.ApplicationServices));

    return app.UseRouter(routes.Build());
}

The good thing about this is that the framework now handles all the hard work, iterating through all the Controller's Actions and setting up their default routes, thus saving you some redundant work.

The bad thing is, there's little or no documentation about how you could add your own routes. Luckily enough, you can easily do that by using either a Convention-Based and/or an Attribute-Based approach (aka Attribute Routing).

Convention-Based

In your Startup.cs class, replace this:

app.UseMvc();

with this:

app.UseMvc(routes =>
            {
                // Route Sample A
                routes.MapRoute(
                    name: "RouteSampleA",
                    template: "MyOwnGet",
                    defaults: new { controller = "Items", action = "Get" }
                );
                // Route Sample B
                routes.MapRoute(
                    name: "RouteSampleB",
                    template: "MyOwnPost",
                    defaults: new { controller = "Items", action = "Post" }
                );
            });

Attribute-Based

A great thing about MVC6 is that you can also define routes on a per-controller basis by decorating either the Controller class and/or the Action methods with the appropriate RouteAttribute and/or HttpGet / HttpPost template parameters, such as the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;

namespace MyNamespace.Controllers
{
    [Route("api/[controller]")]
    public class ItemsController : Controller
    {
        // GET: api/items
        [HttpGet()]
        public IEnumerable<string> Get()
        {
            return GetLatestItems();
        }

        // GET: api/items/5
        [HttpGet("{num}")]
        public IEnumerable<string> Get(int num)
        {
            return GetLatestItems(5);
        }       

        // GET: api/items/GetLatestItems
        [HttpGet("GetLatestItems")]
        public IEnumerable<string> GetLatestItems()
        {
            return GetLatestItems(5);
        }

        // GET api/items/GetLatestItems/5
        [HttpGet("GetLatestItems/{num}")]
        public IEnumerable<string> GetLatestItems(int num)
        {
            return new string[] { "test", "test2" };
        }

        // POST: /api/items/PostSomething
        [HttpPost("PostSomething")]
        public IActionResult Post([FromBody]string someData)
        {
            return Content("OK, got it!");
        }
    }
}

This controller will handle the following requests:

 [GET] api/items
 [GET] api/items/5
 [GET] api/items/GetLatestItems
 [GET] api/items/GetLatestItems/5
 [POST] api/items/PostSomething

Also notice that if you use the two approaches togheter, Attribute-based routes (when defined) would override Convention-based ones, and both of them would override the default routes defined by UseMvc().

For more info, you can also read the following post on my blog.

How do you convert a time.struct_time object into a datetime object?

This is not a direct answer to your question (which was answered pretty well already). However, having had times bite me on the fundament several times, I cannot stress enough that it would behoove you to look closely at what your time.struct_time object is providing, vs. what other time fields may have.

Assuming you have both a time.struct_time object, and some other date/time string, compare the two, and be sure you are not losing data and inadvertently creating a naive datetime object, when you can do otherwise.

For example, the excellent feedparser module will return a "published" field and may return a time.struct_time object in its "published_parsed" field:

time.struct_time(tm_year=2013, tm_mon=9, tm_mday=9, tm_hour=23, tm_min=57, tm_sec=42, tm_wday=0, tm_yday=252, tm_isdst=0)

Now note what you actually get with the "published" field.

Mon, 09 Sep 2013 19:57:42 -0400

By Stallman's Beard! Timezone information!

In this case, the lazy man might want to use the excellent dateutil module to keep the timezone information:

from dateutil import parser
dt = parser.parse(entry["published"])
print "published", entry["published"])
print "dt", dt
print "utcoffset", dt.utcoffset()
print "tzinfo", dt.tzinfo
print "dst", dt.dst()

which gives us:

published Mon, 09 Sep 2013 19:57:42 -0400
dt 2013-09-09 19:57:42-04:00
utcoffset -1 day, 20:00:00
tzinfo tzoffset(None, -14400)
dst 0:00:00

One could then use the timezone-aware datetime object to normalize all time to UTC or whatever you think is awesome.

How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()?

var fs = require("fs");
var filename = "./index.html";

function start(resp) {
    resp.writeHead(200, {
        "Content-Type": "text/html"
    });
    fs.readFile(filename, "utf8", function(err, data) {
        if (err) throw err;
        resp.write(data);
        resp.end();
    });
}

Converting a string to int in Groovy

def str = "32"

int num = str as Integer

How do I install cygwin components from the command line?

First, download installer at: https://cygwin.com/setup-x86_64.exe (Windows 64bit), then:

# move installer to cygwin folder
mv C:/Users/<you>/Downloads/setup-x86_64.exe C:/cygwin64/

# add alias to bash_aliases
echo "alias cygwin='C:/cygwin64/setup-x86_64.exe -q -P'" >> ~/.bash_aliases
source ~/.bash_aliases

# add bash_aliases to bashrc if missing
echo "source ~/.bash_aliases" >> ~/.profile

e.g.

# install vim
cygwin vim

# see other options
cygwin --help

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

This problem is usually caused by one of the following

  • null values being returned for columns not set to AllowDBNull
  • duplicate rows being returned with the same primary key.
  • a mismatch in column definition (e.g. size of char fields) between the database and the dataset

Try running your query natively and look at the results, if the resultset is not too large. If you've eliminated null values, then my guess is that the primary key columns is being duplicated.

Or, to see the exact error, you can manually add a Try/Catch block to the generated code like so and then breaking when the exception is raised:

enter image description here

Then within the command window, call GetErrors method on the table getting the error.
For C#, the command would be ? dataTable.GetErrors()
For VB, the command is ? dataTable.GetErrors

enter image description here

This will show you all datarows which have an error. You can get then look at the RowError for each of these, which should tell you the column that's invalid along with the problem. So, to see the error of the first datarow in error the command is:
? dataTable.GetErrors(0).RowError
or in C# it would be ? dataTable.GetErrors()[0].RowError

enter image description here

Swift - How to detect orientation changes

You can use viewWillTransition(to:with:) and tap into animate(alongsideTransition:completion:) to get the interface orientation AFTER the transition is complete. You just have to define and implement a protocol similar to this in order to tap into the event. Note that this code was used for a SpriteKit game and your specific implementation may differ.

protocol CanReceiveTransitionEvents {
    func viewWillTransition(to size: CGSize)
    func interfaceOrientationChanged(to orientation: UIInterfaceOrientation)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)

        guard
            let skView = self.view as? SKView,
            let canReceiveRotationEvents = skView.scene as? CanReceiveTransitionEvents else { return }

        coordinator.animate(alongsideTransition: nil) { _ in
            if let interfaceOrientation = UIApplication.shared.windows.first?.windowScene?.interfaceOrientation {
                canReceiveRotationEvents.interfaceOrientationChanged(to: interfaceOrientation)
            }
        }

        canReceiveRotationEvents.viewWillTransition(to: size)
    }

You can set breakpoints in these functions and observe that interfaceOrientationChanged(to orientation: UIInterfaceOrientation) is always called after viewWillTransition(to size: CGSize) with the updated orientation.

Override browser form-filling and input highlighting with HTML/CSS

The form element has an autocomplete attribute that you can set to off. As of the CSS the !important directive after a property keeps it from being overriden:

background-color: white !important;

Only IE6 doesn't understand it.

If I misunderstood you, there's also the outline property that you could find useful.

Removing elements with Array.map in JavaScript

You should use the filter method rather than map unless you want to mutate the items in the array, in addition to filtering.

eg.

var filteredItems = items.filter(function(item)
{
    return ...some condition...;
});

[Edit: Of course you could always do sourceArray.filter(...).map(...) to both filter and mutate]

How to JOIN three tables in Codeigniter

public function getdata(){
        $this->db->select('c.country_name as country, s.state_name as state, ct.city_name as city, t.id as id');
        $this->db->from('tblmaster t'); 
        $this->db->join('country c', 't.country=c.country_id');
        $this->db->join('state s', 't.state=s.state_id');
        $this->db->join('city ct', 't.city=ct.city_id');
        $this->db->order_by('t.id','desc');
        $query = $this->db->get();      
        return $query->result();
}

How to disable text selection using jQuery?

I found this answer ( Prevent Highlight of Text Table ) most helpful, and perhaps it can be combined with another way of providing IE compatibility.

#yourTable
{
  -moz-user-select: none;
  -khtml-user-select: none;
  -webkit-user-select: none;
  user-select: none;
}

How to split one text file into multiple *.txt files?

If each part have the same lines number, for example 22, here my solution:
split --numeric-suffixes=2 --additional-suffix=.txt -l 22 file.txt file
and you obtain file2.txt with the first 22 lines, file3.txt the 22 next line…

Thank @hamruta-takawale, @dror-s and @stackoverflowuser2010

/usr/lib/x86_64-linux-gnu/libstdc++.so.6: version CXXABI_1.3.8' not found

I've got correct solution here.

The best way to correctly install gcc-4.9 and set it as your default gcc version use:

sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt-get update
sudo apt-get install gcc-4.9 g++-4.9
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.9 60 --slave /usr/bin/g++ g++ /usr/bin/g++-4.9

The --slave, with g++, will cause g++ to be switched along with gcc, to the same version. But, at this point gcc-4.9 will be your only version configured in update-alternatives, so add 4.8 to update-alternatives, so there actually is an alternative, by using:

sudo apt-get install gcc-4.8 g++-4.8
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.8 60 --slave /usr/bin/g++ g++ /usr/bin/g++-4.8

Then you can check which one that is set, and change back and forth using:

sudo update-alternatives --config gcc

NOTE: You could skip installing the PPA Repository and just use /usr/bin/gcc-4.9-base but I prefer using the fresh updated toolchains.

Program to find largest and smallest among 5 numbers without using array

For example 5 consecutive numbers

int largestNumber;
int smallestNumber;
int number;
std::cin>>number;
largestNumber = number;
smallestNumber = number;
for (i=0 ; i<5; i++)
{
   std::cin>>number;
   if (number > largestNumber) 
   {
     largest = number;
   }
   if (numbers < smallestNumber) 
   {
     smallestNumber= number;
   }
}

Updating property value in properties file without deleting other values

Open the output stream and store properties after you have closed the input stream.

FileInputStream in = new FileInputStream("First.properties");
Properties props = new Properties();
props.load(in);
in.close();

FileOutputStream out = new FileOutputStream("First.properties");
props.setProperty("country", "america");
props.store(out, null);
out.close();

Datatables warning(table id = 'example'): cannot reinitialise data table

You can add destroy:true to the configuration to make sure data table already present is removed before being reinitialized.

$('#example').dataTable({
    destroy: true,
    ...
});

Setting Icon for wpf application (VS 08)

@742's answer works pretty well, but as outlined in the comments when running from the VS debugger the generic icon is still shown.

If you want to have your icon even when you're pressing F5, you can add in the Main Window:

<Window x:Class="myClass"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Icon="./Resources/Icon/myIcon.png">

where you indicate the path to your icon (the icon can be *.png, *.ico.)

(Note you will still need to set the Application Icon or it'll still be the default in Explorer).

Github Push Error: RPC failed; result=22, HTTP code = 413

I had the same issue (on Win XP), I updated the libcurl-4.dll file in my Git bin directory to the SSL version from http://www.paehl.com/open_source/?download=curl_DLL_ONLY.7z (renaming to libcurl4.dll). All working ok now.

React native ERROR Packager can't listen on port 8081

in my case, internet on emulator is down as there is no wifi signal on emulator. Resetting emulator has worked.

Fastest way to copy a file in Node.js

Well, usually it is good to avoid asynchronous file operations. Here is the short (i.e. no error handling) sync example:

var fs = require('fs');
fs.writeFileSync(targetFile, fs.readFileSync(sourceFile));

Does overflow:hidden applied to <body> work on iPhone Safari?

html {
  position:relative;
  top:0px;
  left:0px;
  overflow:auto;
  height:auto
}

add this as default to your css

.class-on-html{
  position:fixed;
  top:0px;
  left:0px;
  overflow:hidden;
  height:100%;
}

toggleClass this class to to cut page

when you turn off this class first line will call scrolling bar back

Dynamically create checkbox with JQuery from text input

<div id="cblist">
    <input type="checkbox" value="first checkbox" id="cb1" /> <label for="cb1">first checkbox</label>
</div>

<input type="text" id="txtName" />
<input type="button" value="ok" id="btnSave" />

<script type="text/javascript">
$(document).ready(function() {
    $('#btnSave').click(function() {
        addCheckbox($('#txtName').val());
    });
});

function addCheckbox(name) {
   var container = $('#cblist');
   var inputs = container.find('input');
   var id = inputs.length+1;

   $('<input />', { type: 'checkbox', id: 'cb'+id, value: name }).appendTo(container);
   $('<label />', { 'for': 'cb'+id, text: name }).appendTo(container);
}
</script>

Need to ZIP an entire directory using Node.js

Adm-zip has problems just compressing an existing archive https://github.com/cthackers/adm-zip/issues/64 as well as corruption with compressing binary files.

I've also ran into compression corruption issues with node-zip https://github.com/daraosn/node-zip/issues/4

node-archiver is the only one that seems to work well to compress but it doesn't have any uncompress functionality.

How to run a PowerShell script from a batch file

If you run a batch file calling PowerShell as a administrator, you better run it like this, saving you all the trouble:

powershell.exe -ExecutionPolicy Bypass -Command "Path\xxx.ps1"

It is better to use Bypass...

Downloading jQuery UI CSS from Google's CDN

Google is hosting jQueryUI css at this link https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery.ui.all.css

If you look at this code directly, it is importing the css using @import which can be slow. You may want to factor the import into its parts to gain a slight performance benefit:

https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery.ui.base.css https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery.ui.theme.css

How to re-index all subarray elements of a multidimensional array?

$result = ['5' => 'cherry', '7' => 'apple'];
array_multisort($result, SORT_ASC);
print_r($result);

Array ( [0] => apple [1] => cherry )

//...
array_multisort($result, SORT_DESC);
//...

Array ( [0] => cherry [1] => apple )

How can I create a Java method that accepts a variable number of arguments?

You can pass all similar type values in the function while calling it. In the function definition put a array so that all the passed values can be collected in that array. e.g. .

static void demo (String ... stringArray) {
  your code goes here where read the array stringArray
}

Google Maps API OVER QUERY LIMIT per second limit

Often when you need to show so many points on the map, you'd be better off using the server-side approach, this article explains when to use each:

Geocoding Strategies: https://developers.google.com/maps/articles/geocodestrat

The client-side limit is not exactly "10 requests per second", and since it's not explained in the API docs I wouldn't rely on its behavior.

disable a hyperlink using jQuery

Below will replace the link with it's text

$('a').each(function () {
    $(this).replaceWith($(this).text());
});

Edit :

Above given code will work with hyperlinks with text only, it will not work with images. When we'll try it with image link it won't show any image.

To make this code compatible with image links following will work fine

// below given function will replace links with images i.e. for image links
$('a img').each(function () {
    var image = this.src;
    var img = $('<img>', { src: image });
    $(this).parent().replaceWith(img);
});

// This piece of code will replace links with its text i.e. for text links
$('a').each(function () {
    $(this).replaceWith($(this).text());
});

explanation : In above given code snippets, in first snippet we are replacing all the image links with it's images only. After that we are replacing text links with it's text.

How to cache data in a MVC application

Reference the System.Web dll in your model and use System.Web.Caching.Cache

    public string[] GetNames()
    {
      string[] names = Cache["names"] as string[];
      if(names == null) //not in cache
      {
        names = DB.GetNames();
        Cache["names"] = names;
      }
      return names;
    }

A bit simplified but I guess that would work. This is not MVC specific and I have always used this method for caching data.

Convert DataTable to IEnumerable<T>

I wrote an article on this subject over here. I think it could help you.

Typically it's doing something like that:

static void Main(string[] args)
{
    // Convert from a DataTable source to an IEnumerable.
    var usersSourceDataTable = CreateMockUserDataTable();
    var usersConvertedList = usersSourceDataTable.ToEnumerable<User>();

    // Convert from an IEnumerable source to a DataTable.
    var usersSourceList = CreateMockUserList();
    var usersConvertedDataTable = usersSourceList.ToDataTable<User>();
}

Destroy or remove a view in Backbone.js

I know I am late to the party, but hopefully this will be useful for someone else. If you are using backbone v0.9.9+, you could use, listenTo and stopListening

initialize: function () {
    this.listenTo(this.model, 'change', this.render);
    this.listenTo(this.model, 'destroy', this.remove);
}

stopListening is called automatically by remove. You can read more here and here

Purpose of returning by const value?

In the hypothetical situation where you could perform a potentially expensive non-const operation on an object, returning by const-value prevents you from accidentally calling this operation on a temporary. Imagine that + returned a non-const value, and you could write:

(a + b).expensive();

In the age of C++11, however, it is strongly advised to return values as non-const so that you can take full advantage of rvalue references, which only make sense on non-constant rvalues.

In summary, there is a rationale for this practice, but it is essentially obsolete.

Can I grep only the first n lines of a file?

grep -A 10 <Pattern>

This is to grab the pattern and the next 10 lines after the pattern. This would work well only for a known pattern, if you don't have a known pattern use the "head" suggestions.

Adding a Method to an Existing Object Instance

In Python monkeypatching generally works by overwriting a class or function's signature with your own. Below is an example from the Zope Wiki:

from SomeOtherProduct.SomeModule import SomeClass
def speak(self):
   return "ook ook eee eee eee!"
SomeClass.speak = speak

This code will overwrite/create a method called peak in the class. In Jeff Atwood's recent post on monkey patching, he showed an example in C# 3.0 which is the current language I use for work.

Best way to convert string to bytes in Python 3?

It's easier than it is thought:

my_str = "hello world"
my_str_as_bytes = str.encode(my_str)
type(my_str_as_bytes) # ensure it is byte representation
my_decoded_str = my_str_as_bytes.decode()
type(my_decoded_str) # ensure it is string representation

Selecting multiple items in ListView

This example stores the values you have checked and displays them in a toast. And it updates when you uncheck items http://android-coding.blogspot.ro/2011/09/listview-with-multiple-choice.html

Make div (height) occupy parent remaining height

I'm not sure it can be done purely with CSS, unless you're comfortable in sort of faking it with illusions. Maybe use Josh Mein's answer, and set #container to overflow:hidden.

For what it's worth, here's a jQuery solution:

var contH = $('#container').height(),
upH = $('#up').height();
$('#down').css('height' , contH - upH);

What is the difference between XAMPP or WAMP Server & IIS?

In addition to the above, WAMP supports 64 bit PHP on Windows systems while XAMPP only offers 32 bit versions. This actually made me switch to WAMP on my Windows machine since you need 64 bit PHP 7 to get bigint numbers correctly from MySQL

Specific Time Range Query in SQL Server

select * from table where 
(dtColumn between #3/1/2009# and #3/31/2009#) and 
(hour(dtColumn) between 6 and 22) and 
(weekday(dtColumn, 1) between 2 and 4) 

Plotting a fast Fourier transform in Python

So I run a functionally equivalent form of your code in an IPython notebook:

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack

# Number of samplepoints
N = 600
# sample spacing
T = 1.0 / 800.0
x = np.linspace(0.0, N*T, N)
y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)
yf = scipy.fftpack.fft(y)
xf = np.linspace(0.0, 1.0/(2.0*T), N/2)

fig, ax = plt.subplots()
ax.plot(xf, 2.0/N * np.abs(yf[:N//2]))
plt.show()

I get what I believe to be very reasonable output.

enter image description here

It's been longer than I care to admit since I was in engineering school thinking about signal processing, but spikes at 50 and 80 are exactly what I would expect. So what's the issue?

In response to the raw data and comments being posted

The problem here is that you don't have periodic data. You should always inspect the data that you feed into any algorithm to make sure that it's appropriate.

import pandas
import matplotlib.pyplot as plt
#import seaborn
%matplotlib inline

# the OP's data
x = pandas.read_csv('http://pastebin.com/raw.php?i=ksM4FvZS', skiprows=2, header=None).values
y = pandas.read_csv('http://pastebin.com/raw.php?i=0WhjjMkb', skiprows=2, header=None).values
fig, ax = plt.subplots()
ax.plot(x, y)

enter image description here

Dynamically load a JavaScript file

For those of you, who love one-liners:

import('./myscript.js');

Chances are you might get an error, like:

Access to script at 'http://..../myscript.js' from origin 'http://127.0.0.1' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

In which case, you can fallback to:

fetch('myscript.js').then(r => r.text()).then(t => new Function(t)());

How to create/read/write JSON files in Qt5

Sadly, many JSON C++ libraries have APIs that are non trivial to use, while JSON was intended to be easy to use.

So I tried jsoncpp from the gSOAP tools on the JSON doc shown in one of the answers above and this is the code generated with jsoncpp to construct a JSON object in C++ which is then written in JSON format to std::cout:

value x(ctx);
x["appDesc"]["description"] = "SomeDescription";
x["appDesc"]["message"] = "SomeMessage";
x["appName"]["description"] = "Home";
x["appName"]["message"] = "Welcome";
x["appName"]["imp"][0] = "awesome";
x["appName"]["imp"][1] = "best";
x["appName"]["imp"][2] = "good";
std::cout << x << std::endl;

and this is the code generated by jsoncpp to parse JSON from std::cin and extract its values (replace USE_VAL as needed):

value x(ctx);
std::cin >> x;
if (x.soap->error)
  exit(EXIT_FAILURE); // error parsing JSON
#define USE_VAL(path, val) std::cout << path << " = " << val << std::endl
if (x.has("appDesc"))
{
  if (x["appDesc"].has("description"))
    USE_VAL("$.appDesc.description", x["appDesc"]["description"]);
  if (x["appDesc"].has("message"))
    USE_VAL("$.appDesc.message", x["appDesc"]["message"]);
}
if (x.has("appName"))
{
  if (x["appName"].has("description"))
    USE_VAL("$.appName.description", x["appName"]["description"]);
  if (x["appName"].has("message"))
    USE_VAL("$.appName.message", x["appName"]["message"]);
  if (x["appName"].has("imp"))
  {
    for (int i2 = 0; i2 < x["appName"]["imp"].size(); i2++)
      USE_VAL("$.appName.imp[]", x["appName"]["imp"][i2]);
  }
}

This code uses the JSON C++ API of gSOAP 2.8.28. I don't expect people to change libraries, but I think this comparison helps to put JSON C++ libraries in perspective.

Looping over arrays, printing both index and value

You would find the array keys with "${!foo[@]}" (reference), so:

for i in "${!foo[@]}"; do 
  printf "%s\t%s\n" "$i" "${foo[$i]}"
done

Which means that indices will be in $i while the elements themselves have to be accessed via ${foo[$i]}

How to copy a map?

You are not copying the map, but the reference to the map. Your delete thus modifies the values in both your original map and the super map. To copy a map, you have to use a for loop like this:

for k,v := range originalMap {
  newMap[k] = v
}

Here's an example from the now-retired SO documentation:

// Create the original map
originalMap := make(map[string]int)
originalMap["one"] = 1
originalMap["two"] = 2

// Create the target map
targetMap := make(map[string]int)

// Copy from the original map to the target map
for key, value := range originalMap {
  targetMap[key] = value
}

Excerpted from Maps - Copy a Map. The original author was JepZ. Attribution details can be found on the contributor page. The source is licenced under CC BY-SA 3.0 and may be found in the Documentation archive. Reference topic ID: 732 and example ID: 9834.

forEach is not a function error with JavaScript array

Since you are using features of ES6 (arrow functions), you may also simply use a for loop like this:

_x000D_
_x000D_
for(let child of [{0: [{'a':1,'b':2},{'c':3}]},{1:[]}]) {_x000D_
  console.log(child)_x000D_
}
_x000D_
_x000D_
_x000D_

Eclipse: Error ".. overlaps the location of another project.." when trying to create new project

Eclipse is erroring because if you try and create a project on a directory that exists, Eclipse doesn't know if it's an actual project or not - so it errors, saving you from losing work!

So you have two solutions:

  1. Move the folder counter_src somewhere else, then create the project (which will create the directory), then import the source files back into the newly created counter_src.

  2. Right-click on the project explorer and import an existing project, select C:\Users\Martin\Java\Counter\ as your root directory. If Eclipse sees a project, you will be able to import it.

How Big can a Python List Get?

Performance characteristics for lists are described on Effbot.

Python lists are actually implemented as vector for fast random access, so the container will basically hold as many items as there is space for in memory. (You need space for pointers contained in the list as well as space in memory for the object(s) being pointed to.)

Appending is O(1) (amortized constant complexity), however, inserting into/deleting from the middle of the sequence will require an O(n) (linear complexity) reordering, which will get slower as the number of elements in your list.

Your sorting question is more nuanced, since the comparison operation can take an unbounded amount of time. If you're performing really slow comparisons, it will take a long time, though it's no fault of Python's list data type.

Reversal just takes the amount of time it required to swap all the pointers in the list (necessarily O(n) (linear complexity), since you touch each pointer once).

How to tag an older commit in Git?

This is an old question, and the answers already given all work, but there's also a new option which can be considered.

If you're using SourceTree to manage your git repositories, you can right-click on any commit and add a tag to it. With another mouseclick you can also send the tag straight to the branch on origin.

How can I check if an InputStream is empty without reading from it?

Based on the suggestion of using the PushbackInputStream, you'll find an exemple implementation here:

/**
 * @author Lorber Sebastien <i>([email protected])</i>
 */
public class NonEmptyInputStream extends FilterInputStream {

  /**
   * Once this stream has been created, do not consume the original InputStream 
   * because there will be one missing byte...
   * @param originalInputStream
   * @throws IOException
   * @throws EmptyInputStreamException
   */
  public NonEmptyInputStream(InputStream originalInputStream) throws IOException, EmptyInputStreamException {
    super( checkStreamIsNotEmpty(originalInputStream) );
  }


  /**
   * Permits to check the InputStream is empty or not
   * Please note that only the returned InputStream must be consummed.
   *
   * see:
   * http://stackoverflow.com/questions/1524299/how-can-i-check-if-an-inputstream-is-empty-without-reading-from-it
   *
   * @param inputStream
   * @return
   */
  private static InputStream checkStreamIsNotEmpty(InputStream inputStream) throws IOException, EmptyInputStreamException {
    Preconditions.checkArgument(inputStream != null,"The InputStream is mandatory");
    PushbackInputStream pushbackInputStream = new PushbackInputStream(inputStream);
    int b;
    b = pushbackInputStream.read();
    if ( b == -1 ) {
      throw new EmptyInputStreamException("No byte can be read from stream " + inputStream);
    }
    pushbackInputStream.unread(b);
    return pushbackInputStream;
  }

  public static class EmptyInputStreamException extends RuntimeException {
    public EmptyInputStreamException(String message) {
      super(message);
    }
  }

}

And here are some passing tests:

  @Test(expected = EmptyInputStreamException.class)
  public void test_check_empty_input_stream_raises_exception_for_empty_stream() throws IOException {
    InputStream emptyStream = new ByteArrayInputStream(new byte[0]);
    new NonEmptyInputStream(emptyStream);
  }

  @Test
  public void test_check_empty_input_stream_ok_for_non_empty_stream_and_returned_stream_can_be_consummed_fully() throws IOException {
    String streamContent = "HELLooooô wörld";
    InputStream inputStream = IOUtils.toInputStream(streamContent, StandardCharsets.UTF_8);
    inputStream = new NonEmptyInputStream(inputStream);
    assertThat(IOUtils.toString(inputStream,StandardCharsets.UTF_8)).isEqualTo(streamContent);
  }

Fixing "Lock wait timeout exceeded; try restarting transaction" for a 'stuck" Mysql table?

Goto processes in mysql.

So can see there is task still working.

Kill the particular process or wait until process complete.

How to restore PostgreSQL dump file into Postgres databases?

The problem with your attempt at the psql command line is the direction of the slashes:

newTestDB-# /i E:\db-rbl-restore-20120511_Dump-20120514.sql   # incorrect
newTestDB-# \i E:/db-rbl-restore-20120511_Dump-20120514.sql   # correct

To be clear, psql commands start with a backslash, so you should have put \i instead. What happened as a result of your typo is that psql ignored everything until finding the first \, which happened to be followed by db, and \db happens to be the psql command for listing table spaces, hence why the output was a List of tablespaces. It was not a listing of "default tables of PostgreSQL" as you said.

Further, it seems that psql expects the filepath argument to delimit directories using the forward slash regardless of OS (thus on Windows this would be counter-intuitive).

It is worth noting that your attempt at "elevating permissions" had no relation to the outcome of the command you attempted to execute. Also, you did not say what caused the supposed "Permission Denied" error.

Finally, the extension on the dump file does not matter, in fact you don't even need an extension. Indeed, pgAdmin suggests a .backup extension when selecting a backup filename, but you can actually make it whatever you want, again, including having no extension at all. The problem is that pgAdmin seems to only allow a "Restore" of "Custom or tar" or "Directory" dumps (at least this is the case in the MAC OS X version of the app), so just use the psql \i command as shown above.

Assigning default values to shell variables with a single command in bash

For command line arguments:

VARIABLE="${1:-$DEFAULTVALUE}"

which assigns to VARIABLE the value of the 1st argument passed to the script or the value of DEFAULTVALUE if no such argument was passed. Qouting prevents globbing and word splitting.

How to set default value for column of new created table from select statement in 11g

The reason is that CTAS (Create table as select) does not copy any metadata from the source to the target table, namely

  • no primary key
  • no foreign keys
  • no grants
  • no indexes
  • ...

To achieve what you want, I'd either

  • use dbms_metadata.get_ddl to get the complete table structure, replace the table name with the new name, execute this statement, and do an INSERT afterward to copy the data
  • or keep using CTAS, extract the not null constraints for the source table from user_constraints and add them to the target table afterwards

When do we need curly braces around shell variables?

You are also able to do some text manipulation inside the braces:

STRING="./folder/subfolder/file.txt"
echo ${STRING} ${STRING%/*/*}

Result:

./folder/subfolder/file.txt ./folder

or

STRING="This is a string"
echo ${STRING// /_}

Result:

This_is_a_string

You are right in "regular variables" are not needed... But it is more helpful for the debugging and to read a script.

Using comma as list separator with AngularJS

Just use Javascript's built-in join(separator) function for arrays:

<li ng-repeat="friend in friends">
  <b>{{friend.email.join(', ')}}</b>...
</li>

Why use #define instead of a variable

The #define allows you to establish a value in a header that would otherwise compile to size-greater-than-zero. Your headers should not compile to size-greater-than-zero.

// File:  MyFile.h

// This header will compile to size-zero.
#define TAX_RATE 0.625

// NO:  static const double TAX_RATE = 0.625;
// NO:  extern const double TAX_RATE;  // WHAT IS THE VALUE?

EDIT: As Neil points out in the comment to this post, the explicit definition-with-value in the header would work for C++, but not C.

List Highest Correlation Pairs from a Large Correlation Matrix in Pandas?

I didn't want to unstack or over-complicate this issue, since I just wanted to drop some highly correlated features as part of a feature selection phase.

So I ended up with the following simplified solution:

# map features to their absolute correlation values
corr = features.corr().abs()

# set equality (self correlation) as zero
corr[corr == 1] = 0

# of each feature, find the max correlation
# and sort the resulting array in ascending order
corr_cols = corr.max().sort_values(ascending=False)

# display the highly correlated features
display(corr_cols[corr_cols > 0.8])

In this case, if you want to drop correlated features, you may map through the filtered corr_cols array and remove the odd-indexed (or even-indexed) ones.

Django 1.7 - makemigrations not detecting changes

I have encountered this issue, the command

python manage.py makemigrations

worked with me once I saved the changes that I made on the files.

Add line break to ::after or ::before pseudo-element content

I had to have new lines in a tooltip. I had to add this CSS on my :after :

.tooltip:after {
  width: 500px;
  white-space: pre;
  word-wrap: break-word;
}

The word-wrap seems necessary.

In addition, the \A didn't work in the middle of the text to display, to force a new line.

 &#13;&#10; 

worked. I was then able to get such a tooltip :

enter image description here

How can I get href links from HTML using Python?

Try with Beautifulsoup:

from BeautifulSoup import BeautifulSoup
import urllib2
import re

html_page = urllib2.urlopen("http://www.yourwebsite.com")
soup = BeautifulSoup(html_page)
for link in soup.findAll('a'):
    print link.get('href')

In case you just want links starting with http://, you should use:

soup.findAll('a', attrs={'href': re.compile("^http://")})

In Python 3 with BS4 it should be:

from bs4 import BeautifulSoup
import urllib.request

html_page = urllib.request.urlopen("http://www.yourwebsite.com")
soup = BeautifulSoup(html_page, "html.parser")
for link in soup.findAll('a'):
    print(link.get('href'))

How can I search sub-folders using glob.glob module?

Here is a adapted version that enables glob.glob like functionality without using glob2.

def find_files(directory, pattern='*'):
    if not os.path.exists(directory):
        raise ValueError("Directory not found {}".format(directory))

    matches = []
    for root, dirnames, filenames in os.walk(directory):
        for filename in filenames:
            full_path = os.path.join(root, filename)
            if fnmatch.filter([full_path], pattern):
                matches.append(os.path.join(root, filename))
    return matches

So if you have the following dir structure

tests/files
+-- a0
¦   +-- a0.txt
¦   +-- a0.yaml
¦   +-- b0
¦       +-- b0.yaml
¦       +-- b00.yaml
+-- a1

You can do something like this

files = utils.find_files('tests/files','**/b0/b*.yaml')
> ['tests/files/a0/b0/b0.yaml', 'tests/files/a0/b0/b00.yaml']

Pretty much fnmatch pattern match on the whole filename itself, rather than the filename only.

MySQL stored procedure vs function, which would I use when?

A stored function can be used within a query. You could then apply it to every row, or within a WHERE clause.

A procedure is executed using the CALL query.

How to recursively find and list the latest modified files in a directory with subdirectories and times

Try this:

#!/bin/bash
stat --format %y $(ls -t $(find alfa/ -type f) | head -n 1)

It uses find to gather all files from the directory, ls to list them sorted by modification date, head for selecting the first file and finally stat to show the time in a nice format.

At this time it is not safe for files with whitespace or other special characters in their names. Write a commend if it doesn't meet your needs yet.

How do you fix a bad merge, and replay your good commits onto a fixed merge?

The simplest way I found was suggested by leontalbot (as a comment), which is a post published by Anoopjohn. I think its worth its own space as an answer:

(I converted it to a bash script)

#!/bin/bash
if [[ $1 == "" ]]; then
    echo "Usage: $0 FILE_OR_DIR [remote]";
    echo "FILE_OR_DIR: the file or directory you want to remove from history"
    echo "if 'remote' argument is set, it will also push to remote repository."
    exit;
fi
FOLDERNAME_OR_FILENAME=$1;

#The important part starts here: ------------------------

git filter-branch -f --index-filter "git rm -rf --cached --ignore-unmatch $FOLDERNAME_OR_FILENAME" -- --all
rm -rf .git/refs/original/
git reflog expire --expire=now --all
git gc --prune=now
git gc --aggressive --prune=now

if [[ $2 == "remote" ]]; then
    git push --all --force
fi
echo "Done."

All credits goes to Annopjohn, and to leontalbot for pointing it out.

NOTE

Be aware that the script doesn't include validations, so be sure you don't make mistakes and that you have a backup in case something goes wrong. It worked for me, but it may not work in your situation. USE IT WITH CAUTION (follow the link if you want to know what is going on).

How to stretch the background image to fill a div

body{
  margin:0;
  background:url('image.png') no-repeat 50% 50% fixed;
  background-size: cover;
}

Change the background color of CardView programmatically

What you are looking for is:

CardView card = ...
card.setCardBackgroundColor(color);

In XML

 card_view:cardBackgroundColor="@android:color/white"

Update: in XML

app:cardBackgroundColor="@android:color/white"

using CASE in the WHERE clause

You can transform logical implication A => B to NOT A or B. This is one of the most basic laws of logic. In your case it is something like this:

SELECT *
FROM logs 
WHERE pw='correct' AND (id>=800 OR success=1)  
AND YEAR(timestamp)=2011

I also transformed NOT id<800 to id>=800, which is also pretty basic.

MySQL 'create schema' and 'create database' - Is there any difference

Mysql documentation says : CREATE SCHEMA is a synonym for CREATE DATABASE as of MySQL 5.0.2.


this all goes back to an ANSI standard for SQL in the mid-80s.

That standard had a "CREATE SCHEMA" command, and it served to introduce multiple name spaces for table and view names. All tables and views were created within a "schema". I do not know whether that version defined some cross-schema access to tables and views, but I assume it did. AFAIR, no product (at least back then) really implemented it, that whole concept was more theory than practice.

OTOH, ISTR this version of the standard did not have the concept of a "user" or a "CREATE USER" command, so there were products that used the concept of a "user" (who then had his own name space for tables and views) to implement their equivalent of "schema".

This is an area where systems differ.

As far as administration is concerned, this should not matter too much, because here you have differences anyway.

As far as you look at application code, you "only" have to care about cases where one application accesses tables from multiple name spaces. AFAIK, all systems support a syntax ".", and for this it should not matter whether the name space is that of a user, a "schema", or a "database".

PDO get the last ID inserted

lastInsertId() only work after the INSERT query.

Correct:

$stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass) 
                              VALUES(?,?,?);");
$sonuc = $stmt->execute([$username,$email,$pass]);
$LAST_ID = $this->conn->lastInsertId();

Incorrect:

$stmt = $this->conn->prepare("SELECT * FROM users");
$sonuc = $stmt->execute();
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0