Programs & Examples On #Tribool

Using if elif fi in shell scripts

sh is interpreting the && as a shell operator. Change it to -a, that’s [’s conjunction operator:

[ "$arg1" = "$arg2" -a "$arg1" != "$arg3" ]

Also, you should always quote the variables, because [ gets confused when you leave off arguments.

Difference between x86, x32, and x64 architectures?

x86 means Intel 80x86 compatible. This used to include the 8086, a 16-bit only processor. Nowadays it roughly means any CPU with a 32-bit Intel compatible instruction set (usually anything from Pentium onwards). Never read x32 being used.

x64 means a CPU that is x86 compatible but has a 64-bit mode as well (most often the 64-bit instruction set as introduced by AMD is meant; Intel's idea of a 64-bit mode was totally stupid and luckily Intel admitted that and is now using AMDs variant).

So most of the time you can simplify it this way: x86 is Intel compatible in 32-bit mode, x64 is Intel compatible in 64-bit mode.

How do I run Redis on Windows?

The Redis download page now has links to some unofficial Windows ports. The dmajkic one seems to be the most popular/complete.

More detailed answer: How to run Redis as a service under Windows

const char* concatenation

One more example:

// calculate the required buffer size (also accounting for the null terminator):
int bufferSize = strlen(one) + strlen(two) + 1;

// allocate enough memory for the concatenated string:
char* concatString = new char[ bufferSize ];

// copy strings one and two over to the new buffer:
strcpy( concatString, one );
strcat( concatString, two );

...

// delete buffer:
delete[] concatString;

But unless you specifically don't want or can't use the C++ standard library, using std::string is probably safer.

Stack smashing detected

I got this error because of a missing return statement.

How to get MAC address of your machine using a C program?

I have just write one and test it on gentoo in virtualbox.

// get_mac.c
#include <stdio.h>    //printf
#include <string.h>   //strncpy
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>   //ifreq
#include <unistd.h>   //close

int main()
{
    int fd;
    struct ifreq ifr;
    char *iface = "enp0s3";
    unsigned char *mac = NULL;

    memset(&ifr, 0, sizeof(ifr));

    fd = socket(AF_INET, SOCK_DGRAM, 0);

    ifr.ifr_addr.sa_family = AF_INET;
    strncpy(ifr.ifr_name , iface , IFNAMSIZ-1);

    if (0 == ioctl(fd, SIOCGIFHWADDR, &ifr)) {
        mac = (unsigned char *)ifr.ifr_hwaddr.sa_data;

        //display mac address
        printf("Mac : %.2X:%.2X:%.2X:%.2X:%.2X:%.2X\n" , mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
    }

    close(fd);

    return 0;
}

TypeError: can't use a string pattern on a bytes-like object in re.findall()

The problem is that your regex is a string, but html is bytes:

>>> type(html)
<class 'bytes'>

Since python doesn't know how those bytes are encoded, it throws an exception when you try to use a string regex on them.

You can either decode the bytes to a string:

html = html.decode('ISO-8859-1')  # encoding may vary!
title = re.findall(pattern, html)  # no more error

Or use a bytes regex:

regex = rb'<title>(,+?)</title>'
#        ^

In this particular context, you can get the encoding from the response headers:

with urllib.request.urlopen(url) as response:
    encoding = response.info().get_param('charset', 'utf8')
    html = response.read().decode(encoding)

See the urlopen documentation for more details.

In C++ check if std::vector<string> contains a certain value

  1. If your container only contains unique values, consider using std::set instead. It allows querying of set membership with logarithmic complexity.

     std::set<std::string> s;
     s.insert("abc");
     s.insert("xyz");
     if (s.find("abc") != s.end()) { ...
    
  2. If your vector is kept sorted, use std::binary_search, it offers logarithmic complexity as well.

  3. If all else fails, fall back to std::find, which is a simple linear search.

Calling a Javascript Function from Console

you can invoke it using window.function_name() or directly function_name()

MySQL INNER JOIN Alias

Use a seperate column to indicate the join condition

SELECT  t.importid, 
        case 
            when t.importid = g.home 
            then 'home' 
            else 'away' 
        end as join_condition, 
        g.network, 
        g.date_start 
FROM    game g
INNER JOIN team t ON (t.importid = g.home OR t.importid = g.away)
ORDER BY date_start DESC 
LIMIT 7

Read and parse a Json File in C#

This can also be done in the following way:

JObject data = JObject.Parse(File.ReadAllText(MyFilePath));

C++ error: undefined reference to 'clock_gettime' and 'clock_settime'

Since glibc version 2.17, the library linking -lrt is no longer required.

The clock_* are now part of the main C library. You can see the change history of glibc 2.17 where this change was done explains the reason for this change:

+* The `clock_*' suite of functions (declared in <time.h>) is now available
+  directly in the main C library.  Previously it was necessary to link with
+  -lrt to use these functions.  This change has the effect that a
+  single-threaded program that uses a function such as `clock_gettime' (and
+  is not linked with -lrt) will no longer implicitly load the pthreads
+  library at runtime and so will not suffer the overheads associated with
+  multi-thread support in other code such as the C++ runtime library.

If you decide to upgrade glibc, then you can check the compatibility tracker of glibc if you are concerned whether there would be any issues using the newer glibc.

To check the glibc version installed on the system, run the command:

ldd --version

(Of course, if you are using old glibc (<2.17) then you will still need -lrt.)

E: gnupg, gnupg2 and gnupg1 do not seem to be installed, but one of them is required for this operation

In your Dockerfile, run this first:

apt-get update && apt-get install -y gnupg2

No Exception while type casting with a null in java

As others have written, you can cast null to everything. Normally, you wouldn't need that, you can write:

String nullString = null;

without putting the cast there.

But there are occasions where such casts make sense:

a) if you want to make sure that a specific method is called, like:

void foo(String bar) {  ... }
void foo(Object bar) {  ... }

then it would make a difference if you type

foo((String) null) vs. foo(null)

b) if you intend to use your IDE to generate code; for example I am typically writing unit tests like:

@Test(expected=NullPointerException.class)
public testCtorWithNullWhatever() {
    new MyClassUnderTest((Whatever) null);
}

I am doing TDD; this means that the class "MyClassUnderTest" probably doesn't exist yet. By writing down that code, I can then use my IDE to first generate the new class; and to then generate a constructor accepting a "Whatever" argument "out of the box" - the IDE can figure from my test that the constructor should take exactly one argument of type Whatever.

Apache could not be started - ServerRoot must be a valid directory and Unable to find the specified module

I checked the line 35 of xampp/apache/conf/httpd.conf and it was:

ServerRoot "/xampp/apache"

Which doesn't exist. ...

Create the directory, or change the path to the directory that contains your hypertext documents.

In jQuery, what's the best way of formatting a number to 2 decimal places?

We modify a Meouw function to be used with keyup, because when you are using an input it can be more helpful.

Check this:

Hey there!, @heridev and I created a small function in jQuery.

You can try next:

HTML

<input type="text" name="one" class="two-digits"><br>
<input type="text" name="two" class="two-digits">?

jQuery

// apply the two-digits behaviour to elements with 'two-digits' as their class
$( function() {
    $('.two-digits').keyup(function(){
        if($(this).val().indexOf('.')!=-1){         
            if($(this).val().split(".")[1].length > 2){                
                if( isNaN( parseFloat( this.value ) ) ) return;
                this.value = parseFloat(this.value).toFixed(2);
            }  
         }            
         return this; //for chaining
    });
});

? DEMO ONLINE:

http://jsfiddle.net/c4Wqn/

(@heridev, @vicmaster)

Spring Boot and how to configure connection details to MongoDB?

Here is How you can do in Spring Boot 2.0 by creating custom MongoClient adding Providing more control for Connection ,

Please follow github Link for Full Source Code

@Configuration
@EnableMongoRepositories(basePackages = { "com.frugalis.repository" })
@ComponentScan(basePackages = { "com.frugalis.*" })
@PropertySource("classpath:application.properties")
public class MongoJPAConfig extends AbstractMongoConfiguration {

    @Value("${com.frugalis.mongo.database}")
    private String database;
    @Value("${com.frugalis.mongo.server}")
    private String host;
    @Value("${com.frugalis.mongo.port}")
    private String port;
    @Value("${com.frugalis.mongo.username}")
    private String username;
    @Value("${com.frugalis.mongo.password}")
    private String password;


    @Override
    protected String getDatabaseName() {
        return database;
    }

    @Override
    protected String getMappingBasePackage() {
        return "com.frugalis.entity.mongo";
    }

    @Bean
    public MongoTemplate mongoTemplate() throws Exception {
        return new MongoTemplate(mongoClient(), getDatabaseName());
    }

    @Override
    @Bean
    public MongoClient mongoClient() {

        List<MongoCredential> allCred = new ArrayList<MongoCredential>();
        System.out.println("???????????????????"+username+" "+database+" "+password+" "+host+" "+port);
        allCred.add(MongoCredential.createCredential(username, database, password.toCharArray()));
        MongoClient client = new MongoClient((new ServerAddress(host, Integer.parseInt(port))), allCred);
        client.setWriteConcern(WriteConcern.ACKNOWLEDGED);

        return client;
    }} 

Error:Execution failed for task ':app:dexDebug'. com.android.ide.common.process.ProcessException

I solved the same issue by removing:

compile fileTree(include: ['*.jar'], dir: 'libs')

and adding for each jar file:

compile files('libs/yourjarfile.jar')

IE Driver download location Link for Selenium

You can download IE Driver (both 32 and 64-bit) from Selenium official site: http://docs.seleniumhq.org/download/

32 bit Windows IE

64 bit Windows IE

IE Driver is also available in the following site:

http://selenium-release.storage.googleapis.com/index.html

What is the ultimate postal code and zip regex?

This is a very simple RegEx for validating US Zipcode (not ZipCode Plus Four):

(?!([089])\1{4})\d{5}

Seems all five digit numeric are valid zipcodes except 00000, 88888 & 99999.

I have tested this RegEx with http://regexpal.com/

SP

What is correct media query for IPad Pro?

/* ----------- iPad Pro ----------- */
/* Portrait and Landscape */
@media only screen 
  and (min-width: 1024px) 
  and (max-height: 1366px) 
  and (-webkit-min-device-pixel-ratio: 1.5) {
}

/* Portrait */
@media only screen 
  and (min-width: 1024px) 
  and (max-height: 1366px) 
  and (orientation: portrait) 
  and (-webkit-min-device-pixel-ratio: 1.5) {
}

/* Landscape */
@media only screen 
  and (min-width: 1024px) 
  and (max-height: 1366px) 
  and (orientation: landscape) 
  and (-webkit-min-device-pixel-ratio: 1.5) {

}

I don't have an iPad Pro but this works for me in the Chrome simulator.

Environment Specific application.properties file in Spring Boot application

we can do like this:

in application.yml:

spring:
  profiles:
    active: test //modify here to switch between environments
    include:  application-${spring.profiles.active}.yml

in application-test.yml:

server:
  port: 5000

and in application-local.yml:

server:
  address: 0.0.0.0
  port: 8080

then spring boot will start our app as we wish to.

How to get $HOME directory of different user in bash script?

This works in Linux. Not sure how it behaves in other *nixes.

  getent passwd "${OTHER_USER}"|cut -d\: -f 6

How do I hide anchor text without hiding the anchor?

Mini tip:

I had the following scenario:

<a href="/page/">My link text
:after
</a>

I hided the text with font-size: 0, so I could use a FontAwesome icon for it. This worked on Chrome 36, Firefox 31 and IE9+.

I wouldn't recommend color: transparent because the text stil exists and is selectable. Using line-height: 0px didn't allow me to use :after. Maybe because my element was a inline-block.

Visibility: hidden: Didn't allow me to use :after.

text-indent: -9999px;: Also moved the :after element

Calculate compass bearing / heading to location in Android

If you are on the same timezone

Convert GPS to UTM

http://www.ibm.com/developerworks/java/library/j-coordconvert/ http://stackoverflow.com/questions/176137/java-convert-lat-lon-to-utm

UTM coordinates get you a simples X Y 2D

Calculate the angle between both UTM locations

http://forums.groundspeak.com/GC/index.php?showtopic=146917

This gives the direction as if you were looking north

So whatever you rotate related do North just subtract this angle

If both point have a UTM 45º degree angle and you are 5º east of north, your arrow will point to 40º of north

Git checkout - switching back to HEAD

You can stash (save the changes in temporary box) then, back to master branch HEAD.

$ git add .
$ git stash
$ git checkout master

Jump Over Commits Back and Forth:

  • Go to a specific commit-sha.

      $ git checkout <commit-sha>
    
  • If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.

      # checkout a new branch, add, commit, push
      $ git checkout -b <branch-name>
      $ git add .
      $ git commit -m 'Commit message'
      $ git push origin HEAD          # push the current branch to remote 
    
      $ git checkout master           # back to master branch now
    
  • If you have changes in the specific commit and don't want to keep the changes, you can do stash or reset then checkout to master (or, any other branch).

      # stash
      $ git add -A
      $ git stash
      $ git checkout master
    
      # reset
      $ git reset --hard HEAD
      $ git checkout master
    
  • After checking out a specific commit if you have no uncommitted change(s) then, just back to master or other branch.

      $ git status          # see the changes
      $ git checkout master
    
      # or, shortcut
      $ git checkout -      # back to the previous state
    

How to put a jpg or png image into a button in HTML

<a href="#">
        <img src="p.png"></img>
    </a>

Test or check if sheet exists

I did another thing: delete a sheet only if it's exists - not to get an error if it doesn't:

Excel.DisplayAlerts = False 
Dim WS
For Each WS In Excel.Worksheets
    If WS.name = "Sheet2" Then
        Excel.sheets("Sheet2").Delete
        Exit For
    End If
Next
Excel.DisplayAlerts = True

"Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo." when using GCC

You don't need to fiddle around with any command :)

Once the XCode is updated, open the Xcode IDE program. Please accept terms and conditions.

You are all set to go :))

Why maven settings.xml file is not there?

As per the maven's documentation, there are two possible settings.xml locations

One is the global maven's repo (Your initial download and subsequent unzipped files from apache maven) $M2_HOME/conf/settings.xml

And the second is the user created one (Your local copy) ${user.home}/.m2/settings.xml

The local copy takes precedence over the global copy in terms of settings information. But it is said that they both get merged during "runtime". If you need to have your local copy of the settings.xml, simply copy from the global copy and paste in your .m2 folder and adjust the details as needed

How to build a RESTful API?

Another framework which has not been mentioned so far is Laravel. It's great for building PHP apps in general but thanks to the great router it's really comfortable and simple to build rich APIs. It might not be that slim as Slim or Sliex but it gives you a solid structure.

See Aaron Kuzemchak - Simple API Development With Laravel on YouTube and

Laravel 4: A Start at a RESTful API on NetTuts+

How do I extract text that lies between parentheses (round brackets)?

A very simple way to do it is by using regular expressions:

Regex.Match("User name (sales)", @"\(([^)]*)\)").Groups[1].Value

As a response to the (very funny) comment, here's the same Regex with some explanation:

\(             # Escaped parenthesis, means "starts with a '(' character"
    (          # Parentheses in a regex mean "put (capture) the stuff 
               #     in between into the Groups array" 
       [^)]    # Any character that is not a ')' character
       *       # Zero or more occurrences of the aforementioned "non ')' char"
    )          # Close the capturing group
\)             # "Ends with a ')' character"

How to convert a Drawable to a Bitmap?

So after looking (and using) of the other answers, seems they all handling ColorDrawable and PaintDrawable badly. (Especially on lollipop) seemed that Shaders were tweaked so solid blocks of colors were not handled correctly.

I am using the following code now:

public static Bitmap drawableToBitmap(Drawable drawable) {
    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable) drawable).getBitmap();
    }

    // We ask for the bounds if they have been set as they would be most
    // correct, then we check we are  > 0
    final int width = !drawable.getBounds().isEmpty() ?
            drawable.getBounds().width() : drawable.getIntrinsicWidth();

    final int height = !drawable.getBounds().isEmpty() ?
            drawable.getBounds().height() : drawable.getIntrinsicHeight();

    // Now we check we are > 0
    final Bitmap bitmap = Bitmap.createBitmap(width <= 0 ? 1 : width, height <= 0 ? 1 : height,
            Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);

    return bitmap;
}

Unlike the others, if you call setBounds on the Drawable before asking to turn it into a bitmap, it will draw the bitmap at the correct size!

Python string prints as [u'String']

Maybe i dont understand , why cant you just get the element.text and then convert it before using it ? for instance (dont know why you would do this but...) find all label elements of the web page and iterate between them until you find one called MyText

        avail = []
        avail = driver.find_elements_by_class_name("label");
        for i in avail:
                if  i.text == "MyText":

Convert the string from i and do whatever you wanted to do ... maybe im missing something in the original message ? or was this what you were looking for ?

How can I create a Windows .exe (standalone executable) using Java/Eclipse?

Java doesn't natively allow building of an exe, that would defeat its purpose of being cross-platform.

AFAIK, these are your options:

  1. Make a runnable JAR. If the system supports it and is configured appropriately, in a GUI, double clicking the JAR will launch the app. Another option would be to write a launcher shell script/batch file which will start your JAR with the appropriate parameters

  2. There also executable wrappers - see How can I convert my Java program to an .exe file?

See also: Convert Java to EXE: Why, When, When Not and How

How to truncate the time on a DateTime object in Python?

You can just use

datetime.date.today()

It's light and returns exactly what you want.

“Origin null is not allowed by Access-Control-Allow-Origin” error for request made by application running from a file:// URL

If you are doing local testing or calling the file from something like file:// then you need to disable browser security.

On MAC: open -a Google\ Chrome --args --disable-web-security

How to read file using NPOI

private DataTable GetDataTableFromExcel(String Path)
    {
        XSSFWorkbook wb;
        XSSFSheet sh;
        String Sheet_name;

        using (var fs = new FileStream(Path, FileMode.Open, FileAccess.Read))
        {
            wb = new XSSFWorkbook(fs);

               Sheet_name= wb.GetSheetAt(0).SheetName;  //get first sheet name
        }
        DataTable DT = new DataTable();
        DT.Rows.Clear();
        DT.Columns.Clear();

        // get sheet
        sh = (XSSFSheet)wb.GetSheet(Sheet_name);

        int i = 0;
        while (sh.GetRow(i) != null)
        {
            // add neccessary columns
            if (DT.Columns.Count < sh.GetRow(i).Cells.Count)
            {
                for (int j = 0; j < sh.GetRow(i).Cells.Count; j++)
                {
                    DT.Columns.Add("", typeof(string));
                }
            }

            // add row
            DT.Rows.Add();

            // write row value
            for (int j = 0; j < sh.GetRow(i).Cells.Count; j++)
            {
                var cell = sh.GetRow(i).GetCell(j);

                if (cell != null)
                {
                    // TODO: you can add more cell types capatibility, e. g. formula
                    switch (cell.CellType)
                    {
                        case NPOI.SS.UserModel.CellType.Numeric:
                            DT.Rows[i][j] = sh.GetRow(i).GetCell(j).NumericCellValue;
                            //dataGridView1[j, i].Value = sh.GetRow(i).GetCell(j).NumericCellValue;

                            break;
                        case NPOI.SS.UserModel.CellType.String:
                            DT.Rows[i][j] = sh.GetRow(i).GetCell(j).StringCellValue;

                            break;
                    }
                }
            }

            i++;
        }

        return DT;
    }

TypeLoadException says 'no implementation', but it is implemented

I received this error after a recent windows update. I had a service class set to inherit from an interface. The interface contained a signature that returned a ValueTuple, a fairly new feature in C#.

All I can guess is that the windows update installed a new one, but even explicitly referencing it, updating binding redirects, etc...The end result was just changing the signature of the method to something "standard" I guess you could say.

How to properly add cross-site request forgery (CSRF) token using PHP

Security Warning: md5(uniqid(rand(), TRUE)) is not a secure way to generate random numbers. See this answer for more information and a solution that leverages a cryptographically secure random number generator.

Looks like you need an else with your if.

if (!isset($_SESSION['token'])) {
    $token = md5(uniqid(rand(), TRUE));
    $_SESSION['token'] = $token;
    $_SESSION['token_time'] = time();
}
else
{
    $token = $_SESSION['token'];
}

Java: How to convert a File object to a String object in java?

Readin file with file inputstream and append file content to string.

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class CopyOffileInputStream {

    public static void main(String[] args) {

        //File file = new File("./store/robots.txt");
        File file = new File("swingloggingsscce.log");

        FileInputStream fis = null;
        String str = "";

        try {
            fis = new FileInputStream(file);
            int content;
            while ((content = fis.read()) != -1) {
                // convert to char and display it
                str += (char) content;
            }

            System.out.println("After reading file");
            System.out.println(str);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

Using "&times" word in html changes to ×

&times; stands for × in html. Use &amp;times to get &times

Understanding Fragment's setRetainInstance(boolean)

setRetaininstance is only useful when your activity is destroyed and recreated due to a configuration change because the instances are saved during a call to onRetainNonConfigurationInstance. That is, if you rotate the device, the retained fragments will remain there(they're not destroyed and recreated.) but when the runtime kills the activity to reclaim resources, nothing is left. When you press back button and exit the activity, everything is destroyed.

Usually I use this function to saved orientation changing Time.Say I have download a bunch of Bitmaps from server and each one is 1MB, when the user accidentally rotate his device, I certainly don't want to do all the download work again.So I create a Fragment holding my bitmaps and add it to the manager and call setRetainInstance,all the Bitmaps are still there even if the screen orientation changes.

How to remove empty cells in UITableView?

or you can call tableView method to set the footer height in 1 point, and it will add an last line, but you can hide it too, by setting footer background color.

code:

func tableView(tableView: UITableView,heightForFooterInSection section: Int) -> CGFloat {
     return 1
}

looks like last line

(413) Request Entity Too Large | uploadReadAheadSize

Got a similar error on IIS Express with Visual Studio 2017.

HTTP Error 413.0 - Request Entity Too Large

The page was not displayed because the request entity is too large.

Most likely causes:

  • The Web server is refusing to service the request because the request entity is too large.

  • The Web server cannot service the request because it is trying to negotiate a client certificate but the request entity is too large.

  • The request URL or the physical mapping to the URL (i.e., the physical file system path to the URL's content) is too long.

Things you can try:

  • Verify that the request is valid.

  • If using client certificates, try:

    • Increasing system.webServer/serverRuntime@uploadReadAheadSize

    • Configure your SSL endpoint to negotiate client certificates as part of the initial SSL handshake. (netsh http add sslcert ... clientcertnegotiation=enable) .vs\config\applicationhost.config

Solve this by editing \.vs\config\applicationhost.config. Switch serverRuntime from Deny to Allow like this:

<section name="serverRuntime" overrideModeDefault="Allow" />

If this value is not edited, you will get an error like this when setting uploadReadAheadSize:

HTTP Error 500.19 - Internal Server Error

The requested page cannot be accessed because the related configuration data for the page is invalid.

This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false".

Then edit Web.config with the following values:

<system.webServer>
  <serverRuntime uploadReadAheadSize="10485760" />
...

Meaning of Choreographer messages in Logcat

This if an Info message that could pop in your LogCat on many situations.

In my case, it happened when I was inflating several views from XML layout files programmatically. The message is harmless by itself, but could be the sign of a later problem that would use all the RAM your App is allowed to use and cause the mega-evil Force Close to happen. I have grown to be the kind of Developer that likes to see his Log WARN/INFO/ERROR Free. ;)

So, this is my own experience:

I got the message:

10-09 01:25:08.373: I/Choreographer(11134): Skipped XXX frames!  The application may be doing too much work on its main thread.

... when I was creating my own custom "super-complex multi-section list" by inflating a view from XML and populating its fields (images, text, etc...) with the data coming from the response of a REST/JSON web service (without paging capabilities) this views would act as rows, sub-section headers and section headers by adding all of them in the correct order to a LinearLayout (with vertical orientation inside a ScrollView). All of that to simulate a listView with clickable elements... but well, that's for another question.

As a responsible Developer you want to make the App really efficient with the system resources, so the best practice for lists (when your lists are not so complex) is to use a ListActivity or ListFragment with a Loader and fill the ListView with an Adapter, this is supposedly more efficient, in fact it is and you should do it all the time, again... if your list is not so complex.

Solution: I implemented paging on my REST/JSON web service to prevent "big response sizes" and I wrapped the code that added the "rows", "section headers" and "sub-section headers" views on an AsyncTask to keep the Main Thread cool.

So... I hope my experience helps someone else that is cracking their heads open with this Info message.

Happy hacking!

invalid types 'int[int]' for array subscript

You're trying to access a 3 dimensional array with 4 de-references

You only need 3 loops instead of 4, or int myArray[10][10][10][10];

Can't create project on Netbeans 8.2

@ubuntu 18.04

sudo apt install openjdk-8-jdk
then
sudo update-alternatives --config java


  Selection    Path                                            Priority   Status
------------------------------------------------------------
  0            /usr/lib/jvm/java-11-openjdk-amd64/bin/java      1111      auto mode
  1            /usr/lib/jvm/java-11-openjdk-amd64/bin/java      1111      manual mode
* 2            /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java   1081      manual mode

Press <enter> to keep the current choice[*], or type selection number: 

choose java 8 then restart netbeans
Done

Regex replace uppercase with lowercase letters

You may:

Find: (\w) Replace With: \L$1

Or select the text, ctrl+K+L.

Get month name from number

I created my own function converting numbers to their corresponding month.

def month_name (number):
    if number == 1:
        return "January"
    elif number == 2:
        return "February"
    elif number == 3:
        return "March"
    elif number == 4:
        return "April"
    elif number == 5:
        return "May"
    elif number == 6:
        return "June"
    elif number == 7:
        return "July"
    elif number == 8:
        return "August"
    elif number == 9:
        return "September"
    elif number == 10:
        return "October"
    elif number == 11:
        return "November"
    elif number == 12:
        return "December"

Then I can call the function. For example:

print (month_name (12))

Outputs:

>>> December

How to debug an apache virtual host configuration?

I found my own mistake, I did not add log file name: ErrorLog /var/log/apache2
And this path: Directory "/usr/share/doc/" Did not contain website sources.

After I changed these two, all worked. Interestingly, apache did not issue any errors, just did not open my website silently on my Mac OS Sierra.

Remove characters after specific character in string, then remove substring?

To remove everything before the first /

input = input.Substring(input.IndexOf("/"));

To remove everything after the first /

input = input.Substring(0, input.IndexOf("/") + 1);

To remove everything before the last /

input = input.Substring(input.LastIndexOf("/"));

To remove everything after the last /

input = input.Substring(0, input.LastIndexOf("/") + 1);

An even more simpler solution for removing characters after a specified char is to use the String.Remove() method as follows:

To remove everything after the first /

input = input.Remove(input.IndexOf("/") + 1);

To remove everything after the last /

input = input.Remove(input.LastIndexOf("/") + 1);

Setting environment variable in react-native?

Step 1: Create separate component like this Component name : pagebase.js
Step 2: Inside this use code this

    export const BASE_URL = "http://192.168.10.10:4848/";
    export const API_KEY = 'key_token';

Step 3: Use it in any component, for using it first import this component then use it. Import it and use it:

        import * as base from "./pagebase";

        base.BASE_URL
        base.API_KEY

How to add a new column to a CSV file?

Yes Its a old question but it might help some

import csv
import uuid

# read and write csv files
with open('in_file','r') as r_csvfile:
    with open('out_file','w',newline='') as w_csvfile:

        dict_reader = csv.DictReader(r_csvfile,delimiter='|')
        #add new column with existing
        fieldnames = dict_reader.fieldnames + ['ADDITIONAL_COLUMN']
        writer_csv = csv.DictWriter(w_csvfile,fieldnames,delimiter='|')
        writer_csv.writeheader()


        for row in dict_reader:
            row['ADDITIONAL_COLUMN'] = str(uuid.uuid4().int >> 64) [0:6]
            writer_csv.writerow(row)

Should Jquery code go in header or footer?

Standard practice is to put all of your scripts at the bottom of the page, but I use ASP.NET MVC with a number of jQuery plugins, and I find that it all works better if I put my jQuery scripts in the <head> section of the master page.

In my case, there are artifacts that occur when the page is loaded, if the scripts are at the bottom of the page. I'm using the jQuery TreeView plugin, and if the scripts are not loaded at the beginning, the tree will render without the necessary CSS classes imposed on it by the plugin. So you get this funny-looking mess when the page first loads, followed by the proper rendering of the TreeView. Very bad looking. Putting the jQuery plugins in the <head> section of the master page eliminates this problem.

How to mount a single file in a volume

Use mount (--mount) instead volume (-v)

More info: https://docs.docker.com/storage/bind-mounts/

Example:

Ensure /tmp/a.txt exists on docker host

docker run -it --mount type=bind,source=/tmp/a.txt,target=/root/a.txt alpine sh

Swift Beta performance: sorting arrays

Swift Array performance revisited:

I wrote my own benchmark comparing Swift with C/Objective-C. My benchmark calculates prime numbers. It uses the array of previous prime numbers to look for prime factors in each new candidate, so it is quite fast. However, it does TONS of array reading, and less writing to arrays.

I originally did this benchmark against Swift 1.2. I decided to update the project and run it against Swift 2.0.

The project lets you select between using normal swift arrays and using Swift unsafe memory buffers using array semantics.

For C/Objective-C, you can either opt to use NSArrays, or C malloc'ed arrays.

The test results seem to be pretty similar with fastest, smallest code optimization ([-0s]) or fastest, aggressive ([-0fast]) optimization.

Swift 2.0 performance is still horrible with code optimization turned off, whereas C/Objective-C performance is only moderately slower.

The bottom line is that C malloc'd array-based calculations are the fastest, by a modest margin

Swift with unsafe buffers takes around 1.19X - 1.20X longer than C malloc'd arrays when using fastest, smallest code optimization. the difference seems slightly less with fast, aggressive optimization (Swift takes more like 1.18x to 1.16x longer than C.

If you use regular Swift arrays, the difference with C is slightly greater. (Swift takes ~1.22 to 1.23 longer.)

Regular Swift arrays are DRAMATICALLY faster than they were in Swift 1.2/Xcode 6. Their performance is so close to Swift unsafe buffer based arrays that using unsafe memory buffers does not really seem worth the trouble any more, which is big.

BTW, Objective-C NSArray performance stinks. If you're going to use the native container objects in both languages, Swift is DRAMATICALLY faster.

You can check out my project on github at SwiftPerformanceBenchmark

It has a simple UI that makes collecting stats pretty easy.

It's interesting that sorting seems to be slightly faster in Swift than in C now, but that this prime number algorithm is still faster in Swift.

How to get the full path of the file from a file input

You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:

In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file" field, ostensibly for backward compatibility reasons.

So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.

Elegant way to report missing values in a data.frame

For one more graphical solution, visdat package offers vis_miss.

library(visdat)
vis_miss(airquality)

enter image description here

Very similar to Amelia output with a small difference of giving %s on missings out of the box.

Format Instant to String

Time Zone

To format an Instant a time-zone is required. Without a time-zone, the formatter does not know how to convert the instant to human date-time fields, and therefore throws an exception.

The time-zone can be added directly to the formatter using withZone().

DateTimeFormatter formatter =
    DateTimeFormatter.ofLocalizedDateTime( FormatStyle.SHORT )
                     .withLocale( Locale.UK )
                     .withZone( ZoneId.systemDefault() );

If you specifically want an ISO-8601 format with no explicit time-zone (as the OP asked), with the time-zone implicitly UTC, you need

DateTimeFormatter.ISO_LOCAL_DATE_TIME.withZone(ZoneId.from(ZoneOffset.UTC))

Generating String

Now use that formatter to generate the String representation of your Instant.

Instant instant = Instant.now();
String output = formatter.format( instant );

Dump to console.

System.out.println("formatter: " + formatter + " with zone: " + formatter.getZone() + " and Locale: " + formatter.getLocale() );
System.out.println("instant: " + instant );
System.out.println("output: " + output );

When run.

formatter: Localized(SHORT,SHORT) with zone: US/Pacific and Locale: en_GB
instant: 2015-06-02T21:34:33.616Z
output: 02/06/15 14:34

window.location (JS) vs header() (PHP) for redirection

The first case will fail when JS is off. It's also a little bit slower since JS must be parsed first (DOM must be loaded). However JS is safer since the destination doesn't know the referer and your redirect might be tracked (referers aren't reliable in general yet this is something).

You can also use meta refresh tag. It also requires DOM to be loaded.

OpenCV in Android Studio

For everyone who felt they want to run away with all the steps and screen shots on the (great!) above answers, this worked for me with android studio 2.2.1:

  1. Create a new project, name it as you want and take the default (minSdkVersion 15 is fine).

  2. Download the zip file from here: https://sourceforge.net/projects/opencvlibrary/files/opencv-android/ (I downloaded 3.2.0 version, but there may be a newer versions).

  3. Unzip the zip file, the best place is in your workspace folder, but it not really matter.

  4. Inside Android Studio, click File->New-> Import Module and navigate to \path_to_your_unzipped_file\OpenCV-android-sdk\sdk\java and hit Ok, then accept all default dialogs.

  5. In the gradle file of your app module, add this to the dependencies block:

     dependencies {
         compile project(':openCVLibraryXYZ')
         //rest of code
     }
    

Where XYZ is the exact version you downloaded, for example in my case:

    dependencies {
        compile project(':openCVLibrary320')
        //rest of code
    }

How to do URL decoding in Java?

import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;

public class URLDecoding { 

    String decoded = "";

    public String decodeMethod(String url) throws UnsupportedEncodingException
    {
        decoded = java.net.URLDecoder.decode(url, "UTF-8"); 
        return  decoded;
//"You should use java.net.URI to do this, as the URLDecoder class does x-www-form-urlencoded decoding which is wrong (despite the name, it's for form data)."
    }

    public String getPathMethod(String url) throws URISyntaxException 
    {
        decoded = new java.net.URI(url).getPath();  
        return  decoded; 
    }

    public static void main(String[] args) throws UnsupportedEncodingException, URISyntaxException 
    {
        System.out.println(" Here is your Decoded url with decode method : "+ new URLDecoding().decodeMethod("https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type")); 
        System.out.println("Here is your Decoded url with getPath method : "+ new URLDecoding().getPathMethod("https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest")); 

    } 

}

You can select your method wisely :)

Is it possible to set a custom font for entire of application?

I would also like to improve weston's answer for API 21 Android 5.0.

I had the same issue on my Samsung s5, when using DEFAULT font. (with the others fonts it's working fine)

I managed to make it working by setting the typeface ("sans" for example) in XML files, for each Textview or Button

<TextView
android:layout_width="match_parent"
android:layout_height="39dp"
android:textColor="@color/abs__background_holo_light"
android:textSize="12sp"
android:gravity="bottom|center"
android:typeface="sans" />

and in MyApplication Class :

public class MyApplication extends Application {
    @Override
    public void onCreate() {
    TypefaceUtil.overrideFont(getApplicationContext(), "SANS_SERIF",
    "fonts/my_font.ttf");
    }
}

Hope it helps.

How to monitor the memory usage of Node.js?

The original memwatch is essentially dead. Try memwatch-next instead, which seems to be working well on modern versions of Node.

Converting Columns into rows with their respective data in sql server

Sound like you want to UNPIVOT

Sample from books online:

--Create the table and insert values as portrayed in the previous example.
CREATE TABLE pvt (VendorID int, Emp1 int, Emp2 int,
    Emp3 int, Emp4 int, Emp5 int);
GO
INSERT INTO pvt VALUES (1,4,3,5,4,4);
INSERT INTO pvt VALUES (2,4,1,5,5,5);
INSERT INTO pvt VALUES (3,4,3,5,4,4);
INSERT INTO pvt VALUES (4,4,2,5,5,4);
INSERT INTO pvt VALUES (5,5,1,5,5,5);
GO
--Unpivot the table.
SELECT VendorID, Employee, Orders
FROM 
   (SELECT VendorID, Emp1, Emp2, Emp3, Emp4, Emp5
   FROM pvt) p
UNPIVOT
   (Orders FOR Employee IN 
      (Emp1, Emp2, Emp3, Emp4, Emp5)
)AS unpvt;
GO

Returns:

VendorID   Employee   Orders
---------- ---------- ------
1          Emp1       4
1          Emp2       3
1          Emp3       5
1          Emp4       4
1          Emp5       4
2          Emp1       4
2          Emp2       1
2          Emp3       5
2          Emp4       5
2          Emp5       5

see also: Unpivot SQL thingie and the unpivot tag

Picking a random element from a set

int size = myHashSet.size();
int item = new Random().nextInt(size); // In real life, the Random object should be rather more shared than this
int i = 0;
for(Object obj : myhashSet)
{
    if (i == item)
        return obj;
    i++;
}

How to make a view with rounded corners?

With the Material Components Library the best way to make a View with rounded corners is to use the MaterialShapeDrawable.

Create a ShapeAppearanceModel with custom rounded corners:

ShapeAppearanceModel shapeAppearanceModelLL1 = new ShapeAppearanceModel()
        .toBuilder()
        .setAllCorners(CornerFamily.ROUNDED,radius16)
        .build();

Create a MaterialShapeDrawable:

MaterialShapeDrawable shapeDrawableLL1 = new MaterialShapeDrawable(shapeAppearanceModeLL1);

If you want to apply also an elevationOverlay for the dark theme use this:

MaterialShapeDrawable shapeDrawableLL1 = MaterialShapeDrawable.createWithElevationOverlay(this, 4.0f);
shapeDrawableLL1.setShapeAppearanceModel(shapeAppearanceModelLL1);

Optional: apply to the shapeDrawable a background color and a stroke

shapeDrawableLL1.setFillColor(
       ContextCompat.getColorStateList(this,R.color...));
 shapeDrawableLL1.setStrokeWidth(2.0f);
 shapeDrawableLL1.setStrokeColor(
       ContextCompat.getColorStateList(this,R.color...));

Finally apply the shapeDrawable as background in your LinearLayout (or other view):

LinearLayout linearLayout1= findViewById(R.id.ll_1);
ViewCompat.setBackground(linearLayout1,shapeDrawableLL1);

enter image description here

Delete all but the most recent X files in bash

Removes all but the 10 latest (most recents) files

ls -t1 | head -n $(echo $(ls -1 | wc -l) - 10 | bc) | xargs rm

If less than 10 files no file is removed and you will have : error head: illegal line count -- 0

To count files with bash

Difference between long and int data types

A typical best practice is not using long/int/short directly. Instead, according to specification of compilers and OS, wrap them into a header file to ensure they hold exactly the amount of bits that you want. Then use int8/int16/int32 instead of long/int/short. For example, on 32bit Linux, you could define a header like this

typedef char int8;
typedef short int16;
typedef int int32;
typedef unsigned int uint32;

Get current date, given a timezone in PHP?

I have created some simple function you can use to convert time to any timezone :

function convertTimeToLocal($datetime,$timezone='Europe/Dublin') {
        $given = new DateTime($datetime, new DateTimeZone("UTC"));
        $given->setTimezone(new DateTimeZone($timezone));
        $output = $given->format("Y-m-d"); //can change as per your requirement
        return $output;
}

SELECT INTO USING UNION QUERY

INSERT INTO #Temp1
SELECT val1, val2 
FROM TABLE1
 UNION
SELECT val1, val2
FROM TABLE2

Where is array's length property defined?

Arrays are special objects in java, they have a simple attribute named length which is final.

There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.

10.7. Array Members

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

Resources:

Time part of a DateTime Field in SQL

you can use CONVERT(TIME,GETDATE()) in this case:

INSERT INTO infoTbl
(itDate, itTime)
VALUES (GETDATE(),CONVERT(TIME,GETDATE()))

or if you want print it or return that time use like this:

DECLARE @dt TIME
SET @dt = CONVERT(TIME,GETDATE())
PRINT @dt

C# Threading - How to start and stop a thread

This is how I do it...

public class ThreadA {
    public ThreadA(object[] args) {
        ...
    }
    public void Run() {
        while (true) {
            Thread.sleep(1000); // wait 1 second for something to happen.
            doStuff();
            if(conditionToExitReceived) // what im waiting for...
                break;
        }
        //perform cleanup if there is any...
    }
}

Then to run this in its own thread... ( I do it this way because I also want to send args to the thread)

private void FireThread(){
    Thread thread = new Thread(new ThreadStart(this.startThread));
    thread.start();
}
private void (startThread){
    new ThreadA(args).Run();
}

The thread is created by calling "FireThread()"

The newly created thread will run until its condition to stop is met, then it dies...

You can signal the "main" with delegates, to tell it when the thread has died.. so you can then start the second one...

Best to read through : This MSDN Article

What is parsing in terms that a new programmer would understand?

Simple explanation: Parsing is breaking a block of data into smaller pieces (tokens) by following a set of rules (using delimiters for example), so that this data could be processes piece by piece (managed, analysed, interpreted, transmitted, ets).

Examples: Many applications (like Spreadsheet programs) use CSV (Comma Separated Values) file format to import and export data. CSV format makes it possible for the applications to process this data with a help of a special parser. Web browsers have special parsers for HTML and CSS files. JSON parsers exist. All special file formats must have some parsers designed specifically for them.

How to convert a .eps file to a high quality 1024x1024 .jpg?

For vector graphics, ImageMagick has both a render resolution and an output size that are independent of each other.

Try something like

convert -density 300 image.eps -resize 1024x1024 image.jpg

Which will render your eps at 300dpi. If 300 * width > 1024, then it will be sharp. If you render it too high though, you waste a lot of memory drawing a really high-res graphic only to down sample it again. I don't currently know of a good way to render it at the "right" resolution in one IM command.

The order of the arguments matters! The -density X argument needs to go before image.eps because you want to affect the resolution that the input file is rendered at.

This is not super obvious in the manpage for convert, but is hinted at:

SYNOPSIS

convert [input-option] input-file [output-option] output-file

How to use pull to refresh in Swift?

Details

  • Xcode Version 10.3 (10G8), Swift 5

Features

  • Ability to make "pull to refresh" programmatically
  • Protection from multi- "pull to refresh" events
  • Ability to continue animating of the activity indicator when view controller switched (e.g. in case of TabController)

Solution

import UIKit

class RefreshControl: UIRefreshControl {

    private weak var actionTarget: AnyObject?
    private var actionSelector: Selector?
    override init() { super.init() }

    convenience init(actionTarget: AnyObject?, actionSelector: Selector) {
        self.init()
        self.actionTarget = actionTarget
        self.actionSelector = actionSelector
        addTarget()
    }

    private func addTarget() {
        guard let actionTarget = actionTarget, let actionSelector = actionSelector else { return }
        addTarget(actionTarget, action: actionSelector, for: .valueChanged)
    }

    required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }

    func endRefreshing(deadline: DispatchTime? = nil) {
        guard let deadline = deadline else { endRefreshing(); return }
        DispatchQueue.global(qos: .default).asyncAfter(deadline: deadline) { [weak self] in
            DispatchQueue.main.async { self?.endRefreshing() }
        }
    }

    func refreshActivityIndicatorView() {
        guard let selector = actionSelector else { return }
        let _isRefreshing = isRefreshing
        removeTarget(actionTarget, action: selector, for: .valueChanged)
        endRefreshing()
        if _isRefreshing { beginRefreshing() }
        addTarget()
    }

    func generateRefreshEvent() {
        beginRefreshing()
        sendActions(for: .valueChanged)
    }
}

public extension UIScrollView {

    private var _refreshControl: RefreshControl? { return refreshControl as? RefreshControl }

    func addRefreshControll(actionTarget: AnyObject?, action: Selector, replaceIfExist: Bool = false) {
        if !replaceIfExist && refreshControl != nil { return }
        refreshControl = RefreshControl(actionTarget: actionTarget, actionSelector: action)
    }

    func scrollToTopAndShowRunningRefreshControl(changeContentOffsetWithAnimation: Bool = false) {
        _refreshControl?.refreshActivityIndicatorView()
        guard   let refreshControl = refreshControl,
                contentOffset.y != -refreshControl.frame.height else { return }
        setContentOffset(CGPoint(x: 0, y: -refreshControl.frame.height), animated: changeContentOffsetWithAnimation)
    }

    private var canStartRefreshing: Bool {
        guard let refreshControl = refreshControl, !refreshControl.isRefreshing else { return false }
        return true
    }

    func startRefreshing() {
        guard canStartRefreshing else { return }
        _refreshControl?.generateRefreshEvent()
    }

    func pullAndRefresh() {
        guard canStartRefreshing else { return }
        scrollToTopAndShowRunningRefreshControl(changeContentOffsetWithAnimation: true)
        _refreshControl?.generateRefreshEvent()
    }

    func endRefreshing(deadline: DispatchTime? = nil) { _refreshControl?.endRefreshing(deadline: deadline) }
}

Usage

// Add refresh control to UICollectionView / UITableView / UIScrollView
private func setupTableView() {
    let tableView = UITableView()
    // ...
    tableView.addRefreshControll(actionTarget: self, action: #selector(refreshData))
}

@objc func refreshData(_ refreshControl: UIRefreshControl) {
    tableView?.endRefreshing(deadline: .now() + .seconds(3))
}

// Stop refreshing in UICollectionView / UITableView / UIScrollView
tableView.endRefreshing()

// Simulate pull to refresh in UICollectionView / UITableView / UIScrollView
tableView.pullAndRefresh()

Full Sample

Do not forget to add the solution code here

import UIKit

class ViewController: UIViewController {

    private weak var tableView: UITableView?

    override func viewDidLoad() {
        super.viewDidLoad()
        setupTableView()
    }

    private func setupTableView() {
        let tableView = UITableView()
        view.addSubview(tableView)
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        tableView.dataSource = self
        tableView.delegate = self
        tableView.addRefreshControll(actionTarget: self, action: #selector(refreshData))
        self.tableView = tableView
    }
}

extension ViewController {
    @objc func refreshData(_ refreshControl: UIRefreshControl) {
        print("refreshing")
        tableView?.endRefreshing(deadline: .now() + .seconds(3))
    }
}

extension ViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int { return 1 }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = "\(indexPath)"
        return cell
    }
}

extension ViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.pullAndRefresh()
    }
}

Change navbar color in Twitter Bootstrap

tl;dr - TWBSColor - Generate your own Bootstrap navbar

Version notes: - Online tool: Bootstrap 3.3.2+ / 4.0.0+ - This answer: Bootstrap 3.0.x

Available navbars

You've got two basic navbars:

<!-- A light one -->
<nav class="navbar navbar-default" role="navigation"></nav>
<!-- A dark one -->
<nav class="navbar navbar-inverse" role="navigation"></nav>

Default color usage

Here are the main colors and their usage:

  • #F8F8F8: navbar background
  • #E7E7E7: navbar border
  • #777: default color
  • #333: hover color (#5E5E5E for .nav-brand)
  • #555: active color
  • #D5D5D5: active background

Default style

If you want to put some custom style, here's the CSS you need to change:

/* navbar */
.navbar-default {
    background-color: #F8F8F8;
    border-color: #E7E7E7;
}
/* Title */
.navbar-default .navbar-brand {
    color: #777;
}
.navbar-default .navbar-brand:hover,
.navbar-default .navbar-brand:focus {
    color: #5E5E5E;
}
/* Link */
.navbar-default .navbar-nav > li > a {
    color: #777;
}
.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-nav > li > a:focus {
    color: #333;
}
.navbar-default .navbar-nav > .active > a,
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus {
    color: #555;
    background-color: #E7E7E7;
}
.navbar-default .navbar-nav > .open > a,
.navbar-default .navbar-nav > .open > a:hover,
.navbar-default .navbar-nav > .open > a:focus {
    color: #555;
    background-color: #D5D5D5;
}
/* Caret */
.navbar-default .navbar-nav > .dropdown > a .caret {
    border-top-color: #777;
    border-bottom-color: #777;
}
.navbar-default .navbar-nav > .dropdown > a:hover .caret,
.navbar-default .navbar-nav > .dropdown > a:focus .caret {
    border-top-color: #333;
    border-bottom-color: #333;
}
.navbar-default .navbar-nav > .open > a .caret,
.navbar-default .navbar-nav > .open > a:hover .caret,
.navbar-default .navbar-nav > .open > a:focus .caret {
    border-top-color: #555;
    border-bottom-color: #555;
}
/* Mobile version */
.navbar-default .navbar-toggle {
    border-color: #DDD;
}
.navbar-default .navbar-toggle:hover,
.navbar-default .navbar-toggle:focus {
    background-color: #DDD;
}
.navbar-default .navbar-toggle .icon-bar {
    background-color: #CCC;
}
@media (max-width: 767px) {
    .navbar-default .navbar-nav .open .dropdown-menu > li > a {
        color: #777;
    }
    .navbar-default .navbar-nav .open .dropdown-menu > li > a:hover,
    .navbar-default .navbar-nav .open .dropdown-menu > li > a:focus {
          color: #333;
    }
}

Custom colored navbar examples

Here are four examples of a custom colored navbar:

Enter image description here

And the SCSS code:

$bgDefault   : #e74c3c;
$bgHighlight : #c0392b;
$colDefault  : #ecf0f1;
$colHighlight: #ffbbbc;
.navbar-default {
  background-color: $bgDefault;
  border-color: $bgHighlight;
  .navbar-brand {
    color: $colDefault;
    &:hover, &:focus {
      color: $colHighlight; }}
  .navbar-text {
    color: $colDefault; }
  .navbar-nav {
    > li {
      > a {
        color: $colDefault;
        &:hover,  &:focus {
          color: $colHighlight; }}}
    > .active {
      > a, > a:hover, > a:focus {
        color: $colHighlight;
        background-color: $bgHighlight; }}
    > .open {
      > a, > a:hover, > a:focus {
        color: $colHighlight;
        background-color: $bgHighlight; }}}
  .navbar-toggle {
    border-color: $bgHighlight;
    &:hover, &:focus {
      background-color: $bgHighlight; }
    .icon-bar {
      background-color: $colDefault; }}
  .navbar-collapse,
  .navbar-form {
    border-color: $colDefault; }
  .navbar-link {
    color: $colDefault;
    &:hover {
      color: $colHighlight; }}}
@media (max-width: 767px) {
  .navbar-default .navbar-nav .open .dropdown-menu {
    > li > a {
      color: $colDefault;
      &:hover, &:focus {
        color: $colHighlight; }}
    > .active {
      > a, > a:hover, > a:focus, {
        color: $colHighlight;
        background-color: $bgHighlight; }}}
}

And finally, a little gift

I've just made a script which will allow you to generate your theme: TWBSColor - Generate your own Bootstrap navbar

[Update]: TWBSColor now generates SCSS/SASS/Less/CSS code.
[Update]: From now, you can use Less as the default language provided by TWBSColor
[Update]: TWBSColor now supports drop down menus colorization
[Update]: TWBSColor now allows to choose your version (Bootstrap 4 support added)

Make $JAVA_HOME easily changable in Ubuntu

This will probably solve your problem: https://help.ubuntu.com/community/EnvironmentVariables

Session-wide environment variables

In order to set environment variables in a way that affects a particular user's environment, one should not place commands to set their values in particular shell script files in the user's home directory, but use:

~/.pam_environment - This file is specifically meant for setting a user's environment. It is not a script file, but rather consists of assignment expressions, one per line.

Not recommended:

~/.profile - This is probably the best file for placing environment variable assignments in, since it gets executed automatically by the DisplayManager during the startup process desktop session as well as by the login shell when one logs-in from the textual console.

How to make a boolean variable switch between true and false every time a method is invoked?

Without looking at it, set it to not itself. I don't know how to code it in Java, but in Objective-C I would say

booleanVariable = !booleanVariable;

This flips the variable.

SELECT INTO Variable in MySQL DECLARE causes syntax error?

You can also use SET instead of DECLARE

SET @myvar := (SELECT somevalue INTO myvar FROM mytable WHERE uid=1);

SELECT myvar;

Print current call stack from a method in Python code

Here's an example of getting the stack via the traceback module, and printing it:

import traceback

def f():
    g()

def g():
    for line in traceback.format_stack():
        print(line.strip())

f()

# Prints:
# File "so-stack.py", line 10, in <module>
#     f()
# File "so-stack.py", line 4, in f
#     g()
# File "so-stack.py", line 7, in g
#     for line in traceback.format_stack():

If you really only want to print the stack to stderr, you can use:

traceback.print_stack()

Or to print to stdout (useful if want to keep redirected output together), use:

traceback.print_stack(file=sys.stdout)

But getting it via traceback.format_stack() lets you do whatever you like with it.

How to configure Spring Security to allow Swagger URL to be accessed without authentication

I updated with /configuration/** and /swagger-resources/** and it worked for me.

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/**", "/swagger-ui.html", "/webjars/**");

}

Which variable size to use (db, dw, dd) with x86 assembly?

The full list is:

DB, DW, DD, DQ, DT, DDQ, and DO (used to declare initialized data in the output file.)

See: http://www.tortall.net/projects/yasm/manual/html/nasm-pseudop.html

They can be invoked in a wide range of ways: (Note: for Visual-Studio - use "h" instead of "0x" syntax - eg: not 0x55 but 55h instead):

    db      0x55                ; just the byte 0x55
    db      0x55,0x56,0x57      ; three bytes in succession
    db      'a',0x55            ; character constants are OK
    db      'hello',13,10,'$'   ; so are string constants
    dw      0x1234              ; 0x34 0x12
    dw      'A'                 ; 0x41 0x00 (it's just a number)
    dw      'AB'                ; 0x41 0x42 (character constant)
    dw      'ABC'               ; 0x41 0x42 0x43 0x00 (string)
    dd      0x12345678          ; 0x78 0x56 0x34 0x12
    dq      0x1122334455667788  ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
    ddq     0x112233445566778899aabbccddeeff00
    ; 0x00 0xff 0xee 0xdd 0xcc 0xbb 0xaa 0x99
    ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
    do      0x112233445566778899aabbccddeeff00 ; same as previous
    dd      1.234567e20         ; floating-point constant
    dq      1.234567e20         ; double-precision float
    dt      1.234567e20         ; extended-precision float

DT does not accept numeric constants as operands, and DDQ does not accept float constants as operands. Any size larger than DD does not accept strings as operands.

Making an asynchronous task in Flask

I would use Celery to handle the asynchronous task for you. You'll need to install a broker to serve as your task queue (RabbitMQ and Redis are recommended).

app.py:

from flask import Flask
from celery import Celery

broker_url = 'amqp://guest@localhost'          # Broker URL for RabbitMQ task queue

app = Flask(__name__)    
celery = Celery(app.name, broker=broker_url)
celery.config_from_object('celeryconfig')      # Your celery configurations in a celeryconfig.py

@celery.task(bind=True)
def some_long_task(self, x, y):
    # Do some long task
    ...

@app.route('/render/<id>', methods=['POST'])
def render_script(id=None):
    ...
    data = json.loads(request.data)
    text_list = data.get('text_list')
    final_file = audio_class.render_audio(data=text_list)
    some_long_task.delay(x, y)                 # Call your async task and pass whatever necessary variables
    return Response(
        mimetype='application/json',
        status=200
    )

Run your Flask app, and start another process to run your celery worker.

$ celery worker -A app.celery --loglevel=debug

I would also refer to Miguel Gringberg's write up for a more in depth guide to using Celery with Flask.

Where is Xcode's build folder?

With a project previously created in Xcode3, I see an intermediate directory under build/ called Foo.build where Foo is my project's name, and then in that are the directories you'd expect (Debug-iphonesimulator, Release-iphoneos, etc, assuming you've done a build of that type) containing the object files and products.

Now, I suspect that if you start a new project in Xcode4, the default location is under DerivedData, but if you open an Xcode3 project in Xcode4, then Xcode4 uses the build/ directory (as described above). So, there are several correct answers. :-) Under the File menu, Project Settings, you can see you can customize how XCode works in this regard as much or as little as you like.

Notification bar icon turns white in Android 5 Lollipop

Post android Lollipop release android has changed the guidelines for displaying notification icons in the Notification bar. The official documentation says "Update or remove assets that involve color. The system ignores all non-alpha channels in action icons and in the main notification icon. You should assume that these icons will be alpha-only. The system draws notification icons in white and action icons in dark gray.” Now what that means in lay man terms is "Convert all parts of the image that you don’t want to show to transparent pixels. All colors and non transparent pixels are displayed in white"

You can see how to do this in detail with screenshots here https://blog.clevertap.com/fixing-notification-icon-for-android-lollipop-and-above/

Hope that helps

What's the difference between & and && in MATLAB?

Both are logical AND operations. The && though, is a "short-circuit" operator. From the MATLAB docs:

They are short-circuit operators in that they evaluate their second operand only when the result is not fully determined by the first operand.

See more here.

PHP Get Highest Value from Array

<?php 
$array = array("a"=>1,"b"=>2,"c"=>4,"d"=>5); 

foreach ($array as $key => $value) {
   if ($value >= $max) 
    $max = $key;     
}
echo " The array in largest number :".$max."<br/>";
?> 

How to get an element by its href in jquery?

If you want to get any element that has part of a URL in their href attribute you could use:

$( 'a[href*="google.com"]' );

This will select all elements with a href that contains google.com, for example:

As stated by @BalusC in the comments below, it will also match elements that have google.com at any position in the href, like blahgoogle.com.

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

You usually get this error if your tables use the InnoDB engine. In that case you would have to drop the foreign key, and then do the alter table and drop the column.

But the tricky part is that you can't drop the foreign key using the column name, but instead you would have to find the name used to index it. To find that, issue the following select:

SHOW CREATE TABLE region;

This should show you the name of the index, something like this:

CONSTRAINT region_ibfk_1 FOREIGN KEY (country_id) REFERENCES country (id) ON DELETE NO ACTION ON UPDATE NO ACTION

Now simply issue an:

alter table region drop foreign key region_ibfk_1;

And finally an:

alter table region drop column country_id;

And you are good to go!

npm behind a proxy fails with status 403

If you need to provide a username and password to authenticate at your proxy, this is the syntax to use:

npm config set proxy http://usr:pwd@host:port
npm config set https-proxy http://usr:pwd@host:port

How to create an array of object literals in a loop?

You can do something like that in ES6.

new Array(10).fill().map((e,i) => {
   return {idx: i}
});

How to set variable from a SQL query?

To ASSIGN variables using a SQL select the best practice is as shown below

->DECLARE co_id INT ;
->DECLARE sname VARCHAR(10) ;

->SELECT course_id INTO co_id FROM course_details ;
->SELECT student_name INTO sname FROM course_details;

IF you have to assign more than one variable in a single line you can use this same SELECT INTO

->DECLARE val1 int;
->DECLARE val2 int;

->SELECT student__id,student_name INTO val1,val2 FROM student_details;

--HAPPY CODING-- 

How to update and delete a cookie?

check this out A little framework: a complete cookies reader/writer with full Unicode support

/*\
|*|
|*|  :: cookies.js ::
|*|
|*|  A complete cookies reader/writer framework with full unicode support.
|*|
|*|  Revision #1 - September 4, 2014
|*|
|*|  https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
|*|  https://developer.mozilla.org/User:fusionchess
|*|  https://github.com/madmurphy/cookies.js
|*|
|*|  This framework is released under the GNU Public License, version 3 or later.
|*|  http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*|  Syntaxes:
|*|
|*|  * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*|  * docCookies.getItem(name)
|*|  * docCookies.removeItem(name[, path[, domain]])
|*|  * docCookies.hasItem(name)
|*|  * docCookies.keys()
|*|
\*/

var docCookies = {
  getItem: function (sKey) {
    if (!sKey) { return null; }
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toUTCString();
          break;
      }
    }
    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  removeItem: function (sKey, sPath, sDomain) {
    if (!this.hasItem(sKey)) { return false; }
    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
    return true;
  },
  hasItem: function (sKey) {
    if (!sKey) { return false; }
    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  },
  keys: function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
    return aKeys;
  }
};

Can I give a default value to parameters or optional parameters in C# functions?

This is a feature of C# 4.0, but was not possible without using function overload prior to that version.

Stylesheet not loaded because of MIME-type

Remove rel="stylesheet" and add type="text/html". So it will look like this -

<link  href="styles.css" type="text/html" />

Append key/value pair to hash with << in Ruby

Since hashes aren't inherently ordered, there isn't a notion of appending. Ruby hashes since 1.9 maintain insertion order, however. Here are the ways to add new key/value pairs.

The simplest solution is

h[:key] = "bar"

If you want a method, use store:

h.store(:key, "bar")

If you really, really want to use a "shovel" operator (<<), it is actually appending to the value of the hash as an array, and you must specify the key:

h[:key] << "bar"

The above only works when the key exists. To append a new key, you have to initialize the hash with a default value, which you can do like this:

h = Hash.new {|h, k| h[k] = ''}
h[:key] << "bar"

You may be tempted to monkey patch Hash to include a shovel operator that works in the way you've written:

class Hash
  def <<(k,v)
    self.store(k,v)
  end
end

However, this doesn't inherit the "syntactic sugar" applied to the shovel operator in other contexts:

h << :key, "bar" #doesn't work
h.<< :key, "bar" #works

How do I revert all local changes in Git managed project to previous state?

If you want to revert changes made to your working copy, do this:

git checkout .

If you want to revert changes made to the index (i.e., that you have added), do this. Warning this will reset all of your unpushed commits to master!:

git reset

If you want to revert a change that you have committed, do this:

git revert <commit 1> <commit 2>

If you want to remove untracked files (e.g., new files, generated files):

git clean -f

Or untracked directories (e.g., new or automatically generated directories):

git clean -fd

Eclipse says: “Workspace in use or cannot be created, chose a different one.” How do I unlock a workspace?

I've seen 3 other fixes so far:

  1. in .metadata/, rm .lock file
  2. if #1 doesn't work, try killing the process javaw.exe etc. then rm .lock file
  3. if #1 and #2 don't work, try rm .log file in .metadata/, and double check .plugin/.
  4. This has always worked for me: relocate .metadata/, open and close eclipse, then overwrite .metadata back

The solution boils down to cleaning up the .metadata folder.

Binding multiple events to a listener (without JQuery)?

ES2015:

let el = document.getElementById("el");
let handler =()=> console.log("changed");
['change', 'keyup', 'cut'].forEach(event => el.addEventListener(event, handler));

Windows command to get service status?

Using pstools - in particular psservice and "query" - for example:

psservice query "serviceName"

Maximum length of the textual representation of an IPv6 address?

As indicated a standard ipv6 address is at most 45 chars, but an ipv6 address can also include an ending % followed by a "scope" or "zone" string, which has no fixed length but is generally a small positive integer or a network interface name, so in reality it can be bigger than 45 characters. Network interface names are typically "eth0", "eth1", "wlan0", so choosing 50 as the limit is likely good enough.

Easiest way to toggle 2 classes in jQuery

I've made a jQuery plugin for working DRY:

$.fn.toggle2classes = function(class1, class2){
  if( !class1 || !class2 )
    return this;

  return this.each(function(){
    var $elm = $(this);

    if( $elm.hasClass(class1) || $elm.hasClass(class2) )
      $elm.toggleClass(class1 +' '+ class2);

    else
      $elm.addClass(class1);
  });
};

You can just try it here, copy and run this in the console and then try:

$('body').toggle2classes('a', 'b');

"SSL certificate verify failed" using pip to install packages

pip install --trusted-host pypi.python.org autopep8 (any package name)

This command will add pypi.python.org to the trusted sources and will install all the required package.

I ran into the error myself and typing this command helped me install all the pip packages of python.

JQuery .each() backwards

Needed to do a reverse on $.each so i used Vinay idea:

//jQuery.each(collection, callback) =>
$.each($(collection).get().reverse(), callback func() {});

worked nicely, thanks

Find the number of employees in each department - SQL Oracle

SELECT d.DEPTNO
    , d.dname
    , COUNT(e.ename) AS count
FROM   emp e
      INNER JOIN dept d ON e.DEPTNO = d.deptno
GROUP BY d.deptno
      , d.dname;

How to select different app.config for several build configurations

You should consider ConfigGen. It was developed for this purpose. It produces a config file for each deployment machine, based on a template file and a settings file. I know that this doesn't answer your question specifically, but it might well answer your problem.

So rather than Debug, Release etc, you might have Test, UAT, Production etc. You can also have different settings for each developer machine, so that you can generate a config specific to your dev machine and change it without affecting any one else's deployment.

An example of usage might be...

<Target Name="BeforeBuild">
    <Exec Command="C:\Tools\cfg -s $(ProjectDir)App.Config.Settings.xls -t       
        $(ProjectDir)App.config.template.xml -o $(SolutionDir)ConfigGen" />

    <Exec Command="C:\Tools\cfg -s $(ProjectDir)App.Config.Settings.xls -t
        $(ProjectDir)App.config.template.xml -l -n $(ProjectDir)App.config" />
</Target>

If you place this in your .csproj file, and you have the following files...

$(ProjectDir)App.Config.Settings.xls

MachineName        ConfigFilePath   SQLServer        

default             App.config      DEVSQL005
Test                App.config      TESTSQL005
UAT                 App.config      UATSQL005
Production          App.config      PRODSQL005
YourLocalMachine    App.config      ./SQLEXPRESS


$(ProjectDir)App.config.template.xml 

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
   <configuration>
   <appSettings>
       <add key="ConnectionString" value="Data Source=[%SQLServer%]; 
           Database=DatabaseName; Trusted_Connection=True"/>
   </appSettings>
</configuration>

... then this will be the result...

From the first command, a config file generated for each environment specified in the xls file, placed in the output directory $(SolutionDir)ConfigGen

.../solutiondir/ConfigGen/Production/App.config

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
   <configuration>
   <appSettings>
       <add key="ConnectionString" value="Data Source=PRODSQL005; 
           Database=DatabaseName; Trusted_Connection=True"/>
   </appSettings>
</configuration>

From the second command, the local App.config used on your dev machine will be replaced with the generated config specified by the local (-l) switch and the filename (-n) switch.

Python: avoiding pylint warnings about too many arguments

First, one of Perlis's epigrams:

"If you have a procedure with 10 parameters, you probably missed some."

Some of the 10 arguments are presumably related. Group them into an object, and pass that instead.

Making an example up, because there's not enough information in the question to answer directly:

class PersonInfo(object):
  def __init__(self, name, age, iq):
    self.name = name
    self.age = age
    self.iq = iq

Then your 10 argument function:

def f(x1, x2, name, x3, iq, x4, age, x5, x6, x7):
  ...

becomes:

def f(personinfo, x1, x2, x3, x4, x5, x6, x7):
  ...

and the caller changes to:

personinfo = PersonInfo(name, age, iq)
result = f(personinfo, x1, x2, x3, x4, x5, x6, x7)

Get protocol + host name from URL

Here is a slightly improved version:

urls = [
    "http://stackoverflow.com:8080/some/folder?test=/questions/9626535/get-domain-name-from-url",
    "Stackoverflow.com:8080/some/folder?test=/questions/9626535/get-domain-name-from-url",
    "http://stackoverflow.com/some/folder?test=/questions/9626535/get-domain-name-from-url",
    "https://StackOverflow.com:8080?test=/questions/9626535/get-domain-name-from-url",
    "stackoverflow.com?test=questions&v=get-domain-name-from-url"]
for url in urls:
    spltAr = url.split("://");
    i = (0,1)[len(spltAr)>1];
    dm = spltAr[i].split("?")[0].split('/')[0].split(':')[0].lower();
    print dm

Output

stackoverflow.com
stackoverflow.com
stackoverflow.com
stackoverflow.com
stackoverflow.com

Fiddle: https://pyfiddle.io/fiddle/23e4976e-88d2-4757-993e-532aa41b7bf0/?i=true

How do I tokenize a string sentence in NLTK?

This is actually on the main page of nltk.org:

>>> import nltk
>>> sentence = """At eight o'clock on Thursday morning
... Arthur didn't feel very good."""
>>> tokens = nltk.word_tokenize(sentence)
>>> tokens
['At', 'eight', "o'clock", 'on', 'Thursday', 'morning',
'Arthur', 'did', "n't", 'feel', 'very', 'good', '.']

Collision resolution in Java HashMap

It isn't defined to do so. In order to achieve this functionality, you need to create a map that maps keys to lists of values:

Map<Foo, List<Bar>> myMap;

Or, you could use the Multimap from google collections / guava libraries

How to change the window title of a MATLAB plotting figure?

First you must create an empty figure with the following command.

figure('name','Title of the window here');

By doing this, the newly created figure becomes you active figure. Immediately after calling a plot() command, it will print your plotting onto this figure. So your window will have a title.

This is the code you must use:

figure('name','Title of the window here');

hold on

x = [0; 0.2; 0.4; 0.6; 0.8; 1; 1.2; 1.4; 1.6; 1.8; 2; 2.2; 2.4; 2.6; 2.8; 3; 3.2; 3.4; 3.6; 3.8; 4; 4.2; 4.4; 4.6; 4.8; 5; 5.2; 5.4; 5.6; 5.8; 6; 6.2; 6.4; 6.6; 6.8; 7; 7.2; 7.4; 7.6; 7.8; 8; 8.2; 8.4; 8.6; 8.8; 9; 9.2; 9.4; 9.6; 9.8; 10; 10.2; 10.4; 10.6; 10.8; 11; 11.2; 11.4; 11.6; 11.8; 12; 12.2; 12.4; 12.6; 12.8; 13; 13.2; 13.4; 13.6; 13.8; 14; 14.2; 14.4; 14.6; 14.8; 15; 15.2; 15.4; 15.6; 15.8; 16; 16.2; 16.4; 16.6; 16.8; 17; 17.2; 17.4; 17.6; 17.8; 18; 18.2; 18.4; 18.6; 18.8];
y = [0; 0.198669; 0.389418; 0.564642; 0.717356; 0.841471; 0.932039; 0.98545; 0.999574; 0.973848; 0.909297; 0.808496; 0.675463; 0.515501; 0.334988; 0.14112; -0.0583741; -0.255541; -0.44252; -0.611858; -0.756802; -0.871576; -0.951602; -0.993691; -0.996165; -0.958924; -0.883455; -0.772764; -0.631267; -0.464602; -0.279415; -0.0830894; 0.116549; 0.311541; 0.494113; 0.656987; 0.793668; 0.898708; 0.96792; 0.998543; 0.989358; 0.940731; 0.854599; 0.734397; 0.584917; 0.412118; 0.22289; 0.0247754; -0.174327; -0.366479; -0.544021; -0.699875; -0.827826; -0.922775; -0.980936; -0.99999; -0.979178; -0.919329; -0.822829; -0.693525; -0.536573; -0.358229; -0.165604; 0.033623; 0.23151; 0.420167; 0.592074; 0.740376; 0.859162; 0.943696; 0.990607; 0.998027; 0.965658; 0.894791; 0.788252; 0.650288; 0.486399; 0.303118; 0.107754; -0.0919069; -0.287903; -0.472422; -0.638107; -0.778352; -0.887567; -0.961397; -0.9969; -0.992659; -0.948844; -0.867202; -0.750987; -0.604833; -0.434566; -0.246974; -0.0495356];
plot(x, y, '--b');

x = [0; 0.2; 0.4; 0.6; 0.8; 1; 1.2; 1.4; 1.6; 1.8; 2; 2.2; 2.4; 2.6; 2.8; 3; 3.2; 3.4; 3.6; 3.8; 4; 4.2; 4.4; 4.6; 4.8; 5; 5.2; 5.4; 5.6; 5.8; 6; 6.2; 6.4; 6.6; 6.8; 7; 7.2; 7.4; 7.6; 7.8; 8; 8.2; 8.4; 8.6; 8.8; 9; 9.2; 9.4; 9.6; 9.8; 10; 10.2; 10.4; 10.6; 10.8; 11; 11.2; 11.4; 11.6; 11.8; 12; 12.2; 12.4; 12.6; 12.8; 13; 13.2; 13.4; 13.6; 13.8; 14; 14.2; 14.4; 14.6; 14.8; 15; 15.2; 15.4; 15.6; 15.8; 16; 16.2; 16.4; 16.6; 16.8; 17; 17.2; 17.4; 17.6; 17.8; 18; 18.2; 18.4; 18.6; 18.8];
y = [-1; -0.980133; -0.921324; -0.825918; -0.697718; -0.541836; -0.364485; -0.172736; 0.0257666; 0.223109; 0.411423; 0.583203; 0.731599; 0.850695; 0.935744; 0.983355; 0.991629; 0.960238; 0.890432; 0.784994; 0.648128; 0.48529; 0.302972; 0.108443; -0.0905427; -0.286052; -0.470289; -0.635911; -0.776314; -0.885901; -0.960303; -0.996554; -0.993208; -0.950399; -0.869833; -0.754723; -0.609658; -0.44042; -0.253757; -0.057111; 0.141679; 0.334688; 0.514221; 0.673121; 0.805052; 0.904756; 0.968256; 0.993023; 0.978068; 0.923987; 0.832937; 0.708548; 0.555778; 0.380717; 0.190346; -0.00774649; -0.205663; -0.395514; -0.56973; -0.721365; -0.844375; -0.933855; -0.986238; -0.999436; -0.972923; -0.907755; -0.806531; -0.673287; -0.513333; -0.333047; -0.139617; 0.0592467; 0.255615; 0.44166; 0.609964; 0.753818; 0.867487; 0.946439; 0.987526; 0.989111; 0.95113; 0.875097; 0.764044; 0.622398; 0.455806; 0.27091; 0.0750802; -0.123876; -0.318026; -0.499631; -0.66145; -0.797032; -0.900972; -0.969126; -0.998776];
plot(x, y, '-r');

hold off

title('My plot title');
xlabel('My x-axis title');
ylabel('My y-axis title');

Unzip a file with php

I updated answer of Morteza Ziaeemehr to a cleaner and better code, This will unzip a file provided within form into current directory using DIR.

<!DOCTYPE html>
<html>
<head>
  <meta charset='utf-8' >
  <title>Unzip</title>
  <style>
  body{
    font-family: arial, sans-serif;
    word-wrap: break-word;
  }
  .wrapper{
    padding:20px;
    line-height: 1.5;
    font-size: 1rem;
  }
  span{
    font-family: 'Consolas', 'courier new', monospace;
    background: #eee;
    padding:2px;
  }
  </style>
</head>
<body>
  <div class="wrapper">
    <?php
    if(isset($_GET['page']))
    {
      $type = $_GET['page'];
      global $con;
      switch($type)
        {
            case 'unzip':
            {    
                $zip_filename =$_POST['filename'];
                echo "Unzipping <span>" .__DIR__. "/" .$zip_filename. "</span> to <span>" .__DIR__. "</span><br>";
                echo "current dir: <span>" . __DIR__ . "</span><br>";
                $zip = new ZipArchive;
                $res = $zip->open(__DIR__ . '/' .$zip_filename);
                if ($res === TRUE) 
                {
                    $zip->extractTo(__DIR__);
                    $zip->close();
                    echo '<p style="color:#00C324;">Extract was successful! Enjoy ;)</p><br>';
                } 
                else 
                {
                    echo '<p style="color:red;">Zip file not found!</p><br>';
                }
                break;
            }
        }
    }
?>
End Script.
</div>
    <form name="unzip" id="unzip" role="form">
        <div class="body bg-gray">
            <div class="form-group">
                <input type="text" name="filename" class="form-control" placeholder="File Name (with extension)"/>
            </div>        
        </div>
    </form>

<script type="application/javascript">
$("#unzip").submit(function(event) {
  event.preventDefault();
    var url = "function.php?page=unzip"; // the script where you handle the form input.
    $.ajax({
     type: "POST",
     url: url,
     dataType:"json",
           data: $("#unzip").serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert(data.msg); // show response from the php script.
               document.getElementById("unzip").reset();
             }

           });

    return false; // avoid to execute the actual submit of the form
  });
</script>
</body>
</html> 

How to copy only a single worksheet to another workbook using vba

To copy a sheet to a workbook called TARGET:

Sheets("xyz").Copy After:=Workbooks("TARGET.xlsx").Sheets("abc")

This will put the copied sheet xyz in the TARGET workbook after the sheet abc Obviously if you want to put the sheet in the TARGET workbook before a sheet, replace Before for After in the code.

To create a workbook called TARGET you would first need to add a new workbook and then save it to define the filename:

Application.Workbooks.Add (xlWBATWorksheet)
ActiveWorkbook.SaveAs ("TARGET")

However this may not be ideal for you as it will save the workbook in a default location e.g. My Documents.

Hopefully this will give you something to go on though.

how to change attribute "hidden" in jquery

A. Wolff was leading you in the right direction. There are several attributes where you should not be setting a string value. You must toggle it with a boolean true or false.

.attr("hidden", false) will remove the attribute the same as using .removeAttr("hidden").

.attr("hidden", "false") is incorrect and the tag remains hidden.

You should not be setting hidden, checked, selected, or several others to any string value to toggle it.

How to insert pandas dataframe via mysqldb into database?

Andy Hayden mentioned the correct function (to_sql). In this answer, I'll give a complete example, which I tested with Python 3.5 but should also work for Python 2.7 (and Python 3.x):

First, let's create the dataframe:

# Create dataframe
import pandas as pd
import numpy as np

np.random.seed(0)
number_of_samples = 10
frame = pd.DataFrame({
    'feature1': np.random.random(number_of_samples),
    'feature2': np.random.random(number_of_samples),
    'class':    np.random.binomial(2, 0.1, size=number_of_samples),
    },columns=['feature1','feature2','class'])

print(frame)

Which gives:

   feature1  feature2  class
0  0.548814  0.791725      1
1  0.715189  0.528895      0
2  0.602763  0.568045      0
3  0.544883  0.925597      0
4  0.423655  0.071036      0
5  0.645894  0.087129      0
6  0.437587  0.020218      0
7  0.891773  0.832620      1
8  0.963663  0.778157      0
9  0.383442  0.870012      0

To import this dataframe into a MySQL table:

# Import dataframe into MySQL
import sqlalchemy
database_username = 'ENTER USERNAME'
database_password = 'ENTER USERNAME PASSWORD'
database_ip       = 'ENTER DATABASE IP'
database_name     = 'ENTER DATABASE NAME'
database_connection = sqlalchemy.create_engine('mysql+mysqlconnector://{0}:{1}@{2}/{3}'.
                                               format(database_username, database_password, 
                                                      database_ip, database_name))
frame.to_sql(con=database_connection, name='table_name_for_df', if_exists='replace')

One trick is that MySQLdb doesn't work with Python 3.x. So instead we use mysqlconnector, which may be installed as follows:

pip install mysql-connector==2.1.4  # version avoids Protobuf error

Output:

enter image description here

Note that to_sql creates the table as well as the columns if they do not already exist in the database.

Generating (pseudo)random alpha-numeric strings

I like this function for the job

function randomKey($length) {
    $pool = array_merge(range(0,9), range('a', 'z'),range('A', 'Z'));

    for($i=0; $i < $length; $i++) {
        $key .= $pool[mt_rand(0, count($pool) - 1)];
    }
    return $key;
}

echo randomKey(20);

How do I create 7-Zip archives with .NET?

SevenZipSharp is another solution. Creates 7-zip archives...

Removing highcharts.com credits link

You can customise the credits, changing the URL, text, Position etc. All the info is documented here: http://api.highcharts.com/highcharts/credits. To simply disable them altogether, use:

credits: {
    enabled: false
},

How do I insert an image in an activity with android studio?

copy the image that you want to show in android app and paste in drawable folder. given below code

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/image"
 />

Value Change Listener to JTextField

textBoxName.getDocument().addDocumentListener(new DocumentListener() {
   @Override
   public void insertUpdate(DocumentEvent e) {
       onChange();
   }

   @Override
   public void removeUpdate(DocumentEvent e) {
      onChange();
   }

   @Override
   public void changedUpdate(DocumentEvent e) {
      onChange();
   } 
});

But I would not just parse anything the user (maybe on accident) touches on his keyboard into an Integer. You should catch any Exceptions thrown and make sure the JTextField is not empty.

Extract images from PDF without resampling, in python?

Well I have been struggling with this for many weeks, many of these answers helped me through, but there was always something missing, apparently no one here has ever had problems with jbig2 encoded images.

In the bunch of PDF that I am to scan, images encoded in jbig2 are very popular.

As far as I understand there are many copy/scan machines that scan papers and transform them into PDF files full of jbig2 encoded images.

So after many days of tests decided to go for the answer proposed here by dkagedal long time ago.

Here is my step by step on linux: (if you have another OS I suggest to use a linux docker it's going to be much easier.)

First step:

apt-get install poppler-utils

Then I was able to run command line tool called pdfimages like this:

pdfimages -all myfile.pdf ./images_found/

With the above command you will be able to extract all the images contained in myfile.pdf and you will have them saved inside images_found (you have to create images_found before)

In the list you will find several types of images, png, jpg, tiff; all these are easily readable with any graphic tool.

Then you will have some files named like: -145.jb2e and -145.jb2g.

These 2 files contain ONE IMAGE encoded in jbig2 saved in 2 different files one for the header and one for the data

Again I have lost many days trying to find out how to convert those files into something readable and finally I came across this tool called jbig2dec

So first you need to install this magic tool:

apt-get install jbig2dec

then you can run:

jbig2dec -t png -145.jb2g -145.jb2e

You are going to finally be able to get all extracted images converted into something useful.

good luck!

How do I determine if a port is open on a Windows server?

On Windows you can use

netstat -na | find "your_port"

to narrow down the results. You can also filter for LISTENING, ESTABLISHED, TCP and such. Mind it's case-sensitive though.

Swift do-try-catch syntax

enum NumberError: Error {
  case NegativeNumber(number: Int)
  case ZeroNumber
  case OddNumber(number: Int)
}

extension NumberError: CustomStringConvertible {
         var description: String {
         switch self {
             case .NegativeNumber(let number):
                 return "Negative number \(number) is Passed."
             case .OddNumber(let number):
                return "Odd number \(number) is Passed."
             case .ZeroNumber:
                return "Zero is Passed."
      }
   }
}

 func validateEvenNumber(_ number: Int) throws ->Int {
     if number == 0 {
        throw NumberError.ZeroNumber
     } else if number < 0 {
        throw NumberError.NegativeNumber(number: number)
     } else if number % 2 == 1 {
         throw NumberError.OddNumber(number: number)
     }
    return number
}

Now Validate Number :

 do {
     let number = try validateEvenNumber(0)
     print("Valid Even Number: \(number)")
  } catch let error as NumberError {
     print(error.description)
  }

Assert that a WebElement is not present using Selenium WebDriver with java

Not Sure which version of selenium you are referring to, however some commands in selenium * can now do this: http://release.seleniumhq.org/selenium-core/0.8.0/reference.html

  • assertNotSomethingSelected
  • assertTextNotPresent

Etc..

Reading an image file into bitmap from sdcard, why am I getting a NullPointerException?

It works:

Bitmap bitmap = BitmapFactory.decodeFile(filePath);

Difference between SET autocommit=1 and START TRANSACTION in mysql (Have I missed something?)

Being aware of the transaction (autocommit, explicit and implicit) handling for your database can save you from having to restore data from a backup.

Transactions control data manipulation statement(s) to ensure they are atomic. Being "atomic" means the transaction either occurs, or it does not. The only way to signal the completion of the transaction to database is by using either a COMMIT or ROLLBACK statement (per ANSI-92, which sadly did not include syntax for creating/beginning a transaction so it is vendor specific). COMMIT applies the changes (if any) made within the transaction. ROLLBACK disregards whatever actions took place within the transaction - highly desirable when an UPDATE/DELETE statement does something unintended.

Typically individual DML (Insert, Update, Delete) statements are performed in an autocommit transaction - they are committed as soon as the statement successfully completes. Which means there's no opportunity to roll back the database to the state prior to the statement having been run in cases like yours. When something goes wrong, the only restoration option available is to reconstruct the data from a backup (providing one exists). In MySQL, autocommit is on by default for InnoDB - MyISAM doesn't support transactions. It can be disabled by using:

SET autocommit = 0

An explicit transaction is when statement(s) are wrapped within an explicitly defined transaction code block - for MySQL, that's START TRANSACTION. It also requires an explicitly made COMMIT or ROLLBACK statement at the end of the transaction. Nested transactions is beyond the scope of this topic.

Implicit transactions are slightly different from explicit ones. Implicit transactions do not require explicity defining a transaction. However, like explicit transactions they require a COMMIT or ROLLBACK statement to be supplied.

Conclusion

Explicit transactions are the most ideal solution - they require a statement, COMMIT or ROLLBACK, to finalize the transaction, and what is happening is clearly stated for others to read should there be a need. Implicit transactions are OK if working with the database interactively, but COMMIT statements should only be specified once results have been tested & thoroughly determined to be valid.

That means you should use:

SET autocommit = 0;

START TRANSACTION;
  UPDATE ...;

...and only use COMMIT; when the results are correct.

That said, UPDATE and DELETE statements typically only return the number of rows affected, not specific details. Convert such statements into SELECT statements & review the results to ensure correctness prior to attempting the UPDATE/DELETE statement.

Addendum

DDL (Data Definition Language) statements are automatically committed - they do not require a COMMIT statement. IE: Table, index, stored procedure, database, and view creation or alteration statements.

"Content is not allowed in prolog" when parsing perfectly valid XML on GAE

The encoding in your XML and XSD (or DTD) are different.
XML file header: <?xml version='1.0' encoding='utf-8'?>
XSD file header: <?xml version='1.0' encoding='utf-16'?>

Another possible scenario that causes this is when anything comes before the XML document type declaration. i.e you might have something like this in the buffer:

helloworld<?xml version="1.0" encoding="utf-8"?>  

or even a space or special character.

There are some special characters called byte order markers that could be in the buffer. Before passing the buffer to the Parser do this...

String xml = "<?xml ...";
xml = xml.trim().replaceFirst("^([\\W]+)<","<");

Put spacing between divs in a horizontal row?

This is because width when provided a % doesn't account for padding/margins. You will need to reduce the amount to possibly 24% or 24.5%. Once this is done you should be good, but you will need to provide different options based on the screen size if you want this to always work correct since you have a hardcoded margin, but a relative size.

Gradle build without tests

the different way to disable test tasks in the project is:

tasks.withType(Test) {enabled = false}

this behavior needed sometimes if you want to disable tests in one of a project(or the group of projects).

This way working for the all kind of test task, not just a java 'tests'. Also, this way is safe. Here's what I mean let's say: you have a set of projects in different languages: if we try to add this kind of record in main build.gradle:

 subprojects{
 .......
 tests.enabled=false
 .......
}

we will fail in a project when if we have no task called tests

Using Custom Domains With IIS Express

This is what worked for me (Updated for VS 2013, see revision history for 2010, for VS 2015 see this: https://stackoverflow.com/a/32744234/218971):

  1. Right-click your Web Application Project ? Properties ? Web, then configure the Servers section as follows:

    • Select IIS Express ? from the drop down
    • Project Url: http://localhost
    • Override application root URL: http://dev.example.com
    • Click Create Virtual Directory (if you get an error here you may need to disable IIS 5/6/7/8, change IIS's Default Site to anything but port :80, make sure Skype isn't using port 80, etc.)
  2. Optionally: Set the Start URL to http://dev.example.com

  3. Open %USERPROFILE%\My Documents\IISExpress\config\applicationhost.config (Windows XP, Vista, and 7) and edit the site definition in the <sites> config block to be along the lines of the following:

    <site name="DevExample" id="997005936">
        <application path="/" applicationPool="Clr2IntegratedAppPool">
            <virtualDirectory
                path="/"
                physicalPath="C:\path\to\application\root" />
        </application>
        <bindings>
            <binding
                protocol="http"
                bindingInformation=":80:dev.example.com" />
        </bindings>
        <applicationDefaults applicationPool="Clr2IntegratedAppPool" />
    </site>
    
  4. If running MVC: make sure the applicationPool is set to one of the "Integrated" options (like "Clr2IntegratedAppPool").

  5. Open your hosts file and add the line 127.0.0.1 dev.example.com.

  6. ? Start your application!

Some great advice from the comments:

  • You may need to run Visual Studio as Administrator.
  • If you want to make other devs see your IIS run netsh http add urlacl url=http://dev.example.com:80/ user=everyone
  • If you want the site to resolve for all hosts set bindingInformation="*:80:". Use any port you want, 80 is just convenient. To resolve all hosts you'll need to run Visual Studio as an administrator

preg_match(); - Unknown modifier '+'

This happened to me because I put a variable in the regex and sometimes its string value included a slash. Solution: preg_quote.

How can I check if a file exists in Perl?

Use:

if (-f $filePath)
{
  # code
}

-e returns true even if the file is a directory. -f will only return true if it's an actual file

PHP function use variable from outside

Do not forget that you also can pass these use variables by reference.

The use cases are when you need to change the use'd variable from inside of your callback (e.g. produce the new array of different objects from some source array of objects).

$sourcearray = [ (object) ['a' => 1], (object) ['a' => 2]];
$newarray = [];
array_walk($sourcearray, function ($item) use (&$newarray) {
    $newarray[] = (object) ['times2' => $item->a * 2];
});
var_dump($newarray);

Now $newarray will comprise (pseudocode here for brevity) [{times2:2},{times2:4}].

On the contrary, using $newarray with no & modifier would make outer $newarray variable be read-only accessible from within the closure scope. But $newarray within closure scope would be a completelly different newly created variable living only within the closure scope.

Despite both variables' names are the same these would be two different variables. The outer $newarray variable would comprise [] in this case after the code has finishes.

OpenCV error: the function is not implemented

Before installing libgtk2.0-dev and pkg-config or libqt4-dev. Make sure that you have uninstalled opencv. You can confirm this by running import cv2 on your python shell. If it fails, then install the needed packages and re-run cmake .

How to Specify "Vary: Accept-Encoding" header in .htaccess

To gzip up your font files as well!

add "x-font/otf x-font/ttf x-font/eot"

as in:

AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xml x-font/otf x-font/ttf x-font/eot

How to change the opacity (alpha, transparency) of an element in a canvas element after it has been drawn?

You can't. It's immediate mode graphics. But you can sort of simulate it by drawing a rectangle over it in the background color with an opacity.

If the image is over something other than a constant color, then it gets quite a bit trickier. You should be able to use the pixel manipulation methods in this case. Just save the area before drawing the image, and then blend that back on top with an opacity afterwards.

How to search through all Git and Mercurial commits in the repository for a certain string?

In addition to richq answer of using git log -g --grep=<regexp> or git grep -e <regexp> $(git log -g --pretty=format:%h): take a look at the following blog posts by Junio C Hamano, current git maintainer


Summary

Both git grep and git log --grep are line oriented, in that they look for lines that match specified pattern.

You can use git log --grep=<foo> --grep=<bar> (or git log --author=<foo> --grep=<bar> that internally translates to two --grep) to find commits that match either of patterns (implicit OR semantic).

Because of being line-oriented, the useful AND semantic is to use git log --all-match --grep=<foo> --grep=<bar> to find commit that has both line matching first and line matching second somewhere.

With git grep you can combine multiple patterns (all which must use the -e <regexp> form) with --or (which is the default), --and, --not, ( and ). For grep --all-match means that file must have lines that match each of alternatives.

PHP Composer update "cannot allocate memory" error (using Laravel 4)

I had the same problem using composer in wsl2.

Microsoft WSL team introduced a file called .wslconfig for tweaking WSL2 settings.

You basically have to create that file at %UserProfile%.wslconfig and set the settings below.

[wsl2]
memory=6GB  # Any size you feel like
swap=30GB
localhostForwarding=true

Restart your computer, and from now on, you won't have any problem with high memory consumption.

Hopefully, it helps!

How to convert list of numpy arrays into single numpy array?

I checked some of the methods for speed performance and find that there is no difference! The only difference is that using some methods you must carefully check dimension.

Timing:

|------------|----------------|-------------------|
|            | shape (10000)  |  shape (1,10000)  |
|------------|----------------|-------------------|
| np.concat  |    0.18280     |      0.17960      |
|------------|----------------|-------------------|
|  np.stack  |    0.21501     |      0.16465      |
|------------|----------------|-------------------|
| np.vstack  |    0.21501     |      0.17181      |
|------------|----------------|-------------------|
|  np.array  |    0.21656     |      0.16833      |
|------------|----------------|-------------------|

As you can see I tried 2 experiments - using np.random.rand(10000) and np.random.rand(1, 10000) And if we use 2d arrays than np.stack and np.array create additional dimension - result.shape is (1,10000,10000) and (10000,1,10000) so they need additional actions to avoid this.

Code:

from time import perf_counter
from tqdm import tqdm_notebook
import numpy as np
l = []
for i in tqdm_notebook(range(10000)):
    new_np = np.random.rand(10000)
    l.append(new_np)



start = perf_counter()
stack = np.stack(l, axis=0 )
print(f'np.stack: {perf_counter() - start:.5f}')

start = perf_counter()
vstack = np.vstack(l)
print(f'np.vstack: {perf_counter() - start:.5f}')

start = perf_counter()
wrap = np.array(l)
print(f'np.array: {perf_counter() - start:.5f}')

start = perf_counter()
l = [el.reshape(1,-1) for el in l]
conc = np.concatenate(l, axis=0 )
print(f'np.concatenate: {perf_counter() - start:.5f}')

Making href (anchor tag) request POST instead of GET?

To do POST you'll need to have a form.

<form action="employee.action" method="post">
    <input type="submit" value="Employee1" />
</form>

There are some ways to post data with hyperlinks, but you'll need some javascript, and a form.

Some tricks: Make a link use POST instead of GET and How do you post data with a link

Edit: to load response on a frame you can target your form to your frame:

<form action="employee.action" method="post" target="myFrame">

Trying to add adb to PATH variable OSX

Alternative: Install adb the easy way

If you don't want to have to worry about your path or updating adb manually, you can use homebrew instead.

brew cask install android-platform-tools

What is the easiest way to parse an INI file in Java?

Another option is Apache Commons Config also has a class for loading from INI files. It does have some runtime dependencies, but for INI files it should only require Commons collections, lang, and logging.

I've used Commons Config on projects with their properties and XML configurations. It is very easy to use and supports some pretty powerful features.

How to redirect the output of a PowerShell to a file during its execution

One possible solution, if your situation allows it:

  1. Rename MyScript.ps1 to TheRealMyScript.ps1
  2. Create a new MyScript.ps1 that looks like:

    .\TheRealMyScript.ps1 > output.txt

Difference between left join and right join in SQL Server

You seem to be asking, "If I can rewrite a RIGHT OUTER JOIN using LEFT OUTER JOIN syntax then why have a RIGHT OUTER JOIN syntax at all?" I think the answer to this question is, because the designers of the language didn't want to place such a restriction on users (and I think they would have been criticized if they did), which would force users to change the order of tables in the FROM clause in some circumstances when merely changing the join type.

Only using @JsonIgnore during serialization, but not deserialization

In my case, I have Jackson automatically (de)serializing objects that I return from a Spring MVC controller (I am using @RestController with Spring 4.1.6). I had to use com.fasterxml.jackson.annotation.JsonIgnore instead of org.codehaus.jackson.annotate.JsonIgnore, as otherwise, it simply did nothing.

How to convert datetime format to date format in crystal report using C#?

There are many ways you can do this. You can just use what is described here or you can do myDate.ToString("dd-MMM-yyyy"); There are plenty of help for this topic in the MSDN documentation.

You could also write you own DateExtension class which will allow you to go something like myDate.ToMyDateFormat();

    public static class DateTimeExtensions
    {
        public static DateTime ToMyDateFormat(this DateTime d)
        {
            return d.ToString("dd-MMM-yyyy");
        }
    }

How to get the selected item of a combo box to a string variable in c#

You can use as below:

string selected = cmbbox.Text;
MessageBox.Show(selected);

How to identify server IP address in PHP

I found this to work for me: GetHostByName("");

Running XAMPP v1.7.1 on Windows 7 running Apache webserver. Unfortunately it just give my gateway IP address.

How do I calculate r-squared using Python and Numpy?

From yanl (yet-another-library) sklearn.metrics has an r2_score function;

from sklearn.metrics import r2_score

coefficient_of_dermination = r2_score(y, p(x))

How to create correct JSONArray in Java using JSONObject

Here is some code using java 6 to get you started:

JSONObject jo = new JSONObject();
jo.put("firstName", "John");
jo.put("lastName", "Doe");

JSONArray ja = new JSONArray();
ja.put(jo);

JSONObject mainObj = new JSONObject();
mainObj.put("employees", ja);

Edit: Since there has been a lot of confusion about put vs add here I will attempt to explain the difference. In java 6 org.json.JSONArray contains the put method and in java 7 javax.json contains the add method.

An example of this using the builder pattern in java 7 looks something like this:

JsonObject jo = Json.createObjectBuilder()
  .add("employees", Json.createArrayBuilder()
    .add(Json.createObjectBuilder()
      .add("firstName", "John")
      .add("lastName", "Doe")))
  .build();

How to install pip in CentOS 7?

Below are the steps I followed to install python34 and pip

yum update -y
yum -y install yum-utils
yum -y groupinstall development
yum -y install https://centos7.iuscommunity.org/ius-release.rpm
yum makecache
yum -y install python34u  python34u-pip
python3.6 -v
echo "alias python=/usr/bin/python3.4" >> ~/.bash_profile
source ~/.bash_profile
pip3 install --upgrade pip

# if yum install python34u-pip doesnt work, try 

curl https://bootstrap.pypa.io/get-pip.py | python

How to Implement DOM Data Binding in JavaScript

It is very simple two way data binding in vanilla javascript....

<input type="text" id="inp" onkeyup="document.getElementById('name').innerHTML=document.getElementById('inp').value;">

<div id="name">

</div>

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

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

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

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

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

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

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

AngularJS sorting rows by table header

I think this working CodePen example that I created will show you exactly how to do what you want.

The template:

<section ng-app="app" ng-controller="MainCtrl">
  <span class="label">Ordered By: {{orderByField}}, Reverse Sort: {{reverseSort}}</span><br><br>
  <table class="table table-bordered">
    <thead>
      <tr>
        <th>
          <a href="#" ng-click="orderByField='firstName'; reverseSort = !reverseSort">
          First Name <span ng-show="orderByField == 'firstName'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
          </a>
        </th>
        <th>
          <a href="#" ng-click="orderByField='lastName'; reverseSort = !reverseSort">
            Last Name <span ng-show="orderByField == 'lastName'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
          </a>
        </th>
        <th>
          <a href="#" ng-click="orderByField='age'; reverseSort = !reverseSort">
          Age <span ng-show="orderByField == 'age'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
          </a>
        </th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="emp in data.employees|orderBy:orderByField:reverseSort">
        <td>{{emp.firstName}}</td>
        <td>{{emp.lastName}}</td>
        <td>{{emp.age}}</td>
      </tr>
    </tbody>
  </table>
</section>

The JavaScript code:

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.orderByField = 'firstName';
  $scope.reverseSort = false;

  $scope.data = {
    employees: [{
      firstName: 'John',
      lastName: 'Doe',
      age: 30
    },{
      firstName: 'Frank',
      lastName: 'Burns',
      age: 54
    },{
      firstName: 'Sue',
      lastName: 'Banter',
      age: 21
    }]
  };
});

Gradle Build Android Project "Could not resolve all dependencies" error

Add this to your gradle:

allprojects {
    buildscript {
        repositories {
            maven {
                url "https://dl.bintray.com/android/android-tools"
            }
        }
    }
...
}

Dynamically load a JavaScript file

Here is a simple one with callback and IE support:

function loadScript(url, callback) {

    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState) { //IE
        script.onreadystatechange = function () {
            if (script.readyState == "loaded" || script.readyState == "complete") {
                script.onreadystatechange = null;
                callback();
            }
        };
    } else { //Others
        script.onload = function () {
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

loadScript("https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function () {

     //jQuery loaded
     console.log('jquery loaded');

});

Input text dialog Android

How about this EXAMPLE? It seems straightforward.

final EditText txtUrl = new EditText(this);

// Set the default text to a link of the Queen
txtUrl.setHint("http://www.librarising.com/astrology/celebs/images2/QR/queenelizabethii.jpg");

new AlertDialog.Builder(this)
  .setTitle("Moustachify Link")
  .setMessage("Paste in the link of an image to moustachify!")
  .setView(txtUrl)
  .setPositiveButton("Moustachify", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
      String url = txtUrl.getText().toString();
      moustachify(null, url);
    }
  })
  .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
    }
  })
  .show(); 

Meaning of "487 Request Terminated"

The 487 Response indicates that the previous request was terminated by user/application action. The most common occurrence is when the CANCEL happens as explained above. But it is also not limited to CANCEL. There are other cases where such responses can be relevant. So it depends on where you are seeing this behavior and whether its a user or application action that caused it.

15.1.2 UAS Behavior==> BYE Handling in RFC 3261

The UAS MUST still respond to any pending requests received for that dialog. It is RECOMMENDED that a 487 (Request Terminated) response be generated to those pending requests.

Root user/sudo equivalent in Cygwin?

Based on @mat-khor's answer, I took the syswin su.exe, saved it as manufacture-syswin-su.exe, and wrote this wrapper script. It handles redirection of the command's stdout and stderr, so it can be used in a pipe, etc. Also, the script exits with the status of the given command.

Limitations:

  • The syswin-su options are currently hardcoded to use the current user. Prepending env USERNAME=... to the script invocation overrides it. If other options were needed, the script would have to distinguish between syswin-su and command arguments, e.g. splitting at the first --.
  • If the UAC prompt is cancelled or declined, the script hangs.

.

#!/bin/bash
set -e

# join command $@ into a single string with quoting (required for syswin-su)
cmd=$( ( set -x; set -- "$@"; ) 2>&1 | perl -nle 'print $1 if /\bset -- (.*)/' )

tmpDir=$(mktemp -t -d -- "$(basename "$0")_$(date '+%Y%m%dT%H%M%S')_XXX")
mkfifo -- "$tmpDir/out"
mkfifo -- "$tmpDir/err"

cat >> "$tmpDir/script" <<-SCRIPT
    #!/bin/env bash
    $cmd > '$tmpDir/out' 2> '$tmpDir/err'
    echo \$? > '$tmpDir/status'
SCRIPT

chmod 700 -- "$tmpDir/script"

manufacture-syswin-su -s bash -u "$USERNAME" -m -c "cygstart --showminimized bash -c '$tmpDir/script'" > /dev/null &
cat -- "$tmpDir/err" >&2 &
cat -- "$tmpDir/out"
wait $!
exit $(<"$tmpDir/status")

Unix: How to delete files listed in a file

You can use this one-liner:

cat 1.txt | xargs echo rm | sh

Which does shell expansion but executes rm the minimum number of times.

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

If everything mentioned above does not work try the following. It worked for me.

Remove your project from the server > Restart server > Add your project to server > Restart server.

Detailed Instruction:

1. Right click on server > Add and Remove
2. Select your project > Remove > Finish
3. Restart your server
4. Right click on server > Add and Remove
5. Select your project > Add > Finish
6. Restart your server again.

IIS error, Unable to start debugging on the webserver

Do you use or have IIS Rewrite installed on your machine? I have a similar problem on my machine but to get round it, I have web.config open as the current page in VS and press f5. I then have to navigate to the page to debug. It seems to work for me.

What is the difference between == and equals() in Java?

The String pool (aka interning) and Integer pool blur the difference further, and may allow you to use == for objects in some cases instead of .equals

This can give you greater performance (?), at the cost of greater complexity.

E.g.:

assert "ab" == "a" + "b";

Integer i = 1;
Integer j = i;
assert i == j;

Complexity tradeoff: the following may surprise you:

assert new String("a") != new String("a");

Integer i = 128;
Integer j = 128;
assert i != j;

I advise you to stay away from such micro-optimization, and always use .equals for objects, and == for primitives:

assert (new String("a")).equals(new String("a"));

Integer i = 128;
Integer j = 128;
assert i.equals(j);

SQL Server: How to check if CLR is enabled?

This is @Jason's answer but with simplified output

SELECT name, CASE WHEN value = 1 THEN 'YES' ELSE 'NO' END AS 'Enabled'
FROM sys.configurations WHERE name = 'clr enabled'

The above returns the following:

| name        | Enabled |
-------------------------
| clr enabled | YES     |

Tested on SQL Server 2017

How to use Checkbox inside Select Option

You can use this library on git for this purpose https://github.com/ehynds/jquery-ui-multiselect-widget

for initiating the selectbox use this

    $("#selectBoxId").multiselect().multiselectfilter();

and when you have the data ready in json (from ajax or any method), first parse the data & then assign the js array to it

    var js_arr = $.parseJSON(/*data from ajax*/);
    $("#selectBoxId").val(js_arr);
    $("#selectBoxId").multiselect("refresh");

Understanding esModuleInterop in tsconfig file

in your tsconfig you have to add: "esModuleInterop": true - it should help.

How to round to 2 decimals with Python?

You can use round operator for up to 2 decimal

num = round(343.5544, 2)
print(num) // output is 343.55

How is length implemented in Java Arrays?

I believe its just a property as you access it as a property.

String[] s = new String[]{"abc","def","ghi"}
System.out.println(s.length)

returns 3

if it was a method then you would call s.length() right?

Disable single warning error

If you only want to suppress a warning in a single line of code, you can use the suppress warning specifier:

#pragma warning(suppress: 4101)
// here goes your single line of code where the warning occurs

For a single line of code, this works the same as writing the following:

#pragma warning(push)
#pragma warning(disable: 4101)
// here goes your code where the warning occurs
#pragma warning(pop)

'typeid' versus 'typeof' in C++

The primary difference between the two is the following

  • typeof is a compile time construct and returns the type as defined at compile time
  • typeid is a runtime construct and hence gives information about the runtime type of the value.

typeof Reference: http://www.delorie.com/gnu/docs/gcc/gcc_36.html

typeid Reference: https://en.wikipedia.org/wiki/Typeid

How do I convert a datetime to date?

You can convert a datetime object to a date with the date() method of the date time object, as follows:

<datetime_object>.date()

Javascript one line If...else...else if statement

This is use mostly for assigning variable, and it uses binomial conditioning eg.

var time = Date().getHours(); // or something

var clockTime = time > 12 ? 'PM' : 'AM' ;

There is no ElseIf, for the sake of development don't use chaining, you can use switch which is much faster if you have multiple conditioning in .js

How to display JavaScript variables in a HTML page without document.write

innerHTML is fine and still valid. Use it all the time on projects big and small. I just flipped to an open tab in my IDE and there was one right there.

 document.getElementById("data-progress").innerHTML = "<img src='../images/loading.gif'/>";

Not much has changed in js + dom manipulation since 2005, other than the addition of more libraries. You can easily set other properties such as

   uploadElement.style.width = "100%";

What to use instead of "addPreferencesFromResource" in a PreferenceActivity?

To add more information to the correct answer above, after reading an example from Android-er I found you can easily convert your preference activity into a preference fragment. If you have the following activity:

public class MyPreferenceActivity extends PreferenceActivity
{
    @Override
    protected void onCreate(final Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.my_preference_screen);
    }
}

The only changes you have to make is to create an internal fragment class, move the addPreferencesFromResources() into the fragment, and invoke the fragment from the activity, like this:

public class MyPreferenceActivity extends PreferenceActivity
{
    @Override
    protected void onCreate(final Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
    }

    public static class MyPreferenceFragment extends PreferenceFragment
    {
        @Override
        public void onCreate(final Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.my_preference_screen);
        }
    }
}

There may be other subtleties to making more complex preferences from fragments; if so, I hope someone notes them here.

How do I convert a IPython Notebook into a Python file via commandline?

The following example turns an Iron Python Notebook called a_notebook.ipynb into a python script called a_python_script.py leaving out the cells tagged with the keyword remove, which I add manually to the cells that I don't want to end up in the script, leaving out visualizations and other steps that once I am done with the notebook I don't need to be executed by the script.

import nbformat as nbf
from nbconvert.exporters import PythonExporter
from nbconvert.preprocessors import TagRemovePreprocessor

with open("a_notebook.ipynb", 'r', encoding='utf-8') as f:
    the_notebook_nodes = nbf.read(f, as_version = 4)

trp = TagRemovePreprocessor()

trp.remove_cell_tags = ("remove",)

pexp = PythonExporter()

pexp.register_preprocessor(trp, enabled= True)

the_python_script, meta = pexp.from_notebook_node(the_notebook_nodes)

with open("a_python_script.py", 'w') as f:
    f.writelines(the_python_script)

How to create a sleep/delay in nodejs that is Blocking?

asynchronous call ping command to block current code to execution in specified milliseconds.

  • ping command is Cross-platform
  • start /b means: start program but not show window.

code as below:

const { execSync } = require('child_process')
// delay(blocking) specified milliseconds
function sleep(ms) {
    // special Reserved IPv4 Address(RFC 5736): 192.0.0.0
    // refer: https://en.wikipedia.org/wiki/Reserved_IP_addresses
    execSync(`start /b ping 192.0.0.0 -n 1 -w ${ms} > nul`)
}

// usage
console.log("delay 2500ms start\t:" + (new Date().getTime() / 1000).toFixed(3))
sleep(2500)
console.log("delay 2500ms end\t:" + (new Date().getTime() / 1000).toFixed(3))

notice important: Above is not a precision solution, it just approach the blocking time

How can I account for period (AM/PM) using strftime?

The Python time.strftime docs say:

When used with the strptime() function, the %p directive only affects the output hour field if the %I directive is used to parse the hour.

Sure enough, changing your %H to %I makes it work.

How do you add an SDK to Android Studio?

You have to put your SDK's in a given directory or .app directory. You have to do it in finder while you are out of the application i'm assuming, but personally I'd use terminal in Mac instead of doing it in the App itself or finder. According to Google:

On Windows and Mac, the individual tools and other SDK packages are saved within the Android Studio application directory. To access the tools directly, use a terminal to navigate into the application and locate the sdk/ directory. For example:

 Windows: \Users\<user>\AppData\Local\Android\android-studio\sdk\
 Mac: /Applications/Android\ Studio.app/sdk/

check if "it's a number" function in Oracle

This is a potential duplicate of Finding rows that don't contain numeric data in Oracle. Also see: How can I determine if a string is numeric in SQL?.

Here's a solution based on Michael Durrant's that works for integers.

SELECT foo
FROM bar
WHERE DECODE(TRIM(TRANSLATE(your_number,'0123456789',' ')), NULL, 'number','contains char') = 'number'

Adrian Carneiro posted a solution that works for decimals and others. However, as Justin Cave pointed out, this will incorrectly classify strings like '123.45.23.234' or '131+234'.

SELECT foo
FROM bar
WHERE DECODE(TRIM(TRANSLATE(your_number,'+-.0123456789',' ')), NULL, 'number','contains char') = 'number'

If you need a solution without PL/SQL or REGEXP_LIKE, this may help.

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6

For me, it was caused before I referred a library (specifically typeORM, using the ormconfig.js file, under the entities key) to the src folder, instead of the dist folder...

   "entities": [
      "src/db/entity/**/*.ts", // Pay attention to "src" and "ts" (this is wrong)
   ],

instead of

   "entities": [
      "dist/db/entity/**/*.js", // Pay attention to "dist" and "js" (this is the correct way)
   ],

Is the LIKE operator case-sensitive with MSSQL Server?

If you want to achieve a case sensitive search without changing the collation of the column / database / server, you can always use the COLLATE clause, e.g.

USE tempdb;
GO
CREATE TABLE dbo.foo(bar VARCHAR(32) COLLATE Latin1_General_CS_AS);
GO
INSERT dbo.foo VALUES('John'),('john');
GO
SELECT bar FROM dbo.foo 
  WHERE bar LIKE 'j%';
-- 1 row

SELECT bar FROM dbo.foo 
  WHERE bar COLLATE Latin1_General_CI_AS LIKE 'j%';
-- 2 rows

GO    
DROP TABLE dbo.foo;

Works the other way, too, if your column / database / server is case sensitive and you don't want a case sensitive search, e.g.

USE tempdb;
GO
CREATE TABLE dbo.foo(bar VARCHAR(32) COLLATE Latin1_General_CI_AS);
GO
INSERT dbo.foo VALUES('John'),('john');
GO
SELECT bar FROM dbo.foo 
  WHERE bar LIKE 'j%';
-- 2 rows

SELECT bar FROM dbo.foo 
  WHERE bar COLLATE Latin1_General_CS_AS LIKE 'j%';
-- 1 row

GO
DROP TABLE dbo.foo;

Swift - how to make custom header for UITableView?

If you are willing to use custom table header as table header, try the followings....

Updated for swift 3.0

Step 1

Create UITableViewHeaderFooterView for custom header..

import UIKit

class MapTableHeaderView: UITableViewHeaderFooterView {

    @IBOutlet weak var testView: UIView!

}

Step 2

Add custom header to UITableView

    override func viewDidLoad() {
            super.viewDidLoad()

            tableView.delegate = self
            tableView.dataSource = self

            //register the header view

            let nibName = UINib(nibName: "CustomHeaderView", bundle: nil)
            self.tableView.register(nibName, forHeaderFooterViewReuseIdentifier: "CustomHeaderView")


    }

    extension BranchViewController : UITableViewDelegate{

    }

    extension BranchViewController : UITableViewDataSource{

        func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            return 200
        }

        func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
            let headerView = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: "CustomHeaderView" ) as! MapTableHeaderView

            return headerView
        }

        func tableView(_ tableView: UITableView, numberOfRowsInSection section: 

    Int) -> Int {
            // retuen no of rows in sections
        }

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
            // retuen your custom cells    
        }

        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        }

        func numberOfSections(in tableView: UITableView) -> Int {
            // retuen no of sections
        }

        func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            // retuen height of row
        }


    }

json.dumps vs flask.jsonify

This is flask.jsonify()

def jsonify(*args, **kwargs):
    if __debug__:
        _assert_have_json()
    return current_app.response_class(json.dumps(dict(*args, **kwargs),
        indent=None if request.is_xhr else 2), mimetype='application/json')

The json module used is either simplejson or json in that order. current_app is a reference to the Flask() object i.e. your application. response_class() is a reference to the Response() class.

How do I save a stream to a file in C#?

You must not use StreamReader for binary files (like gifs or jpgs). StreamReader is for text data. You will almost certainly lose data if you use it for arbitrary binary data. (If you use Encoding.GetEncoding(28591) you will probably be okay, but what's the point?)

Why do you need to use a StreamReader at all? Why not just keep the binary data as binary data and write it back to disk (or SQL) as binary data?

EDIT: As this seems to be something people want to see... if you do just want to copy one stream to another (e.g. to a file) use something like this:

/// <summary>
/// Copies the contents of input to output. Doesn't close either stream.
/// </summary>
public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[8 * 1024];
    int len;
    while ( (len = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        output.Write(buffer, 0, len);
    }    
}

To use it to dump a stream to a file, for example:

using (Stream file = File.Create(filename))
{
    CopyStream(input, file);
}

Note that Stream.CopyTo was introduced in .NET 4, serving basically the same purpose.

Calling class staticmethod within the class body?

This is due to staticmethod being a descriptor and requires a class-level attribute fetch to exercise the descriptor protocol and get the true callable.

From the source code:

It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()); the instance is ignored except for its class.

But not directly from inside the class while it is being defined.

But as one commenter mentioned, this is not really a "Pythonic" design at all. Just use a module level function instead.

Pyspark: Filter dataframe based on multiple conditions

faster way (without pyspark.sql.functions)

    df.filter((df.d<5)&((df.col1 != df.col3) |
                    (df.col2 != df.col4) & 
                    (df.col1 ==df.col3)))\
    .show()

Wordpress - Images not showing up in the Media Library

Considering the files were not uploaded via media uploader, they are present in the server but there's no reference to them in your database (in a little more detail).

In order to fix it, install the Media Sync plugin. Once it's active, under Media > Media Sync > Scan Files and select the files you want to import by click the checkbox next to them. Make sure also you untick the selectbox Dry Run (test without making database changes).

Then, when the time comes for you to be ready, just click "Import Selected" and you should see something like this

Media Sync import images

Once it is finished, you can visit Media > Library and you'll see all your imported files there.

get one item from an array of name,value JSON

To answer your exact question you can get the exact behaviour you want by extending the Array prototype with:

Array.prototype.get = function(name) {
    for (var i=0, len=this.length; i<len; i++) {
        if (typeof this[i] != "object") continue;
        if (this[i].name === name) return this[i].value;
    }
};

this will add the get() method to all arrays and let you do what you want, i.e:

arr.get('k1'); //= abc

Find out time it took for a python script to complete execution

import sys
import timeit

start = timeit.default_timer()

#do some nice things...

stop = timeit.default_timer()
total_time = stop - start

# output running time in a nice format.
mins, secs = divmod(total_time, 60)
hours, mins = divmod(mins, 60)

sys.stdout.write("Total running time: %d:%d:%d.\n" % (hours, mins, secs))

How to get current foreground activity context in android?

@lockwobr Thanks for update

This does not work 100% of the time in api version 16, if you read the code on github the function "currentActivityThread" was change in Kitkat, so I want to say version 19ish, kind of hard to match api version to releases in github.

Having access to the current Activity is very handy. Wouldn’t it be nice to have a static getActivity method returning the current Activity with no unnecessary questions?

The Activity class is very useful. It gives access to the application’s UI thread, views, resources, and many more. Numerous methods require a Context, but how to get the pointer? Here are some ways:

  • Tracking the application’s state using overridden lifecycle methods. You have to store the current Activity in a static variable and you need access to the code of all Activities.
  • Tracking the application’s state using Instrumentation. Declare Instrumentation in the manifest, implement it and use its methods to track Activity changes. Passing an Activity pointer to methods and classes used in your Activities. Injecting the pointer using one of the code injection libraries. All of these approaches are rather inconvenient; fortunately, there is a much easier way to get the current Activity.
  • Seems like the system needs access to all Activities without the issues mentioned above. So, most likely there is a way to get Activities using only static calls. I spent a lot of time digging through the Android sources on grepcode.com, and I found what I was looking for. There is a class called ActivityThread. This class has access to all Activities and, what’s even better, has a static method for getting the current ActivityThread. There is only one little problem – the Activity list has package access.

Easy to solve using reflection:

public static Activity getActivity() {
    Class activityThreadClass = Class.forName("android.app.ActivityThread");
    Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null);
    Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
    activitiesField.setAccessible(true);

    Map<Object, Object> activities = (Map<Object, Object>) activitiesField.get(activityThread);
    if (activities == null)
        return null;

    for (Object activityRecord : activities.values()) {
        Class activityRecordClass = activityRecord.getClass();
        Field pausedField = activityRecordClass.getDeclaredField("paused");
        pausedField.setAccessible(true);
        if (!pausedField.getBoolean(activityRecord)) {
            Field activityField = activityRecordClass.getDeclaredField("activity");
            activityField.setAccessible(true);
            Activity activity = (Activity) activityField.get(activityRecord);
            return activity;
        }
    }

    return null;
}

Such a method can be used anywhere in the app and it’s much more convenient than all of the mentioned approaches. Moreover, it seems like it’s not as unsafe as it looks. It doesn’t introduce any new potential leaks or null pointers.

The above code snippet lacks exception handling and naively assumes that the first running Activity is the one we’re looking for. You might want to add some additional checks.

Blog Post

Why does one use dependency injection?

The main reason to use DI is that you want to put the responsibility of the knowledge of the implementation where the knowledge is there. The idea of DI is very much inline with encapsulation and design by interface. If the front end asks from the back end for some data, then is it unimportant for the front end how the back end resolves that question. That is up to the requesthandler.

That is already common in OOP for a long time. Many times creating code pieces like:

I_Dosomething x = new Impl_Dosomething();

The drawback is that the implementation class is still hardcoded, hence has the front end the knowledge which implementation is used. DI takes the design by interface one step further, that the only thing the front end needs to know is the knowledge of the interface. In between the DYI and DI is the pattern of a service locator, because the front end has to provide a key (present in the registry of the service locator) to lets its request become resolved. Service locator example:

I_Dosomething x = ServiceLocator.returnDoing(String pKey);

DI example:

I_Dosomething x = DIContainer.returnThat();

One of the requirements of DI is that the container must be able to find out which class is the implementation of which interface. Hence does a DI container require strongly typed design and only one implementation for each interface at the same time. If you need more implementations of an interface at the same time (like a calculator), you need the service locator or factory design pattern.

D(b)I: Dependency Injection and Design by Interface. This restriction is not a very big practical problem though. The benefit of using D(b)I is that it serves communication between the client and the provider. An interface is a perspective on an object or a set of behaviours. The latter is crucial here.

I prefer the administration of service contracts together with D(b)I in coding. They should go together. The use of D(b)I as a technical solution without organizational administration of service contracts is not very beneficial in my point of view, because DI is then just an extra layer of encapsulation. But when you can use it together with organizational administration you can really make use of the organizing principle D(b)I offers. It can help you in the long run to structure communication with the client and other technical departments in topics as testing, versioning and the development of alternatives. When you have an implicit interface as in a hardcoded class, then is it much less communicable over time then when you make it explicit using D(b)I. It all boils down to maintenance, which is over time and not at a time. :-)

How to use an image for the background in tkinter?

One simple method is to use place to use an image as a background image. This is the type of thing that place is really good at doing.

For example:

background_image=tk.PhotoImage(...)
background_label = tk.Label(parent, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

You can then grid or pack other widgets in the parent as normal. Just make sure you create the background label first so it has a lower stacking order.

Note: if you are doing this inside a function, make sure you keep a reference to the image, otherwise the image will be destroyed by the garbage collector when the function returns. A common technique is to add a reference as an attribute of the label object:

background_label.image = background_image

a tag as a submit button?

Try this code:

<form id="myform">
  <!-- form elements -->
  <a href="#" onclick="document.getElementById('myform').submit()">Submit</a>
</form>

But users with disabled JavaScript won't be able to submit the form, so you could add the following code:

<noscript>
  <input type="submit" value="Submit form!" />
</noscript>

How do I set the default value for an optional argument in Javascript?

You can also do this with ArgueJS:

function (){
  arguments = __({nodebox: undefined, str: [String: "hai"]})

  // and now on, you can access your arguments by
  //   arguments.nodebox and arguments.str
}

Can I access constants in settings.py from templates in Django?

Another way to do this is to create a custom template tag which can let you fish values out of the settings.

@register.tag
def value_from_settings(parser, token):
    try:
        # split_contents() knows not to split quoted strings.
        tag_name, var = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0]
    return ValueFromSettings(var)

class ValueFromSettings(template.Node):
    def __init__(self, var):
        self.arg = template.Variable(var)
    def render(self, context):        
        return settings.__getattr__(str(self.arg))

You can then use:

{% value_from_settings "FQDN" %}

to print it on any page, without jumping through context-processor hoops.

Calling constructors in c++ without new

I assume with the second line you actually mean:

Thing *thing = new Thing("uiae");

which would be the standard way of creating new dynamic objects (necessary for dynamic binding and polymorphism) and storing their address to a pointer. Your code does what JaredPar described, namely creating two objects (one passed a const char*, the other passed a const Thing&), and then calling the destructor (~Thing()) on the first object (the const char* one).

By contrast, this:

Thing thing("uiae");

creates a static object which is destroyed automatically upon exiting the current scope.