Programs & Examples On #External accessory

The External Accessory framework provides support for communicating with external hardware connected to an iOS-based device through the 30-pin dock connector or wirelessly using Bluetooth.

Cross-Origin Read Blocking (CORB)

I encountered this problem because the format of the jsonp response from the server is wrong. The incorrect response is as follows.

callback(["apple", "peach"])

The problem is, the object inside callback should be a correct json object, instead of a json array. So I modified some server code and changed its format:

callback({"fruit": ["apple", "peach"]})

The browser happily accepted the response after the modification.

How is AngularJS different from jQuery

AngularJS : AngularJS is for developing heavy web applications. AngularJS can use jQuery if it’s present in the web-app when the application is being bootstrapped. If it's not present in the script path, then AngularJS falls back to its own implementation of the subset of jQuery.

JQuery : jQuery is a small, fast, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler. jQuery simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.

Read more details here: angularjs-vs-jquery

Avoid synchronized(this) in Java?

The reason not to synchronize on this is that sometimes you need more than one lock (the second lock often gets removed after some additional thinking, but you still need it in the intermediate state). If you lock on this, you always have to remember which one of the two locks is this; if you lock on a private Object, the variable name tells you that.

From the reader's viewpoint, if you see locking on this, you always have to answer the two questions:

  1. what kind of access is protected by this?
  2. is one lock really enough, didn't someone introduce a bug?

An example:

class BadObject {
    private Something mStuff;
    synchronized setStuff(Something stuff) {
        mStuff = stuff;
    }
    synchronized getStuff(Something stuff) {
        return mStuff;
    }
    private MyListener myListener = new MyListener() {
        public void onMyEvent(...) {
            setStuff(...);
        }
    }
    synchronized void longOperation(MyListener l) {
        ...
        l.onMyEvent(...);
        ...
    }
}

If two threads begin longOperation() on two different instances of BadObject, they acquire their locks; when it's time to invoke l.onMyEvent(...), we have a deadlock because neither of the threads may acquire the other object's lock.

In this example we may eliminate the deadlock by using two locks, one for short operations and one for long ones.

Python Regex - How to Get Positions and Values of Matches

note that the span & group are indexed for multi capture groups in a regex

regex_with_3_groups=r"([a-z])([0-9]+)([A-Z])"
for match in re.finditer(regex_with_3_groups, string):
    for idx in range(0, 4):
        print(match.span(idx), match.group(idx))

Using LINQ to group a list of objects

var groupedCustomerList = CustomerList
                         .GroupBy(u => u.GroupID, u=>{
                                                        u.Name = "User" + u.Name;
                                                        return u;
                                                     }, (key,g)=>g.ToList())
                         .ToList();

If you don't want to change the original data, you should add some method (kind of clone and modify) to your class like this:

public class Customer {
  public int ID { get; set; }
  public string Name { get; set; }
  public int GroupID { get; set; }
  public Customer CloneWithNamePrepend(string prepend){
    return new Customer(){
          ID = this.ID,
          Name = prepend + this.Name,
          GroupID = this.GroupID
     };
  }
}    
//Then
var groupedCustomerList = CustomerList
                         .GroupBy(u => u.GroupID, u=>u.CloneWithNamePrepend("User"), (key,g)=>g.ToList())
                         .ToList();

I think you may want to display the Customer differently without modifying the original data. If so you should design your class Customer differently, like this:

public class Customer {
  public int ID { get; set; }
  public string Name { get; set; }
  public int GroupID { get; set; }
  public string Prefix {get;set;}
  public string FullName {
    get { return Prefix + Name;}
  }            
}
//then to display the fullname, just get the customer.FullName; 
//You can also try adding some override of ToString() to your class

var groupedCustomerList = CustomerList
                         .GroupBy(u => {u.Prefix="User", return u.GroupID;} , (key,g)=>g.ToList())
                         .ToList();

How can I add new array elements at the beginning of an array in Javascript?

If you want to push elements that are in a array at the beginning of you array use <func>.apply(<this>, <Array of args>) :

_x000D_
_x000D_
const arr = [1, 2];
arr.unshift.apply(arr, [3, 4]);
console.log(arr); // [3, 4, 1, 2]
_x000D_
_x000D_
_x000D_

Submit HTML form, perform javascript function (alert then redirect)

Looks like your form is submitting which is the default behaviour, you can stop it with this:

<form action="" method="post" onsubmit="completeAndRedirect();return false;">

How to round an image with Glide library?

You can simply call the RoundedCornersTransformation constructor, which has cornerType enum input. Like this:

Glide.with(context)
            .load(bizList.get(position).getCover())
            .bitmapTransform(new RoundedCornersTransformation(context,20,0, RoundedCornersTransformation.CornerType.TOP))
            .into(holder.bizCellCoverImg);

but first you have to add Glide Transformations to your project.

Angular 4: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

async is used for binding to Observables and Promises, but it seems like you're binding to a regular object. You can just remove both async keywords and it should probably work.

How do I detach objects in Entity Framework Code First?

This is an option:

dbContext.Entry(entity).State = EntityState.Detached;

How can I check if char* variable points to empty string?

Check the pointer for NULL and then using strlen to see if it returns 0.
NULL check is important because passing NULL pointer to strlen invokes an Undefined Behavior.

Determine the line of code that causes a segmentation fault?

There are a number of tools available which help debugging segmentation faults and I would like to add my favorite tool to the list: Address Sanitizers (often abbreviated ASAN).

Modern¹ compilers come with the handy -fsanitize=address flag, adding some compile time and run time overhead which does more error checking.

According to the documentation these checks include catching segmentation faults by default. The advantage here is that you get a stack trace similar to gdb's output, but without running the program inside a debugger. An example:

int main() {
  volatile int *ptr = (int*)0;
  *ptr = 0;
}
$ gcc -g -fsanitize=address main.c
$ ./a.out
AddressSanitizer:DEADLYSIGNAL
=================================================================
==4848==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000000 (pc 0x5654348db1a0 bp 0x7ffc05e39240 sp 0x7ffc05e39230 T0)
==4848==The signal is caused by a WRITE memory access.
==4848==Hint: address points to the zero page.
    #0 0x5654348db19f in main /tmp/tmp.s3gwjqb8zT/main.c:3
    #1 0x7f0e5a052b6a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x26b6a)
    #2 0x5654348db099 in _start (/tmp/tmp.s3gwjqb8zT/a.out+0x1099)

AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV /tmp/tmp.s3gwjqb8zT/main.c:3 in main
==4848==ABORTING

The output is slightly more complicated than what gdb would output but there are upsides:

  • There is no need to reproduce the problem to receive a stack trace. Simply enabling the flag during development is enough.

  • ASANs catch a lot more than just segmentation faults. Many out of bounds accesses will be caught even if that memory area was accessible to the process.


¹ That is Clang 3.1+ and GCC 4.8+.

TypeScript enum to object array

I didn't like any of the above answers because none of them correctly handle the mixture of strings/numbers that can be values in TypeScript enums.

The following function follows the semantics of TypeScript enums to give a proper Map of keys to values. From there, getting an array of objects or just the keys or just the values is trivial.

/**
 * Converts the given enum to a map of the keys to the values.
 * @param enumeration The enum to convert to a map.
 */
function enumToMap(enumeration: any): Map<string, string | number> {
  const map = new Map<string, string | number>();
  for (let key in enumeration) {
      //TypeScript does not allow enum keys to be numeric
      if (!isNaN(Number(key))) continue;

      const val = enumeration[key] as string | number;

      //TypeScript does not allow enum value to be null or undefined
      if (val !== undefined && val !== null)
          map.set(key, val);
  }

  return map;
}

Example Usage:

enum Dog {
    Rover = 1,
    Lassie = "Collie",
    Fido = 3,
    Cody = "Mutt",
}

let map = enumToMap(Dog); //Map of keys to values

let objs = Array.from(map.entries()).map(m => ({id: m[1], name: m[0]})); //Objects as asked for in OP
let entries = Array.from(map.entries()); //Array of each entry
let keys = Array.from(map.keys()); //An array of keys
let values = Array.from(map.values()); //An array of values

I'll also point out that the OP is thinking of enums backwards. The "key" in the enum is technically on the left hand side and the value is on the right hand side. TypeScript allows you to repeat the values on the RHS as much as you'd like.

git: updates were rejected because the remote contains work that you do not have locally

You can override any checks that git does by using "force push". Use this command in terminal

git push -f origin master

However, you will potentially ignore the existing work that is in remote - you are effectively rewriting the remote's history to be exactly like your local copy.

MongoDb shuts down with Code 100

In MacOS:-

If you forgot to give the path of the previously created database while running the mongo server, the above error will appear.

sudo ./mongod --dbpath ../../mongo-data/

Reference

Note :- ./mongod && ../../mongo-data is relative path. So you can avoid it by configuration in environment variable

Reference

JDBC ODBC Driver Connection

Didn't work with ODBC-Bridge for me too. I got the way around to initialize ODBC connection using ODBC driver.

 import java.sql.*;  
 public class UserLogin
 {
     public static void main(String[] args)
     {
        try
        {    
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            // C:\\databaseFileName.accdb" - location of your database 
           String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";

            // specify url, username, pasword - make sure these are valid 
            Connection conn = DriverManager.getConnection(url, "username", "password");

            System.out.println("Connection Succesfull");
         } 
         catch (Exception e) 
         {
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());

          }
      }
  }

Update row values where certain condition is met in pandas

You can do the same with .ix, like this:

In [1]: df = pd.DataFrame(np.random.randn(5,4), columns=list('abcd'))

In [2]: df
Out[2]: 
          a         b         c         d
0 -0.323772  0.839542  0.173414 -1.341793
1 -1.001287  0.676910  0.465536  0.229544
2  0.963484 -0.905302 -0.435821  1.934512
3  0.266113 -0.034305 -0.110272 -0.720599
4 -0.522134 -0.913792  1.862832  0.314315

In [3]: df.ix[df.a>0, ['b','c']] = 0

In [4]: df
Out[4]: 
          a         b         c         d
0 -0.323772  0.839542  0.173414 -1.341793
1 -1.001287  0.676910  0.465536  0.229544
2  0.963484  0.000000  0.000000  1.934512
3  0.266113  0.000000  0.000000 -0.720599
4 -0.522134 -0.913792  1.862832  0.314315

EDIT

After the extra information, the following will return all columns - where some condition is met - with halved values:

>> condition = df.a > 0
>> df[condition][[i for i in df.columns.values if i not in ['a']]].apply(lambda x: x/2)

I hope this helps!

Running conda with proxy

You can configure a proxy with conda by adding it to the .condarc, like

proxy_servers:
    http: http://user:[email protected]:8080
    https: https://user:[email protected]:8080

Then in cmd Anaconda Power Prompt (base) PS C:\Users\user> run:

conda update -n root conda

Using pip behind a proxy with CNTLM

I could achieve this by running:

pip install --proxy=http://user:[email protected]:3128 package==version

I'm using Python 3.7.3 inside a corporative proxy.

jQuery animated number counter from zero to value

This is work for me !

<script type="text/javascript">
$(document).ready(function(){
        countnumber(0,40,"stat1",50);
        function countnumber(start,end,idtarget,duration){
            cc=setInterval(function(){
                if(start==end)
                {
                    $("#"+idtarget).html(start);
                    clearInterval(cc);
                }
                else
                {
                   $("#"+idtarget).html(start);
                   start++;
                }
            },duration);
        }
    });
</script>
<span id="span1"></span>

Exception 'open failed: EACCES (Permission denied)' on Android

I had the same problem and none of suggestions helped. But I found an interesting reason for that, on a physical device, Galaxy Tab.

When USB storage is on, external storage read and write permissions don't have any effect. Just turn off USB storage, and with the correct permissions, you'll have the problem solved.

DELETE ... FROM ... WHERE ... IN

Try adding parentheses around the row in table1 e.g.

DELETE 
  FROM table1
 WHERE (stn, year(datum)) IN (SELECT stn, jaar FROM table2);

The above is Standard SQL-92 code. If that doesn't work, it could be that your SQL product of choice doesn't support it.

Here's another Standard SQL approach that is more widely implemented among vendors e.g. tested on SQL Server 2008:

MERGE INTO table1 AS t1
   USING table2 AS s1
      ON t1.stn = s1.stn
         AND s1.jaar = YEAR(t1.datum)
WHEN MATCHED THEN DELETE;

Excel: the Incredible Shrinking and Expanding Controls

This problem is very frustrating, my experience is that the properties are usually set properly on the ActiveX objects. I've modified a UDF from above to just be able to run on any active sheet, this will set everything back the way it was before shrinking.

Public Sub ResizeAllOfIt()
Dim myCtrl As OLEObject

For Each myCtrl In ActiveSheet.OLEObjects

 Dim originalHeight
 Dim originalWidth

 originalWidth = myCtrl.width
 originalHeight = myCtrl.height

  myCtrl.height = originalHeight - 1 
  myCtrl.height = originalHeight 
  myCtrl.width = originalWidth

Next myCtrl

End Sub

How to add number of days in postgresql datetime

For me I had to put the whole interval in single quotes not just the value of the interval.

select id,  
   title,
   created_at + interval '1 day' * claim_window as deadline from projects   

Instead of

select id,  
   title,
   created_at + interval '1' day * claim_window as deadline from projects   

Postgres Date/Time Functions

How do I make a file:// hyperlink that works in both IE and Firefox?

file Protocol
Opens a file on a local or network drive.

Syntax

Copy
 file:///sDrives[|sFile]
Tokens 

sDrives
Specifies the local or network drive.

sFile
Optional. Specifies the file to open. If sFile is omitted and the account accessing the drive has permission to browse the directory, a list of accessible files and directories is displayed.

Remarks

The file protocol and sDrives parameter can be omitted and substituted with just the command line representation of the drive letter and file location. For example, to browse the My Documents directory, the file protocol can be specified as file:///C|/My Documents/ or as C:\My Documents. In addition, a single '\' is equivalent to specifying the root directory on the primary local drive. On most computers, this is C:.

Available as of Microsoft Internet Explorer 3.0 or later.

Note Internet Explorer 6 Service Pack 1 (SP1) no longer allows browsing a local machine from the Internet zone. For instance, if an Internet site contains a link to a local file, Internet Explorer 6 SP1 displays a blank page when a user clicks on the link. Previous versions of Windows Internet Explorer followed the link to the local file.

Example

The following sample demonstrates four ways to use the File protocol.

Copy

//Specifying a drive and a file name. 

file:///C|/My Documents/ALetter.html

//Specifying only a drive and a path to browse the directory. 

file:///C|/My Documents/

//Specifying a drive and a directory using the command line representation of the directory location. 

C:\My Documents\

//Specifying only the directory on the local primary drive. 

\My Documents\

http://msdn.microsoft.com/en-us/library/aa767731

Best way to access web camera in Java

I think the project you are looking for is: https://github.com/sarxos/webcam-capture (I'm the author)

There is an example working exactly as you've described - after it's run, the window appear where, after you press "Start" button, you can see live image from webcam device and save it to file after you click on "Snapshot" (source code available, please note that FPS counter in the corner can be disabled):

snapshot

The project is portable (WinXP, Win7, Win8, Linux, Mac, Raspberry Pi) and does not require any additional software to be installed on the PC.

API is really nice and easy to learn. Example how to capture single image and save it to PNG file:

Webcam webcam = Webcam.getDefault();
webcam.open();
ImageIO.write(webcam.getImage(), "PNG", new File("test.png"));

Server returned HTTP response code: 401 for URL: https

Try This. You need pass the authentication to let the server know its a valid user. You need to import these two packages and has to include a jersy jar. If you dont want to include jersy jar then import this package

import sun.misc.BASE64Encoder;

import com.sun.jersey.core.util.Base64;
import sun.net.www.protocol.http.HttpURLConnection;

and then,

String encodedAuthorizedUser = getAuthantication("username", "password");
URL url = new URL("Your Valid Jira URL");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setRequestProperty ("Authorization", "Basic " + encodedAuthorizedUser );

 public String getAuthantication(String username, String password) {
   String auth = new String(Base64.encode(username + ":" + password));
   return auth;
 }

Why is JavaFX is not included in OpenJDK 8 on Ubuntu Wily (15.10)?

According to the packages list in Ubuntu Wily Xenial Bionic there is a package named openjfx. This should be a candidate for what you're looking for:

JavaFX/OpenJFX 8 - Rich client application platform for Java

You can install it via:

sudo apt-get install openjfx

It provides the following JAR files to the OpenJDK installation on Ubuntu systems:

/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/ext/jfxrt.jar
/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/jfxswt.jar
/usr/lib/jvm/java-8-openjdk-amd64/lib/ant-javafx.jar
/usr/lib/jvm/java-8-openjdk-amd64/lib/javafx-mx.jar

If you want to have sources available, for example for debugging, you can additionally install:

sudo apt-get install openjfx-source

How to retrieve Key Alias and Key Password for signed APK in android studio(migrated from Eclipse)

You might like to try this password breaker.

http://maxcamillo.github.io/android-keystore-password-recover/index.html

I was using the Dictionary Attack method. It worked for me because there were only a few combinations to my password that I could think of.

Tomcat request timeout

For anyone who doesn't like none of the solutions posted above like me then you can simply implement a timer yourself and stop the request execution by throwing a runtime exception. Something like below:

                  try 
                 {
                     timer.schedule(new TimerTask() {
                       @Override
                       public void run() {
                         timer.cancel();
                       }
                     }, /* specify time of the requst */ 1000);
                 }
                 catch(Exception e)
                 {
                   throw new RuntimeException("the request is taking longer than usual");
                 }

   

or preferably use the java guava timeLimiter here

Web.Config Debug/Release

The web.config transforms that are part of Visual Studio 2010 use XSLT in order to "transform" the current web.config file into its .Debug or .Release version.

In your .Debug/.Release files, you need to add the following parameter in your connection string fields:

xdt:Transform="SetAttributes" xdt:Locator="Match(name)"

This will cause each connection string line to find the matching name and update the attributes accordingly.

Note: You won't have to worry about updating your providerName parameter in the transform files, since they don't change.

Here's an example from one of my apps. Here's the web.config file section:

<connectionStrings>
      <add name="EAF" connectionString="[Test Connection String]" />
</connectionString>

And here's the web.config.release section doing the proper transform:

<connectionStrings>
      <add name="EAF" connectionString="[Prod Connection String]"
           xdt:Transform="SetAttributes"
           xdt:Locator="Match(name)" />
</connectionStrings>

One added note: Transforms only occur when you publish the site, not when you simply run it with F5 or CTRL+F5. If you need to run an update against a given config locally, you will have to manually change your Web.config file for this.

For more details you can see the MSDN documentation

https://msdn.microsoft.com/en-us/library/dd465326(VS.100).aspx

How to save and load cookies using Python + Selenium WebDriver

Based on the answer by Eduard Florinescu, but with newer code and the missing imports added:

$ cat work-auth.py
#!/usr/bin/python3

# Setup:
# sudo apt-get install chromium-chromedriver
# sudo -H python3 -m pip install selenium

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('/usr/bin/chromedriver',options=chrome_options)
chrome_options.add_argument("user-data-dir=chrome-data")
driver.get('https://www.somedomainthatrequireslogin.com')
time.sleep(30)  # Time to enter credentials
driver.quit()

$ cat work.py
#!/usr/bin/python3

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('/usr/bin/chromedriver',options=chrome_options)
driver.get('https://www.somedomainthatrequireslogin.com')  # Already authenticated
time.sleep(10)
driver.quit()

shell script. how to extract string using regular expressions

One way would be with sed. For example:

echo $name | sed -e 's?http://www\.??'

Normally the sed regular expressions are delimited by `/', but you can use '?' since you're searching for '/'. Here's another bash trick. @DigitalTrauma's answer reminded me that I ought to suggest it. It's similar:

echo ${name#http://www.}

(DigitalTrauma also gets credit for reminding me that the "http://" needs to be handled.)

Playing mp3 song on python

At this point, why not mentioning python-audio-tools:

It's the best solution I found.

(I needed to install libasound2-dev, on Raspbian)

Code excerpt loosely based on:
https://github.com/tuffy/python-audio-tools/blob/master/trackplay

#!/usr/bin/python

import os
import re
import audiotools.player


START = 0
INDEX = 0

PATH = '/path/to/your/mp3/folder'

class TracklistPlayer:
    def __init__(self,
                 tr_list,
                 audio_output=audiotools.player.open_output('ALSA'),  
                 replay_gain=audiotools.player.RG_NO_REPLAYGAIN,
                 skip=False):

        if skip:
            return

        self.track_index = INDEX + START - 1
        if self.track_index < -1:
            print('--> [track index was negative]')
            self.track_index = self.track_index + len(tr_list)

        self.track_list = tr_list

        self.player = audiotools.player.Player(
                audio_output,
                replay_gain,
                self.play_track)

        self.play_track(True, False)

    def play_track(self, forward=True, not_1st_track=True):
        try:
            if forward:
                self.track_index += 1
            else:
                self.track_index -= 1

            current_track = self.track_list[self.track_index]
            audio_file = audiotools.open(current_track)
            self.player.open(audio_file)
            self.player.play()

            print('--> index:   ' + str(self.track_index))
            print('--> PLAYING: ' + audio_file.filename)

            if not_1st_track:
                pass  # here I needed to do something :)

            if forward:
                pass  # ... and also here

        except IndexError:
            print('\n--> playing finished\n')

    def toggle_play_pause(self):
        self.player.toggle_play_pause()

    def stop(self):
        self.player.stop()

    def close(self):
        self.player.stop()
        self.player.close()


def natural_key(el):
    """See http://www.codinghorror.com/blog/archives/001018.html"""
    return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', el)]


def natural_cmp(a, b):
    return cmp(natural_key(a), natural_key(b))


if __name__ == "__main__":

    print('--> path:    ' + PATH)

    # remove hidden files (i.e. ".thumb")
    raw_list = filter(lambda element: not element.startswith('.'), os.listdir(PATH))

    # mp3 and wav files only list
    file_list = filter(lambda element: element.endswith('.mp3') | element.endswith('.wav'), raw_list)

    # natural order sorting
    file_list.sort(key=natural_key, reverse=False)

    track_list = []
    for f in file_list:
        track_list.append(os.path.join(PATH, f))


    TracklistPlayer(track_list)

Google Maps API v3: InfoWindow not sizing correctly

Short answer: set the maxWidth options property in the constructor. Yes, even if setting the maximum width was not what you wanted to do.

Longer story: Migrating a v2 map to v3, I saw exactly the problem described. Windows varied in width and height, and some had vertical scrollbars and some didn't. Some had <br /> embedded in the data, but at least one with that sized OK.

I didn't think the InfoWindowsOptions.maxWidth property was relevant, since I didn't care to constrain the width... but by setting it with the InfoWindow constructor, I got what I wanted, and the windows now autosize (vertically) and show the full content without a vertical scrollbar. Doesn't make a lot of sense to me, but it works!

See: http://fortboise.org/maps/sailing-spots.html

Subtracting 2 lists in Python

If this is something you end up doing frequently, and with different operations, you should probably create a class to handle cases like this, or better use some library like Numpy.

Otherwise, look for list comprehensions used with the zip builtin function:

[a_i - b_i for a_i, b_i in zip(a, b)]

How to compile and run C in sublime text 3?

try to write a shell script named run.sh in your project foler

#!/bin/bash
./YOUR_EXECUTIVE_FILE
...AND OTHER THING

and make a Build System to compile and execute it:

{
      "shell_cmd": "make all && ./run.sh"
}

don't forget $chmod +x run.sh

do one thing and do it well:)

How to remove an HTML element using Javascript?

This works. Just remove the button from the "dummy" div if you want to keep the button.

_x000D_
_x000D_
function removeDummy() {_x000D_
  var elem = document.getElementById('dummy');_x000D_
  elem.parentNode.removeChild(elem);_x000D_
  return false;_x000D_
}
_x000D_
#dummy {_x000D_
  min-width: 200px;_x000D_
  min-height: 200px;_x000D_
  max-width: 200px;_x000D_
  max-height: 200px;_x000D_
  background-color: #fff000;_x000D_
}
_x000D_
<div id="dummy">_x000D_
  <button onclick="removeDummy()">Remove</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

curl: (6) Could not resolve host: google.com; Name or service not known

I have today similar problem. But weirder.

  • host - works host pl.archive.ubuntu.com
  • dig - works on default and on all other DNS's dig pl.archive.ubuntu.com, dig @127.0.1.1 pl.archive.ubuntu.com
  • curl - doesn't work! but for some addresses it does. WEIRD! Same in Ruby, APT and many more.
$ curl -v http://google.com/
*   Trying 172.217.18.78...
* Connected to google.com (172.217.18.78) port 80 (#0)
> GET / HTTP/1.1
> Host: google.com
> User-Agent: curl/7.47.0
> Accept: */*
>
< HTTP/1.1 302 Found
< Cache-Control: private
< Content-Type: text/html; charset=UTF-8
< Referrer-Policy: no-referrer
< Location: http://www.google.pl/?gfe_rd=cr&ei=pt9UWfqXL4uBX_W5n8gB
< Content-Length: 256
< Date: Thu, 29 Jun 2017 11:08:22 GMT
<
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://www.google.pl/?gfe_rd=cr&ei=pt9UWfqXL4uBX_W5n8gB">here</A>.
</BODY></HTML>
* Connection #0 to host google.com left intact

$ curl -v http://pl.archive.ubuntu.com/
* Could not resolve host: pl.archive.ubuntu.com
* Closing connection 0
curl: (6) Could not resolve host: pl.archive.ubuntu.com

Revelation

Eventually I used strace on curl and found that it was connection to nscd deamon.

connect(4, {sa_family=AF_LOCAL, sun_path="/var/run/nscd/socket"}, 110) = 0

Solution

I've restarted the nscd service (Name Service Cache Daemon) and it helped to solve this issue!

systemctl restart nscd.service

YouTube: How to present embed video with sound muted

This is easy. Just add mute=1 to the src parameter of iframe.

Example:

<iframe src="https://www.youtube.com/embed/uNRGWVJ10gQ?controls=0&mute=1&showinfo=0&rel=0&autoplay=1&loop=1&playlist=uNRGWVJ10gQ" frameborder="0" allowfullscreen></iframe>

HTML5 Dynamically create Canvas

Via Jquery:

$('<canvas/>', { id: 'mycanvas', height: 500, width: 200});

http://jsfiddle.net/8DEsJ/736/

disable horizontal scroll on mobile web

try like this

css

*{
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
    -msbox-sizing: border-box;
}
body{
   overflow-x: hidden;
}
img{
   max-width:100%;
}

How to initialize a vector with fixed length in R

?vector

X <- vector(mode="character", length=10)

This will give you empty strings which get printed as two adjacent double quotes, but be aware that there are no double-quote characters in the values themselves. That's just a side-effect of how print.default displays the values. They can be indexed by location. The number of characters will not be restricted, so if you were expecting to get 10 character element you will be disappointed.

>  X[5] <- "character element in 5th position"

>  X
 [1] ""                                  ""                                 
 [3] ""                                  ""                                 
 [5] "character element in 5th position" ""                                 
 [7] ""                                  ""                                 
 [9] ""                                  "" 
>  nchar(X)
 [1]  0  0  0  0 33  0  0  0  0  0

> length(X)
[1] 10

How to resolve symbolic links in a shell script

One of my favorites is realpath foo

realpath - return the canonicalized absolute pathname

realpath  expands  all  symbolic  links  and resolves references to '/./', '/../' and extra '/' characters in the null terminated string named by path and
       stores the canonicalized absolute pathname in the buffer of size PATH_MAX named by resolved_path.  The resulting path will have no symbolic link, '/./' or
       '/../' components.

jQuery .search() to any string

Ah, that would be because RegExp is not jQuery. :)

Try this page. jQuery.attr doesn't return a String so that would certainly cause in this regard. Fortunately I believe you can just use .text() to return the String representation.

Something like:

$("li").val("title").search(/sometext/i));

How to convert string to integer in UNIX

Use this:

#include <stdlib.h>
#include <string.h>

int main()
{
    const char *d1 = "11";
    int d1int = atoi(d1);
    printf("d1 = %d\n", d1);
    return 0;
}

etc.

Find if value in column A contains value from column B?

You could try this

=IF(ISNA(VLOOKUP(<single column I value>,<entire column E range>,1,FALSE)),FALSE, TRUE)

-or-

=IF(ISNA(VLOOKUP(<single column I value>,<entire column E range>,1,FALSE)),"FALSE", "File found in row "   & MATCH(<single column I value>,<entire column E range>,0))

you could replace <single column I value> and <entire column E range> with named ranged. That'd probably be the easiest.

Just drag that formula all the way down the length of your I column in whatever column you want.

type checking in javascript

A number is an integer if its modulo %1 is 0-

function isInt(n){
    return (typeof n== 'number' && n%1== 0);
}

This is only as good as javascript gets- say +- ten to the 15th.

isInt(Math.pow(2,50)+.1) returns true, as does Math.pow(2,50)+.1 == Math.pow(2,50)

Console logging for react?

Here are some more console logging "pro tips":

console.table

var animals = [
    { animal: 'Horse', name: 'Henry', age: 43 },
    { animal: 'Dog', name: 'Fred', age: 13 },
    { animal: 'Cat', name: 'Frodo', age: 18 }
];

console.table(animals);

console.table

console.trace

Shows you the call stack for leading up to the console.

console.trace

You can even customise your consoles to make them stand out

console.todo = function(msg) {
    console.log(‘ % c % s % s % s‘, ‘color: yellow; background - color: black;’, ‘–‘, msg, ‘–‘);
}

console.important = function(msg) {
    console.log(‘ % c % s % s % s’, ‘color: brown; font - weight: bold; text - decoration: underline;’, ‘–‘, msg, ‘–‘);
}

console.todo(“This is something that’ s need to be fixed”);
console.important(‘This is an important message’);

console.todo

If you really want to level up don't limit your self to the console statement.

Here is a great post on how you can integrate a chrome debugger right into your code editor!

https://hackernoon.com/debugging-react-like-a-champ-with-vscode-66281760037

How to make phpstorm display line numbers by default?

Just right click on left side where line numbers generally show, select "show line numbers"

Convert any object to a byte[]

What you're looking for is serialization. There are several forms of serialization available for the .Net platform

VMware Workstation and Device/Credential Guard are not compatible

For those who might be encountering this issue with recent changes to your computer involving Hyper-V, you'll need to disable it while using VMWare or VirtualBox. They don't work together. Windows Sandbox and WSL 2 need the Hyper-V Hypervisor on, which currently breaks VMWare. Basically, you'll need to run the following commands to enable/disable Hyper-V services on next reboot.

To disable Hyper-V and get VMWare working, in PowerShell as Admin:

bcdedit /set hypervisorlaunchtype off

To re-enable Hyper-V and break VMWare for now, in PowerShell as Admin:

bcdedit /set hypervisorlaunchtype auto

You'll need to reboot after that. I've written a PowerShell script that will toggle this for you and confirm it with dialog boxes. It even self-elevates to Administrator using this technique so that you can just right click and run the script to quickly change your Hyper-V mode. It could easily be modified to reboot for you as well, but I personally didn't want that to happen. Save this as hypervisor.ps1 and make sure you've run Set-ExecutionPolicy RemoteSigned so that you can run PowerShell scripts.

# Get the ID and security principal of the current user account
$myWindowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent();
$myWindowsPrincipal = New-Object System.Security.Principal.WindowsPrincipal($myWindowsID);

# Get the security principal for the administrator role
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator;

# Check to see if we are currently running as an administrator
if ($myWindowsPrincipal.IsInRole($adminRole))
{
    # We are running as an administrator, so change the title and background colour to indicate this
    $Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)";
    $Host.UI.RawUI.BackgroundColor = "DarkBlue";
    Clear-Host;
}
else {
    # We are not running as an administrator, so relaunch as administrator

    # Create a new process object that starts PowerShell
    $newProcess = New-Object System.Diagnostics.ProcessStartInfo "PowerShell";

    # Specify the current script path and name as a parameter with added scope and support for scripts with spaces in it's path
    $newProcess.Arguments = "-windowstyle hidden & '" + $script:MyInvocation.MyCommand.Path + "'"

    # Indicate that the process should be elevated
    $newProcess.Verb = "runas";

    # Start the new process
    [System.Diagnostics.Process]::Start($newProcess);

    # Exit from the current, unelevated, process
    Exit;
}

Add-Type -AssemblyName System.Windows.Forms


$state = bcdedit /enum | Select-String -Pattern 'hypervisorlaunchtype\s*(\w+)\s*'


if ($state.matches.groups[1].ToString() -eq "Off"){

    $UserResponse= [System.Windows.Forms.MessageBox]::Show("Enable Hyper-V?" , "Hypervisor" , 4)

    if ($UserResponse -eq "YES" ) 
    {

        bcdedit /set hypervisorlaunchtype auto
        [System.Windows.Forms.MessageBox]::Show("Enabled Hyper-V. Reboot to apply." , "Hypervisor")

    } 

    else 

    { 

        [System.Windows.Forms.MessageBox]::Show("No change was made." , "Hypervisor")
        exit

    }

} else {

    $UserResponse= [System.Windows.Forms.MessageBox]::Show("Disable Hyper-V?" , "Hypervisor" , 4)

    if ($UserResponse -eq "YES" ) 
    {

        bcdedit /set hypervisorlaunchtype off
        [System.Windows.Forms.MessageBox]::Show("Disabled Hyper-V. Reboot to apply." , "Hypervisor")

    } 

    else 

    { 

        [System.Windows.Forms.MessageBox]::Show("No change was made." , "Hypervisor")
        exit

    }

}

css3 text-shadow in IE9

I was looking for a cross-browser text-stroke solution that works when overlaid on background images. think I have a solution for this that doesn't involve extra mark-up, js and works in IE7-9 (I haven't tested 6), and doesn't cause aliasing problems.

This is a combination of using CSS3 text-shadow, which has good support except IE (http://caniuse.com/#search=text-shadow), then using a combination of filters for IE. CSS3 text-stroke support is poor at the moment.

IE Filters

The glow filter (http://www.impressivewebs.com/css3-text-shadow-ie/) looks terrible, so I didn't use that.

David Hewitt's answer involved adding dropshadow filters in a combination of directions. ClearType is then removed unfortunately so we end up with badly aliased text.

I then combined some of the elements suggested on useragentman with the dropshadow filters.

Putting it together

This example would be black text with a white stroke. I'm using conditional html classes by the way to target IE (http://paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/).

#myelement {
    color: #000000;
    text-shadow:
    -1px -1px 0 #ffffff,  
    1px -1px 0 #ffffff,
    -1px 1px 0 #ffffff,
    1px 1px 0 #ffffff;
}

html.ie7 #myelement,
html.ie8 #myelement,
html.ie9 #myelement {
    background-color: white;
    filter: progid:DXImageTransform.Microsoft.Chroma(color='white') progid:DXImageTransform.Microsoft.Alpha(opacity=100) progid:DXImageTransform.Microsoft.dropshadow(color=#ffffff,offX=1,offY=1) progid:DXImageTransform.Microsoft.dropshadow(color=#ffffff,offX=-1,offY=1) progid:DXImageTransform.Microsoft.dropshadow(color=#ffffff,offX=1,offY=-1) progid:DXImageTransform.Microsoft.dropshadow(color=#ffffff,offX=-1,offY=-1);
    zoom: 1;
}

insert multiple rows into DB2 database

I'm assuming you're using DB2 for z/OS, which unfortunately (for whatever reason, I never really understood why) doesn't support using a values-list where a full-select would be appropriate.

You can use a select like below. It's a little unwieldy, but it works:

INSERT INTO tableName (col1, col2, col3, col4, col5) 
SELECT val1, val2, val3, val4, val5 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT val1, val2, val3, val4, val5 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT val1, val2, val3, val4, val5 FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT val1, val2, val3, val4, val5 FROM SYSIBM.SYSDUMMY1

Your statement would work on DB2 for Linux/Unix/Windows (LUW), at least when I tested it on my LUW 9.7.

Differences between unique_ptr and shared_ptr

unique_ptr
is a smart pointer which owns an object exclusively.

shared_ptr
is a smart pointer for shared ownership. It is both copyable and movable. Multiple smart pointer instances can own the same resource. As soon as the last smart pointer owning the resource goes out of scope, the resource will be freed.

What should a JSON service return on failure / error

I don't think you should be returning any http error codes, rather custom exceptions that are useful to the client end of the application so the interface knows what had actually occurred. I wouldn't try and mask real issues with 404 error codes or something to that nature.

Get access to parent control from user control - C#

((frmMain)this.Owner).MyListControl.Items.Add("abc");

Make sure to provide access level you want at Modifiers properties other than Private for MyListControl at frmMain

Sending and Receiving SMS and MMS in Android (pre Kit Kat Android 4.4)

To send an mms for Android 4.0 api 14 or higher without permission to write apn settings, you can use this library: Retrieve mnc and mcc codes from android, then call

Carrier c = Carrier.getCarrier(mcc, mnc);
if (c != null) {
    APN a = c.getAPN();
    if (a != null) {
        String mmsc = a.mmsc;
        String mmsproxy = a.proxy; //"" if none
        int mmsport = a.port; //0 if none
    }
}

To use this, add Jsoup and droid prism jar to the build path, and import com.droidprism.*;

Insert variable into Header Location PHP

There's nothing here explaining the use of multiple variables, so I'll chuck it in just incase someone needs it in the future.

You need to concatenate multiple variables:

header('Location: http://linkhere.com?var1='.$var1.'&var2='.$var2.'&var3'.$var3);

Table column sizing

Updated 2018

Make sure your table includes the table class. This is because Bootstrap 4 tables are "opt-in" so the table class must be intentionally added to the table.

http://codeply.com/go/zJLXypKZxL

Bootstrap 3.x also had some CSS to reset the table cells so that they don't float..

table td[class*=col-], table th[class*=col-] {
    position: static;
    display: table-cell;
    float: none;
}

I don't know why this isn't is Bootstrap 4 alpha, but it may be added back in the final release. Adding this CSS will help all columns to use the widths set in the thead..

Bootstrap 4 Alpha 2 Demo


UPDATE (as of Bootstrap 4.0.0)

Now that Bootstrap 4 is flexbox, the table cells will not assume the correct width when adding col-*. A workaround is to use the d-inline-block class on the table cells to prevent the default display:flex of columns.

Another option in BS4 is to use the sizing utils classes for width...

<thead>
     <tr>
           <th class="w-25">25</th>
           <th class="w-50">50</th>
           <th class="w-25">25</th>
     </tr>
</thead>

Bootstrap 4 Alpha 6 Demo

Lastly, you could use d-flex on the table rows (tr), and the col-* grid classes on the columns (th,td)...

<table class="table table-bordered">
        <thead>
            <tr class="d-flex">
                <th class="col-3">25%</th>
                <th class="col-3">25%</th>
                <th class="col-6">50%</th>
            </tr>
        </thead>
        <tbody>
            <tr class="d-flex">
                <td class="col-sm-3">..</td>
                <td class="col-sm-3">..</td>
                <td class="col-sm-6">..</td>
            </tr>
        </tbody>
    </table>

Bootstrap 4.0.0 (stable) Demo

Note: Changing the TR to display:flex can alter the borders

How to set Linux environment variables with Ansible

For persistently setting environment variables, you can use one of the existing roles over at Ansible Galaxy. I recommend weareinteractive.environment.

Using ansible-galaxy:

$ ansible-galaxy install weareinteractive.environment

Using requirements.yml:

- src: franklinkim.environment

Then in your playbook:

- hosts: all
  sudo: yes
  roles:
    - role: franklinkim.environment
      environment_config:
        NODE_ENV: staging
        DATABASE_NAME: staging

How to center a table of the screen (vertically and horizontally)

For horizontal alignment (No CSS)

Just insert an align attribute inside the table tag

<table align="center"></table

Hex-encoded String to Byte Array

That should do the trick :

byte[] bytes = toByteArray(Str.toCharArray());

public static byte[] toByteArray(char[] array) {
    return toByteArray(array, Charset.defaultCharset());
}

public static byte[] toByteArray(char[] array, Charset charset) {
    CharBuffer cbuf = CharBuffer.wrap(array);
    ByteBuffer bbuf = charset.encode(cbuf);
    return bbuf.array();
}

How get sound input from microphone in python, and process it on the fly?

...and when I got one how to process it (do I need to use Fourier Transform like it was instructed in the above post)?

If you want a "tap" then I think you are interested in amplitude more than frequency. So Fourier transforms probably aren't useful for your particular goal. You probably want to make a running measurement of the short-term (say 10 ms) amplitude of the input, and detect when it suddenly increases by a certain delta. You would need to tune the parameters of:

  • what is the "short-term" amplitude measurement
  • what is the delta increase you look for
  • how quickly the delta change must occur

Although I said you're not interested in frequency, you might want to do some filtering first, to filter out especially low and high frequency components. That might help you avoid some "false positives". You could do that with an FIR or IIR digital filter; Fourier isn't necessary.

Join vs. sub-query

It depends on several factors, including the specific query you're running, the amount of data in your database. Subquery runs the internal queries first and then from the result set again filter out the actual results. Whereas in join runs the and produces the result in one go.

The best strategy is that you should test both the join solution and the subquery solution to get the optimized solution.

Android Studio: Where is the Compiler Error Output Window?

In my case i had a findViewById reference to a view i had deleted in xml

if you are running AS 3.1 and above:

  1. go to Settings > Build, Execution and Deployment > compiler
  2. add --stacktrace to the command line options, click apply and ok
  3. At the bottom of AS click on Console/Build(If you use the stable version 3.1.2 and above) expand the panel and run your app again.

you should see the full stacktrace in the expanded view and the specific error.

History or log of commands executed in Git

A log of your commands may be available in your shell history.

history

If seeing the list of executed commands fly by isn't for you, export the list into a file.

history > path/to/file

You can restrict the exported dump to only show commands with "git" in them by piping it with grep

history | grep "git " > path/to/file

The history may contain lines formatted as such

518  git status -s
519  git commit -am "injects sriracha to all toppings, as required"

Using the number you can re-execute the command with an exclamation mark

$ !518
git status -s

How to get UTF-8 working in Java webapps?

Nice detailed answer. just wanted to add one more thing which will definitely help others to see the UTF-8 encoding on URLs in action .

Follow the steps below to enable UTF-8 encoding on URLs in firefox.

  1. type "about:config" in the address bar.

  2. Use the filter input type to search for "network.standard-url.encode-query-utf8" property.

  3. the above property will be false by default, turn that to TRUE.
  4. restart the browser.

UTF-8 encoding on URLs works by default in IE6/7/8 and chrome.

Set value to currency in <input type="number" />

The browser only allows numerical inputs when the type is set to "number". Details here.

You can use the type="text" and filter out any other than numerical input using JavaScript like descripted here

Is there any JSON Web Token (JWT) example in C#?

Here is the list of classes and functions:

open System
open System.Collections.Generic
open System.Linq
open System.Threading.Tasks
open Microsoft.AspNetCore.Mvc
open Microsoft.Extensions.Logging
open Microsoft.AspNetCore.Authorization
open Microsoft.AspNetCore.Authentication
open Microsoft.AspNetCore.Authentication.JwtBearer
open Microsoft.IdentityModel.Tokens
open System.IdentityModel.Tokens
open System.IdentityModel.Tokens.Jwt
open Microsoft.IdentityModel.JsonWebTokens
open System.Text
open Newtonsoft.Json
open System.Security.Claims
    let theKey = "VerySecretKeyVerySecretKeyVerySecretKey"
    let securityKey = SymmetricSecurityKey(Encoding.UTF8.GetBytes(theKey))
    let credentials = SigningCredentials(securityKey, SecurityAlgorithms.RsaSsaPssSha256)
    let expires = DateTime.UtcNow.AddMinutes(123.0) |> Nullable
    let token = JwtSecurityToken(
                    "lahoda-pro-issuer", 
                    "lahoda-pro-audience",
                    claims = null,
                    expires =  expires,
                    signingCredentials = credentials
        )

    let tokenString = JwtSecurityTokenHandler().WriteToken(token)

Append an array to another array in JavaScript

If you want to modify the original array instead of returning a new array, use .push()...

array1.push.apply(array1, array2);
array1.push.apply(array1, array3);

I used .apply to push the individual members of arrays 2 and 3 at once.

or...

array1.push.apply(array1, array2.concat(array3));

To deal with large arrays, you can do this in batches.

for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
    array1.push.apply(array1, to_add.slice(n, n+300));
}

If you do this a lot, create a method or function to handle it.

var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);

Object.defineProperty(Array.prototype, "pushArrayMembers", {
    value: function() {
        for (var i = 0; i < arguments.length; i++) {
            var to_add = arguments[i];
            for (var n = 0; n < to_add.length; n+=300) {
                push_apply(this, slice_call(to_add, n, n+300));
            }
        }
    }
});

and use it like this:

array1.pushArrayMembers(array2, array3);

_x000D_
_x000D_
var push_apply = Function.apply.bind([].push);_x000D_
var slice_call = Function.call.bind([].slice);_x000D_
_x000D_
Object.defineProperty(Array.prototype, "pushArrayMembers", {_x000D_
    value: function() {_x000D_
        for (var i = 0; i < arguments.length; i++) {_x000D_
            var to_add = arguments[i];_x000D_
            for (var n = 0; n < to_add.length; n+=300) {_x000D_
                push_apply(this, slice_call(to_add, n, n+300));_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
});_x000D_
_x000D_
var array1 = ['a','b','c'];_x000D_
var array2 = ['d','e','f'];_x000D_
var array3 = ['g','h','i'];_x000D_
_x000D_
array1.pushArrayMembers(array2, array3);_x000D_
_x000D_
document.body.textContent = JSON.stringify(array1, null, 4);
_x000D_
_x000D_
_x000D_

What's the difference between SortedList and SortedDictionary?

Yes - their performance characteristics differ significantly. It would probably be better to call them SortedList and SortedTree as that reflects the implementation more closely.

Look at the MSDN docs for each of them (SortedList, SortedDictionary) for details of the performance for different operations in different situtations. Here's a nice summary (from the SortedDictionary docs):

The SortedDictionary<TKey, TValue> generic class is a binary search tree with O(log n) retrieval, where n is the number of elements in the dictionary. In this, it is similar to the SortedList<TKey, TValue> generic class. The two classes have similar object models, and both have O(log n) retrieval. Where the two classes differ is in memory use and speed of insertion and removal:

  • SortedList<TKey, TValue> uses less memory than SortedDictionary<TKey, TValue>.

  • SortedDictionary<TKey, TValue> has faster insertion and removal operations for unsorted data, O(log n) as opposed to O(n) for SortedList<TKey, TValue>.

  • If the list is populated all at once from sorted data, SortedList<TKey, TValue> is faster than SortedDictionary<TKey, TValue>.

(SortedList actually maintains a sorted array, rather than using a tree. It still uses binary search to find elements.)

Find the min/max element of an array in JavaScript

If you need performance then this is the best way for small arrays:

var min = 99999;
var max = 0;
for(var i = 0; i < v.length; i++)
{
    if(v[i] < min)
    {
        min = v[i];
    }
    if(v[i] >= max)
    {
        max = v[i];
    }
}

Overriding the java equals() method - not working?

the instanceOf statement is often used in implementation of equals.

This is a popular pitfall !

The problem is that using instanceOf violates the rule of symmetry:

(object1.equals(object2) == true) if and only if (object2.equals(object1))

if the first equals is true, and object2 is an instance of a subclass of the class where obj1 belongs to, then the second equals will return false!

if the regarded class where ob1 belongs to is declared as final, then this problem can not arise, but in general, you should test as follows:

this.getClass() != otherObject.getClass(); if not, return false, otherwise test the fields to compare for equality!

Find the division remainder of a number

From Python 3.7, there is a new math.remainder() function:

from math import remainder
print(remainder(26,7))

Output:

-2.0  # not 5

Note, as above, it's not the same as %.

Quoting the documentation:

math.remainder(x, y)

Return the IEEE 754-style remainder of x with respect to y. For finite x and finite nonzero y, this is the difference x - n*y, where n is the closest integer to the exact value of the quotient x / y. If x / y is exactly halfway between two consecutive integers, the nearest even integer is used for n. The remainder r = remainder(x, y) thus always satisfies abs(r) <= 0.5 * abs(y).

Special cases follow IEEE 754: in particular, remainder(x, math.inf) is x for any finite x, and remainder(x, 0) and remainder(math.inf, x) raise ValueError for any non-NaN x. If the result of the remainder operation is zero, that zero will have the same sign as x.

On platforms using IEEE 754 binary floating-point, the result of this operation is always exactly representable: no rounding error is introduced.

Issue29962 describes the rationale for creating the new function.

WebDriver: check if an element exists?

I agree with Mike's answer but there's an implicit 3 second wait if no elements are found which can be switched on/off which is useful if you're performing this action a lot:

driver.manage().timeouts().implicitlyWait(0, TimeUnit.MILLISECONDS);
boolean exists = driver.findElements( By.id("...") ).size() != 0
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);

Putting that into a utility method should improve performance if you're running a lot of tests

What is the difference between Java RMI and RPC?

The only real difference between RPC and RMI is that there is objects involved in RMI: instead of invoking functions through a proxy function, we invoke methods through a proxy.

Merge or combine by rownames

you can wrap -Andrie answer into a generic function

mbind<-function(...){
 Reduce( function(x,y){cbind(x,y[match(row.names(x),row.names(y)),])}, list(...) )
}

Here, you can bind multiple frames with rownames as key

What is the difference between URL parameters and query strings?

The query component is indicated by the first ? in a URI. "Query string" might be a synonym (this term is not used in the URI standard).

Some examples for HTTP URIs with query components:

http://example.com/foo?bar
http://example.com/foo/foo/foo?bar/bar/bar
http://example.com/?bar
http://example.com/?@bar._=???/1:
http://example.com/?bar1=a&bar2=b

(list of allowed characters in the query component)

The "format" of the query component is up to the URI authors. A common convention (but nothing more than a convention, as far as the URI standard is concerned¹) is to use the query component for key-value pairs, aka. parameters, like in the last example above: bar1=a&bar2=b.

Such parameters could also appear in the other URI components, i.e., the path² and the fragment. As far as the URI standard is concerned, it’s up to you which component and which format to use.

Example URI with parameters in the path, the query, and the fragment:

http://example.com/foo;key1=value1?key2=value2#key3=value3

¹ The URI standard says about the query component:

[…] query components are often used to carry identifying information in the form of "key=value" pairs […]

² The URI standard says about the path component:

[…] the semicolon (";") and equals ("=") reserved characters are often used to delimit parameters and parameter values applicable to that segment. The comma (",") reserved character is often used for similar purposes.

exit application when click button - iOS

exit(X), where X is a number (according to the doc) should work. But it is not recommended by Apple and won't be accepted by the AppStore. Why? Because of these guidelines (one of my app got rejected):

We found that your app includes a UI control for quitting the app. This is not in compliance with the iOS Human Interface Guidelines, as required by the App Store Review Guidelines.

Please refer to the attached screenshot/s for reference.

The iOS Human Interface Guidelines specify,

"Always Be Prepared to Stop iOS applications stop when people press the Home button to open a different application or use a device feature, such as the phone. In particular, people don’t tap an application close button or select Quit from a menu. To provide a good stopping experience, an iOS application should:

Save user data as soon as possible and as often as reasonable because an exit or terminate notification can arrive at any time.

Save the current state when stopping, at the finest level of detail possible so that people don’t lose their context when they start the application again. For example, if your app displays scrolling data, save the current scroll position."

> It would be appropriate to remove any mechanisms for quitting your app.

Plus, if you try to hide that function, it would be understood by the user as a crash.

Android offline documentation and sample codes

here is direct link for api 17 documentation. Just extract at under docs folder. Hope it helps.

https://dl-ssl.google.com/android/repository/docs-17_r02.zip   (129 MB)

Implicit type conversion rules in C++ operators

If you exclude the unsigned types, there is an ordered hierarchy: signed char, short, int, long, long long, float, double, long double. First, anything coming before int in the above will be converted to int. Then, in a binary operation, the lower ranked type will be converted to the higher, and the results will be the type of the higher. (You'll note that, from the hierarchy, anytime a floating point and an integral type are involved, the integral type will be converted to the floating point type.)

Unsigned complicates things a bit: it perturbs the ranking, and parts of the ranking become implementation defined. Because of this, it's best to not mix signed and unsigned in the same expression. (Most C++ experts seem to avoid unsigned unless bitwise operations are involved. That is, at least, what Stroustrup recommends.)

Add border-bottom to table row <tr>

Another solution to this is border-spacing property:

_x000D_
_x000D_
table td {_x000D_
  border-bottom: 2px solid black;_x000D_
}_x000D_
_x000D_
table {_x000D_
  border-spacing: 0px;_x000D_
}
_x000D_
<table>_x000D_
 <tr>_x000D_
   <td>ABC</td>_x000D_
   <td>XYZ</td>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to refresh a page with jQuery by passing a parameter to URL

You can use Javascript URLSearchParams.

var url = new URL(window.location.href);
url.searchParams.set('single','');
window.location.href = url.href;

[UPDATE]: If IE support is a need, check this thread:

SCRIPT5009: 'URLSearchParams' is undefined in IE 11

Thanks @john-m to talk about the IE support

Setting Action Bar title and subtitle

You can do something like this to code for both versions:

/**
 * Sets the Action Bar for new Android versions.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void actionBarSetup() {
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    ActionBar ab = getActionBar();
    ab.setTitle("My Title");
    ab.setSubtitle("sub-title"); 
  }
}

Then call actionBarSetup() in onCreate(). The if runs the code only on new Android versions and the @TargetApi allows the code to compile. Therefore it makes it safe for both old and new API versions.

Alternatively, you can also use ActionBarSherlock (see edit) so you can have the ActionBar on all versions. You will have to do some changes such as making your Activities extend SherlockActivity and calling getSupportActionBar(), however, it is a very good global solution.

Edit

Note that when this answer was originally written, ActionBarSherlock, which has since been deprecated, was the go-to compatibility solution.

Nowadays, Google's appcompat-v7 library provides the same functionality but is supported (and actively updated) by Google. Activities wanting to implement an ActionBar must:

  • extend AppCompatActivity
  • use a Theme.AppCompat derivative

To get an ActionBar instance using this library, the aptly-named getSupportActionBar() method is used.

Nested iframes, AKA Iframe Inception

Thing is, the code you provided won't work because the <iframe> element has to have a "src" property, like:

<iframe id="uploads" src="http://domain/page.html"></iframe>

It's ok to use .contents() to get the content:

$('#uploads).contents() will give you access to the second iframe, but if that iframe is "INSIDE" the http://domain/page.html document the #uploads iframe loaded.

To test I'm right about this, I created 3 html files named main.html, iframe.html and noframe.html and then selected the div#element just fine with:

$('#uploads').contents().find('iframe').contents().find('#element');

There WILL be a delay in which the element will not be available since you need to wait for the iframe to load the resource. Also, all iframes have to be on the same domain.

Hope this helps ...

Here goes the html for the 3 files I used (replace the "src" attributes with your domain and url):

main.html

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>main.html example</title>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

    <script>
        $(function () {
            console.log( $('#uploads').contents().find('iframe').contents().find('#element') ); // nothing at first

            setTimeout( function () {
                console.log( $('#uploads').contents().find('iframe').contents().find('#element') ); // wait and you'll have it
            }, 2000 );

        });
    </script>
</head>
<body>
    <iframe id="uploads" src="http://192.168.1.70/test/iframe.html"></iframe>
</body>

iframe.html

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>iframe.html example</title>
</head>
<body>
    <iframe src="http://192.168.1.70/test/noframe.html"></iframe>
</body>

noframe.html

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>noframe.html example</title>
</head>
<body>
    <div id="element">some content</div>
</body>

Adding Jar files to IntellijIdea classpath

On the Mac version I was getting the error when trying to run JSON-Clojure.json.clj, which is the script to export a database table to JSON. To get it to work I had to download the latest Clojure JAR from http://clojure.org/ and then right-click on PHPStorm app in the Finder and "Show Package Contents". Then go to Contents in there. Then open the lib folder, and see a bunch of .jar files. Copy the clojure-1.8.0.jar file from the unzipped archive I downloaded from clojure.org into the aforementioned lib folder inside the PHPStorm.app/Contents/lib. Restart the app. Now it freaking works.

EDIT: You also have to put the JSR-223 script engine into PHPStorm.app/Contents/lib. It can be built from https://github.com/ato/clojure-jsr223 or downloaded from https://www.dropbox.com/s/jg7s0c41t5ceu7o/clojure-jsr223-1.5.1.jar?dl=0 .

How to recognize swipe in all 4 directions

In Swift 4.2 and Xcode 9.4.1

Add Animation delegate, CAAnimationDelegate to your class

//Swipe gesture for left and right
let swipeFromRight = UISwipeGestureRecognizer(target: self, action: #selector(didSwipeLeft))
swipeFromRight.direction = UISwipeGestureRecognizerDirection.left
menuTransparentView.addGestureRecognizer(swipeFromRight)

let swipeFromLeft = UISwipeGestureRecognizer(target: self, action: #selector(didSwipeRight))
swipeFromLeft.direction = UISwipeGestureRecognizerDirection.right
menuTransparentView.addGestureRecognizer(swipeFromLeft)

//Swipe gesture selector function
@objc func didSwipeLeft(gesture: UIGestureRecognizer) {
    //We can add some animation also
    DispatchQueue.main.async(execute: {
            let animation = CATransition()
            animation.type = kCATransitionReveal
            animation.subtype = kCATransitionFromRight
            animation.duration = 0.5
            animation.delegate = self
            animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
            //Add this animation to your view
            self.transparentView.layer.add(animation, forKey: nil)
            self.transparentView.removeFromSuperview()//Remove or hide your view if requirement.
        })
}

//Swipe gesture selector function
@objc func didSwipeRight(gesture: UIGestureRecognizer) {
        // Add animation here
        DispatchQueue.main.async(execute: {
            let animation = CATransition()
            animation.type = kCATransitionReveal
            animation.subtype = kCATransitionFromLeft
            animation.duration = 0.5
            animation.delegate = self
            animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
            //Add this animation to your view
            self.transparentView.layer.add(animation, forKey: nil)
            self.transparentView.removeFromSuperview()//Remove or hide yourview if requirement.
        })
}

If you want to remove gesture from view use this code

self.transparentView.removeGestureRecognizer(gesture)

Ex:

func willMoveFromView(view: UIView) {
    if view.gestureRecognizers != nil {
        for gesture in view.gestureRecognizers! {
            //view.removeGestureRecognizer(gesture)//This will remove all gestures including tap etc...
            if let recognizer = gesture as? UISwipeGestureRecognizer {
                //view.removeGestureRecognizer(recognizer)//This will remove all swipe gestures
                if recognizer.direction == .left {//Especially for left swipe
                    view.removeGestureRecognizer(recognizer)
                }
            }
        }
    }
}

Call this function like

//Remove swipe gesture
self.willMoveFromView(view: self.transparentView)

Like this you can write remaining directions and please careful whether if you have scroll view or not from bottom to top and vice versa

If you have scroll view, you will get conflict for Top to bottom and view versa gestures.

click or change event on radio using jquery

Try

$(document).ready(

instead of

$('document').ready(

or you can use a shorthand form

$(function(){
});

Unable to find the requested .Net Framework Data Provider in Visual Studio 2010 Professional

its solved. Use nuget and search for the "ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client".

and install the package. it will resolve the issue for me.

What is getattr() exactly and how do I use it?

# getattr

class hithere():

    def french(self):
        print 'bonjour'

    def english(self):
        print 'hello'

    def german(self):
        print 'hallo'

    def czech(self):
        print 'ahoj'

    def noidea(self):
        print 'unknown language'


def dispatch(language):
    try:
        getattr(hithere(),language)()
    except:
        getattr(hithere(),'noidea')()
        # note, do better error handling than this

dispatch('french')
dispatch('english')
dispatch('german')
dispatch('czech')
dispatch('spanish')

Replace only text inside a div using jquery

Text shouldn't be on its own. Put it into a span element.

Change it to this:

<div id="one">
       <div class="first"></div>
       <span>"Hi I am text"</span>
       <div class="second"></div>
       <div class="third"></div>
</div>
$('#one span').text('Hi I am replace');

How to download a file using a Java REST service and a data stream

Refer this:

@RequestMapping(value="download", method=RequestMethod.GET)
public void getDownload(HttpServletResponse response) {

// Get your file stream from wherever.
InputStream myStream = someClass.returnFile();

// Set the content type and attachment header.
response.addHeader("Content-disposition", "attachment;filename=myfilename.txt");
response.setContentType("txt/plain");

// Copy the stream to the response's output stream.
IOUtils.copy(myStream, response.getOutputStream());
response.flushBuffer();
}

Details at: https://twilblog.github.io/java/spring/rest/file/stream/2015/08/14/return-a-file-stream-from-spring-rest.html

Java - Relative path of a file in a java web application

Do you really need to load it from a file? If you place it along your classes (in WEB-INF/classes) you can get an InputStream to it using the class loader:

InputStream csv = 
   SomeClassInTheSamePackage.class.getResourceAsStream("filename.csv");

Format an Integer using Java String Format

If you are using a third party library called apache commons-lang, the following solution can be useful:

Use StringUtils class of apache commons-lang :

int i = 5;
StringUtils.leftPad(String.valueOf(i), 3, "0"); // --> "005"

As StringUtils.leftPad() is faster than String.format()

"Unable to acquire application service" error while launching Eclipse

I received this message trying to run STS 3.7.0 on java 6 jdk, after pointing to java jdk 7 (-vm param in STS.ini) the issue disappeared.

getting the last item in a javascript object

Map object in JavaScript . This is already about 3 years old now. This map data structure retains the order in which items are inserted. With this retrieving last item will actually result in latest item inserted in the Map

How do I make Git use the editor of my choice for commits?

Mvim as your git editor

Like all the other GUI applications, you have to launch mvim with the wait flag.

git config --global core.editor "mvim --remote-wait"

How do you easily horizontally center a <div> using CSS?

You should use position: relative and text-align: center on the parent element and then display: inline-block on the child element you want to center. This is a simple CSS design pattern that will work across all major browsers. Here is an example below or check out the CodePen Example.

_x000D_
_x000D_
p {_x000D_
  text-align: left;_x000D_
}_x000D_
.container {_x000D_
  position: relative;_x000D_
  display: block;_x000D_
  text-align: center;_x000D_
}_x000D_
/* Style your object */_x000D_
_x000D_
.object {_x000D_
  padding: 10px;_x000D_
  color: #ffffff;_x000D_
  background-color: #556270;_x000D_
}_x000D_
.centerthis {_x000D_
  display: inline-block;_x000D_
}
_x000D_
<div class="container">_x000D_
_x000D_
  <p>Aeroplanigera Mi Psychopathologia Subdistinctio Chirographum Intuor Sons Superbiloquentia Os Sors Sesquiseptimus Municipatio Archipresbyteratus O Conclusio Compedagogius An Maius Septentrionarius Plas Inproportionabilit Constantinopolis Particularisticus.</p>_x000D_
_x000D_
  <span class="object centerthis">Something Centered</span>_x000D_
_x000D_
  <p>Aeroplanigera Mi Psychopathologia Subdistinctio Chirographum Intuor Sons Superbiloquentia Os Sors Sesquiseptimus Municipatio Archipresbyteratus O Conclusio Compedagogius.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to capture a backspace on the onkeydown event

event.key === "Backspace" or "Delete"

More recent and much cleaner: use event.key. No more arbitrary number codes!

input.addEventListener('keydown', function(event) {
    const key = event.key; // const {key} = event; ES6+
    if (key === "Backspace" || key === "Delete") {
        return false;
    }
});

Mozilla Docs

Supported Browsers

how to save DOMPDF generated content to file?

<?php
$content='<table width="100%" border="1">';
$content.='<tr><th>name</th><th>email</th><th>contact</th><th>address</th><th>city</th><th>country</th><th>postcode</th></tr>';
for ($index = 0; $index < 10; $index++) { 
$content.='<tr><td>nadim</td><td>[email protected]</td><td>7737033665</td><td>247 dehligate</td><td>udaipur</td><td>india</td><td>313001</td></tr>';
}
$content.='</table>';
//$html = file_get_contents('pdf.php');
if(isset($_POST['pdf'])){
    require_once('./dompdf/dompdf_config.inc.php');
    $dompdf = new DOMPDF;                        
    $dompdf->load_html($content);
    $dompdf->render();
    $dompdf->stream("hello.pdf");
}
?>
<html>
    <body>
        <form action="#" method="post">        
            <button name="pdf" type="submit">export</button>
        <table width="100%" border="1">
           <tr><th>name</th><th>email</th><th>contact</th><th>address</th><th>city</th><th>country</th><th>postcode</th></tr>         
            <?php for ($index = 0; $index < 10; $index++) { ?>
            <tr><td>nadim</td><td>[email protected]</td><td>7737033665</td><td>247 dehligate</td><td>udaipur</td><td>india</td><td>313001</td></tr>
            <?php } ?>            
        </table>        
        </form>        
    </body>
</html>

Copy entire directory contents to another directory?

With Groovy, you can leverage Ant to do:

new AntBuilder().copy( todir:'/path/to/destination/folder' ) {
  fileset( dir:'/path/to/src/folder' )
}

AntBuilder is part of the distribution and the automatic imports list which means it is directly available for any groovy code.

How to get complete month name from DateTime

If you want the current month you can use DateTime.Now.ToString("MMMM") to get the full month or DateTime.Now.ToString("MMM") to get an abbreviated month.

If you have some other date that you want to get the month string for, after it is loaded into a DateTime object, you can use the same functions off of that object:
dt.ToString("MMMM") to get the full month or dt.ToString("MMM") to get an abbreviated month.

Reference: Custom Date and Time Format Strings

Alternatively, if you need culture specific month names, then you could try these: DateTimeFormatInfo.GetAbbreviatedMonthName Method
DateTimeFormatInfo.GetMonthName Method

Are there any HTTP/HTTPS interception tools like Fiddler for mac OS X?

If you don't get any direct answer to this you could always run Fiddler on a windows machine and configure your browser on the Mac to use the windows machine as a proxy server. Not very satisfactory and requires a second machine (although it could be virtual).

What is the difference between Left, Right, Outer and Inner Joins?

Check out Join (SQL) on Wikipedia

  • Inner join - Given two tables an inner join returns all rows that exist in both tables
  • left / right (outer) join - Given two tables returns all rows that exist in either the left or right table of your join, plus the rows from the other side will be returned when the join clause is a match or null will be returned for those columns

  • Full Outer - Given two tables returns all rows, and will return nulls when either the left or right column is not there

  • Cross Joins - Cartesian join and can be dangerous if not used carefully

TSQL select into Temp table from dynamic sql

How I did it with a pivot in dynamic sql (#AccPurch was created prior to this)

DECLARE @sql AS nvarchar(MAX)
declare @Month Nvarchar(1000)

--DROP TABLE #temp
select distinct YYYYMM into #temp from #AccPurch AS ap
SELECT  @Month = COALESCE(@Month, '') + '[' + CAST(YYYYMM AS VarChar(8)) + '],' FROM    #temp

SELECT   @Month= LEFT(@Month,len(@Month)-1)


SET @sql = N'SELECT UserID, '+ @Month + N' into ##final_Donovan_12345 FROM (
Select ap.AccPurch ,
       ap.YYYYMM ,
       ap.UserID ,
       ap.AccountNumber
FROM #AccPurch AS ap 
) p
Pivot (SUM(AccPurch) FOR YYYYMM IN ('+@Month+ N')) as pvt'


EXEC sp_executesql @sql

Select * INTO #final From ##final_Donovan_12345

DROP TABLE  ##final_Donovan_12345

Select * From #final AS f

chai test array equality doesn't work as expected

For expect, .equal will compare objects rather than their data, and in your case it is two different arrays.

Use .eql in order to deeply compare values. Check out this link.
Or you could use .deep.equal in order to simulate same as .eql.
Or in your case you might want to check .members.

For asserts you can use .deepEqual, link.

Adding VirtualHost fails: Access Forbidden Error 403 (XAMPP) (Windows 7)

I'm using XAMPP 1.6.7 on Windows 7. This article worked for me.

I added the following lines in the file httpd-vhosts.conf at C:/xampp/apache/conf/extra.
I had also uncommented the line # NameVirtualHost *:80

<VirtualHost mysite.dev:80>
    DocumentRoot "C:/xampp/htdocs/mysite"
    ServerName mysite.dev
    ServerAlias mysite.dev
    <Directory "C:/xampp/htdocs/mysite">
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

After restarting the apache, it were still not working. Then I had to follow the step 9 mentioned in the article by editing the file C:/Windows/System32/drivers/etc/hosts.

# localhost name resolution is handled within DNS itself.
     127.0.0.1       localhost
     ::1             localhost
     127.0.0.1       mysite.dev  

Then I got working http://mysite.dev

How can I reverse a NSArray in Objective-C?

There is a much easier solution, if you take advantage of the built-in reverseObjectEnumerator method on NSArray, and the allObjects method of NSEnumerator:

NSArray* reversedArray = [[startArray reverseObjectEnumerator] allObjects];

allObjects is documented as returning an array with the objects that have not yet been traversed with nextObject, in order:

This array contains all the remaining objects of the enumerator in enumerated order.

python: [Errno 10054] An existing connection was forcibly closed by the remote host

I know this is a very old question but it may be that you need to set the request headers. This solved it for me.

For example 'user-agent', 'accept' etc. here is an example with user-agent:

url = 'your-url-here'
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36'}
r = requests.get(url, headers=headers)

How to make pylab.savefig() save image for 'maximized' window instead of default size

There are two major options in matplotlib (pylab) to control the image size:

  1. You can set the size of the resulting image in inches
  2. You can define the DPI (dots per inch) for output file (basically, it is a resolution)

Normally, you would like to do both, because this way you will have full control over the resulting image size in pixels. For example, if you want to render exactly 800x600 image, you can use DPI=100, and set the size as 8 x 6 in inches:

import matplotlib.pyplot as plt
# plot whatever you need...
# now, before saving to file:
figure = plt.gcf() # get current figure
figure.set_size_inches(8, 6)
# when saving, specify the DPI
plt.savefig("myplot.png", dpi = 100)

One can use any DPI. In fact, you might want to play with various DPI and size values to get the result you like the most. Beware, however, that using very small DPI is not a good idea, because matplotlib may not find a good font to render legend and other text. For example, you cannot set the DPI=1, because there are no fonts with characters rendered with 1 pixel :)

From other comments I understood that other issue you have is proper text rendering. For this, you can also change the font size. For example, you may use 6 pixels per character, instead of 12 pixels per character used by default (effectively, making all text twice smaller).

import matplotlib
#...
matplotlib.rc('font', size=6)

Finally, some references to the original documentation: http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.savefig, http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.gcf, http://matplotlib.sourceforge.net/api/figure_api.html#matplotlib.figure.Figure.set_size_inches, http://matplotlib.sourceforge.net/users/customizing.html#dynamic-rc-settings

P.S. Sorry, I didn't use pylab, but as far as I'm aware, all the code above will work same way in pylab - just replace plt in my code with the pylab (or whatever name you assigned when importing pylab). Same for matplotlib - use pylab instead.

How do I get the absolute directory of a file in bash?

$cat abs.sh
#!/bin/bash
echo "$(cd "$(dirname "$1")"; pwd -P)"

Some explanations:

  1. This script get relative path as argument "$1"
  2. Then we get dirname part of that path (you can pass either dir or file to this script): dirname "$1"
  3. Then we cd "$(dirname "$1"); into this relative dir
  4. pwd -P and get absolute path. The -P option will avoid symlinks
  5. As final step we echo it

Then run your script:

abs.sh your_file.txt

How do you clear the console screen in C?

#include <conio.h>

and use

clrscr()

Why can't static methods be abstract in Java?

because if you are using any static member or static variable in class it will load at class loading time.

How could I create a list in c++?

I take it that you know that C++ already has a linked list class, and you want to implement your own because you want to learn how to do it.

First, read Why do we use arrays instead of other data structures? , which contains a good answer of basic data-structures. Then think about how to model them in C++:

struct Node {
    int data;
    Node * next;
};

Basically that's all you need to implement a list! (a very simple one). Yet it has no abstractions, you have to link the items per hand:

Node a={1}, b={20, &a}, c={35, &b} d={42, &c};

Now, you have have a linked list of nodes, all allocated on the stack:

d -> c -> b -> a
42   35   20   1

Next step is to write a wrapper class List that points to the start node, and allows to add nodes as needed, keeping track of the head of the list (the following is very simplified):

class List {
    struct Node {
        int data;
        Node * next;
    };

    Node * head;

public:
    List() {
        head = NULL;
    }

    ~List() {
        while(head != NULL) {
            Node * n = head->next;
            delete head;
            head = n;
        }
    }

    void add(int value) {
        Node * n = new Node;
        n->data = value;
        n->next = head;
        head = n;
    }

    // ...
};

Next step is to make the List a template, so that you can stuff other values (not only integers).

If you are familiar with smart pointers, you can then replace the raw pointers used with smart pointers. Often i find people recommend smart pointers to starters. But in my opinion you should first understand why you need smart pointers, and then use them. But that requires that you need first understand raw pointers. Otherwise, you use some magic tool, without knowing why you need it.

go to link on button click - jquery

Why not just change the second line to

document.location.href="www.example.com/index.php?id=" + $(this).attr('id');

Generate Java class from JSON?

As far as I know there is no such tool. Yet.

The main reason is, I suspect, that unlike with XML (which has XML Schema, and then tools like 'xjc' to do what you ask, between XML and POJO definitions), there is no fully features schema language. There is JSON Schema, but it has very little support for actual type definitions (focuses on JSON structures), so it would be tricky to generate Java classes. But probably still possible, esp. if some naming conventions were defined and used to support generation.

However: this is something that has been fairly frequently requested (on mailing lists of JSON tool projects I follow), so I think that someone will write such a tool in near future.

So I don't think it is a bad idea per se (also: it is not a good idea for all use cases, depends on what you want to do ).

Responsive Images with CSS

the best way i found was to set the image you want to view responsively as a background image and sent a css property for the div as cover.

background-image : url('YOUR URL');
background-size : cover

how to get param in method post spring mvc?

When I want to get all the POST params I am using the code below,

@RequestMapping(value = "/", method = RequestMethod.POST)
public ViewForResponseClass update(@RequestBody AClass anObject) {
    // Source..
}

I am using the @RequestBody annotation for post/put/delete http requests instead of the @RequestParam which reads the GET parameters.

Can I define a class name on paragraph using Markdown?

As mentioned above markdown itself leaves you hanging on this. However, depending on the implementation there are some workarounds:

At least one version of MD considers <div> to be a block level tag but <DIV> is just text. All broswers however are case insensitive. This allows you to keep the syntax simplicity of MD, at the cost of adding div container tags.

So the following is a workaround:

<DIV class=foo>

  Paragraphs here inherit class foo from above.

</div>

The downside of this is that the output code has <p> tags wrapping the <div> lines (both of them, the first because it's not and the second because it doesn't match. No browser fusses about this that I've found, but the code won't validate. MD tends to put in spare <p> tags anyway.

Several versions of markdown implement the convention <tag markdown="1"> in which case MD will do the normal processing inside the tag. The above example becomes:

<div markdown="1" class=foo>

  Paragraphs here inherit class foo from above.

</div>

The current version of Fletcher's MultiMarkdown allows attributes to follow the link if using referenced links.

Force re-download of release dependency using Maven

Most answers provided above would solve the problem.

But if you use IntelliJ and want it to just fix it for you automatically, go to Maven Settings.

Build,Execution, Deployment -> Build Tools -> Maven

enter image description here

Disable Work Offline

Enable Always update snapshots (Switch when required)

How to list records with date from the last 10 days?

you can use between too:

SELECT Table.date
  FROM Table 
  WHERE date between current_date and current_date - interval '10 day';

How can I count the number of matches for a regex?

matcher.find() does not find all matches, only the next match.

Solution for Java 9+

long matches = matcher.results().count();

Solution for Java 8 and older

You'll have to do the following. (Starting from Java 9, there is a nicer solution)

int count = 0;
while (matcher.find())
    count++;

Btw, matcher.groupCount() is something completely different.

Complete example:

import java.util.regex.*;

class Test {
    public static void main(String[] args) {
        String hello = "HelloxxxHelloxxxHello";
        Pattern pattern = Pattern.compile("Hello");
        Matcher matcher = pattern.matcher(hello);

        int count = 0;
        while (matcher.find())
            count++;

        System.out.println(count);    // prints 3
    }
}

Handling overlapping matches

When counting matches of aa in aaaa the above snippet will give you 2.

aaaa
aa
  aa

To get 3 matches, i.e. this behavior:

aaaa
aa
 aa
  aa

You have to search for a match at index <start of last match> + 1 as follows:

String hello = "aaaa";
Pattern pattern = Pattern.compile("aa");
Matcher matcher = pattern.matcher(hello);

int count = 0;
int i = 0;
while (matcher.find(i)) {
    count++;
    i = matcher.start() + 1;
}

System.out.println(count);    // prints 3

Get HTML source of WebElement in Selenium WebDriver using Python

The other answers provide a lot of details about retrieving the markup of a WebElement. However, an important aspect is, modern websites are increasingly implementing JavaScript, ReactJS, jQuery, Ajax, Vue.js, Ember.js, GWT, etc. to render the dynamic elements within the DOM tree. Hence there is a necessity to wait for the element and its children to completely render before retrieving the markup.


Python

Hence, ideally you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • Using get_attribute("outerHTML"):

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#my-id")))
    print(element.get_attribute("outerHTML"))
    
  • Using execute_script():

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#my-id")))
    print(driver.execute_script("return arguments[0].outerHTML;", element))
    
  • Note: You have to add the following imports:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

JUNIT Test class in Eclipse - java.lang.ClassNotFoundException

The above mentioned solutions didn't work for me.

I just restarted my IDE by closing it and reopening it.

And then error disappeared and its working fine now.

html5 input for money/currency

Well in the end I had to compromise by implementing a HTML5/CSS solution, forgoing increment buttons in IE (they're a bit broke in FF anyway!), but gaining number validation that the JQuery spinner doesn't provide. Though I have had to go with a step of whole numbers.

_x000D_
_x000D_
span.gbp {_x000D_
    float: left;_x000D_
    text-align: left;_x000D_
}_x000D_
_x000D_
span.gbp::before {_x000D_
    float: left;_x000D_
    content: "\00a3"; /* £ */_x000D_
    padding: 3px 4px 3px 3px;_x000D_
}_x000D_
_x000D_
span.gbp input {_x000D_
     width: 280px !important;_x000D_
}
_x000D_
<label for="broker_fees">Broker Fees</label>_x000D_
<span class="gbp">_x000D_
    <input type="number" placeholder="Enter whole GBP (&pound;) or zero for none" min="0" max="10000" step="1" value="" name="Broker_Fees" id="broker_fees" required="required" />_x000D_
</span>
_x000D_
_x000D_
_x000D_

The validation is a bit flaky across browsers, where IE/FF allow commas and decimal places (as long as it's .00), where as Chrome/Opera don't and want just numbers.

I guess it's a shame that the JQuery spinner won't work with a number type input, but the docs explicitly state not to do that :-( and I'm puzzled as to why a number spinner widget allows input of any ascii char?

How do I create a URL shortener?

Don't know if anyone will find this useful - it is more of a 'hack n slash' method, yet is simple and works nicely if you want only specific chars.

$dictionary = "abcdfghjklmnpqrstvwxyz23456789";
$dictionary = str_split($dictionary);

// Encode
$str_id = '';
$base = count($dictionary);

while($id > 0) {
    $rem = $id % $base;
    $id = ($id - $rem) / $base;
    $str_id .= $dictionary[$rem];
}


// Decode
$id_ar = str_split($str_id);
$id = 0;

for($i = count($id_ar); $i > 0; $i--) {
    $id += array_search($id_ar[$i-1], $dictionary) * pow($base, $i - 1);
} 

LINQ query to find if items in a list are contained in another list

bool doesL1ContainsL2 = l1.Intersect(l2).Count() == l2.Count;

L1 and L2 are both List<T>

How do the likely/unlikely macros in the Linux kernel work and what is their benefit?

Let's decompile to see what GCC 4.8 does with it

Without __builtin_expect

#include "stdio.h"
#include "time.h"

int main() {
    /* Use time to prevent it from being optimized away. */
    int i = !time(NULL);
    if (i)
        printf("%d\n", i);
    puts("a");
    return 0;
}

Compile and decompile with GCC 4.8.2 x86_64 Linux:

gcc -c -O3 -std=gnu11 main.c
objdump -dr main.o

Output:

0000000000000000 <main>:
   0:       48 83 ec 08             sub    $0x8,%rsp
   4:       31 ff                   xor    %edi,%edi
   6:       e8 00 00 00 00          callq  b <main+0xb>
                    7: R_X86_64_PC32        time-0x4
   b:       48 85 c0                test   %rax,%rax
   e:       75 14                   jne    24 <main+0x24>
  10:       ba 01 00 00 00          mov    $0x1,%edx
  15:       be 00 00 00 00          mov    $0x0,%esi
                    16: R_X86_64_32 .rodata.str1.1
  1a:       bf 01 00 00 00          mov    $0x1,%edi
  1f:       e8 00 00 00 00          callq  24 <main+0x24>
                    20: R_X86_64_PC32       __printf_chk-0x4
  24:       bf 00 00 00 00          mov    $0x0,%edi
                    25: R_X86_64_32 .rodata.str1.1+0x4
  29:       e8 00 00 00 00          callq  2e <main+0x2e>
                    2a: R_X86_64_PC32       puts-0x4
  2e:       31 c0                   xor    %eax,%eax
  30:       48 83 c4 08             add    $0x8,%rsp
  34:       c3                      retq

The instruction order in memory was unchanged: first the printf and then puts and the retq return.

With __builtin_expect

Now replace if (i) with:

if (__builtin_expect(i, 0))

and we get:

0000000000000000 <main>:
   0:       48 83 ec 08             sub    $0x8,%rsp
   4:       31 ff                   xor    %edi,%edi
   6:       e8 00 00 00 00          callq  b <main+0xb>
                    7: R_X86_64_PC32        time-0x4
   b:       48 85 c0                test   %rax,%rax
   e:       74 11                   je     21 <main+0x21>
  10:       bf 00 00 00 00          mov    $0x0,%edi
                    11: R_X86_64_32 .rodata.str1.1+0x4
  15:       e8 00 00 00 00          callq  1a <main+0x1a>
                    16: R_X86_64_PC32       puts-0x4
  1a:       31 c0                   xor    %eax,%eax
  1c:       48 83 c4 08             add    $0x8,%rsp
  20:       c3                      retq
  21:       ba 01 00 00 00          mov    $0x1,%edx
  26:       be 00 00 00 00          mov    $0x0,%esi
                    27: R_X86_64_32 .rodata.str1.1
  2b:       bf 01 00 00 00          mov    $0x1,%edi
  30:       e8 00 00 00 00          callq  35 <main+0x35>
                    31: R_X86_64_PC32       __printf_chk-0x4
  35:       eb d9                   jmp    10 <main+0x10>

The printf (compiled to __printf_chk) was moved to the very end of the function, after puts and the return to improve branch prediction as mentioned by other answers.

So it is basically the same as:

int main() {
    int i = !time(NULL);
    if (i)
        goto printf;
puts:
    puts("a");
    return 0;
printf:
    printf("%d\n", i);
    goto puts;
}

This optimization was not done with -O0.

But good luck on writing an example that runs faster with __builtin_expect than without, CPUs are really smart these days. My naive attempts are here.

C++20 [[likely]] and [[unlikely]]

C++20 has standardized those C++ built-ins: How to use C++20's likely/unlikely attribute in if-else statement They will likely (a pun!) do the same thing.

Array Length in Java

It should be:

int a = arr.length;

Parenthesis should be avoided.

Firebase onMessageReceived not called when app in background

onMessageReceived(RemoteMessage remoteMessage) method called based on the following cases.

  • FCM Response With notification and data block:
{
  
"to": "device token list",
  "notification": {
    "body": "Body of Your Notification",
    "title": "Title of Your Notification"
  },
  "data": {
    "body": "Body of Your Notification in Data",
    "title": "Title of Your Notification in Title",
    "key_1": "Value for key_1",
    "image_url": "www.abc.com/xyz.jpeg",
    "key_2": "Value for key_2"
  }
}
  1. App in Foreground:

onMessageReceived(RemoteMessage remoteMessage) called, shows LargeIcon and BigPicture in the notification bar. We can read the content from both notification and data block

  1. App in Background:

onMessageReceived(RemoteMessage remoteMessage) not called, system tray will receive the message and read body and title from notification block and shows default message and title in the notification bar.

  • FCM Response With only data block:

In this case, removing notification blocks from json

{
  
"to": "device token list",
  "data": {
    "body": "Body of Your Notification in Data",
    "title": "Title of Your Notification in Title",
    "key_1": "Value for key_1",
    "image_url": "www.abc.com/xyz.jpeg",
    "key_2": "Value for key_2"
  }
}

Solution for calling onMessageReceived()

  1. App in Foreground:

onMessageReceived(RemoteMessage remoteMessage) called, shows LargeIcon and BigPicture in the notification bar. We can read the content from both notification and data block

  1. App in Background:

onMessageReceived(RemoteMessage remoteMessage) called, system tray will not receive the message because of notification key is not in the response. Shows LargeIcon and BigPicture in the notification bar

Code

 private void sendNotification(Bitmap bitmap,  String title, String 
    message, PendingIntent resultPendingIntent) {

    NotificationCompat.BigPictureStyle style = new NotificationCompat.BigPictureStyle();
    style.bigPicture(bitmap);

    Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
    String NOTIFICATION_CHANNEL_ID = mContext.getString(R.string.default_notification_channel_id);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "channel_name", NotificationManager.IMPORTANCE_HIGH);

        notificationManager.createNotificationChannel(notificationChannel);
    }
    Bitmap iconLarge = BitmapFactory.decodeResource(mContext.getResources(),
            R.drawable.mdmlogo);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID)
            .setSmallIcon(R.drawable.mdmlogo)
            .setContentTitle(title)
            .setAutoCancel(true)
            .setSound(defaultSound)
            .setContentText(message)
            .setContentIntent(resultPendingIntent)
            .setStyle(style)
            .setLargeIcon(iconLarge)
            .setWhen(System.currentTimeMillis())
            .setPriority(Notification.PRIORITY_MAX)
            .setChannelId(NOTIFICATION_CHANNEL_ID);


    notificationManager.notify(1, notificationBuilder.build());


}

Reference Link:

https://firebase.google.com/docs/cloud-messaging/android/receive

UILabel Align Text to center

IO6.1 [lblTitle setTextAlignment:NSTextAlignmentCenter];

How to set a value to a file input in HTML?

You cannot, due to security reasons.

Imagine:

<form name="foo" method="post" enctype="multipart/form-data">
    <input type="file" value="c:/passwords.txt">
</form>
<script>document.foo.submit();</script>

You don't want the websites you visit to be able to do this, do you? =)

django import error - No module named core.management

I was getting the same problem while I trying to create a new app. If you write python manage.py startapp myapp, then it looks for usr/bin/python. But you need this "python" which is located in /bin directory of your virtual env path. I solved this by mentioning the virtualenv's python path just like this:

<env path>/bin/python manage.py startapp myapp

Node - how to run app.js?

To run app.js file check "main": "app.js" in your package.json file.

Then run command $ node app.js That should run your app and check.

How to 'restart' an android application programmatically

Checkout intent properties like no history , clear back stack etc ... Intent.setFlags

Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);

Extract file name from path, no matter what the os/path format

I have never seen double-backslashed paths, are they existing? The built-in feature of python module os fails for those. All others work, also the caveat given by you with os.path.normpath():

paths = ['a/b/c/', 'a/b/c', '\\a\\b\\c', '\\a\\b\\c\\', 'a\\b\\c', 
...     'a/b/../../a/b/c/', 'a/b/../../a/b/c', 'a/./b/c', 'a\b/c']
for path in paths:
    os.path.basename(os.path.normpath(path))

Resize external website content to fit iFrame width

What you can do is set specific width and height to your iframe (for example these could be equal to your window dimensions) and then applying a scale transformation to it. The scale value will be the ratio between your window width and the dimension you wanted to set to your iframe.

E.g.

<iframe width="1024" height="768" src="http://www.bbc.com" style="-webkit-transform:scale(0.5);-moz-transform-scale(0.5);"></iframe>

JavaScript backslash (\) in variables is causing an error

If you want to use special character in javascript variable value, Escape Character (\) is required.

Backslash in your example is special character, too.

So you should do something like this,

var ttt = "aa ///\\\\\\"; // --> ///\\\

or

var ttt = "aa ///\\"; // --> ///\

But Escape Character not require for user input.

When you press / in prompt box or input field then submit, that means single /.

GitHub Error Message - Permission denied (publickey)

Make sure ssh-add -l shows a fingerprint of an SSH key that's present in the list of SSH keys in your Github account.

If the output is empty, but you know you have a private SSH key that works with your github account, run ssh-add on this key (found in ~/.ssh. It's named id_rsa by default, so you'll likely run ssh-add id_rsa).

Else, follow these instructions to generate an SSH key pair .

Disable webkit's spin buttons on input type="number"?

It seems impossible to prevent spinners from appearing in Opera. As a temporary workaround, you can make room for the spinners. As far as I can tell, the following CSS adds just enough padding, only in Opera:

noindex:-o-prefocus,
input[type=number] {
    padding-right: 1.2em;
}

What is the usefulness of PUT and DELETE HTTP request methods?

Using HTTP Request verb such as GET, POST, DELETE, PUT etc... enables you to build RESTful web applications. Read about it here: http://en.wikipedia.org/wiki/Representational_state_transfer

The easiest way to see benefits from this is to look at this example. Every MVC framework has a Router/Dispatcher that maps URL-s to actionControllers. So URL like this: /blog/article/1 would invoke blogController::articleAction($id); Now this Router is only aware of the URL or /blog/article/1/

But if that Router would be aware of whole HTTP Request object instead of just URL, he could have access HTTP Request verb (GET, POST, PUT, DELETE...), and many other useful stuff about current HTTP Request.

That would enable you to configure application so it can accept the same URL and map it to different actionControllers depending on the HTTP Request verb.

For example:

if you want to retrive article 1 you can do this:

GET /blog/article/1 HTTP/1.1

but if you want to delete article 1 you will do this:

DELETE /blog/article/1 HTTP/1.1

Notice that both HTTP Requests have the same URI, /blog/article/1, the only difference is the HTTP Request verb. And based on that verb your router can call different actionController. This enables you to build neat URL-s.

Read this two articles, they might help you:

Symfony 2 - HTTP Fundamentals

Symfony 2 - Routing

These articles are about Symfony 2 framework, but they can help you to figure out how does HTTP Requests and Responses work.

Hope this helps!

How can I include all JavaScript files in a directory via JavaScript file?

@jellyfishtree it would be a better if you create one php file which includes all your js files from the directory and then only include this php file via a script tag. This has a better performance because the browser has to do less requests to the server. See this:

javascripts.php:

<?php
   //sets the content type to javascript 
   header('Content-type: text/javascript');

   // includes all js files of the directory
   foreach(glob("packages/*.js") as $file) {
      readfile($file);
   }
?>


index.php:

<script type="text/javascript" src="javascripts.php"></script>

That's it!
Have fun! :)

Debug assertion failed. C++ vector subscript out of range

this type of error usually occur when you try to access data through the index in which data data has not been assign. for example

//assign of data in to array
for(int i=0; i<10; i++){
   arr[i]=i;
}
//accessing of data through array index
for(int i=10; i>=0; i--){
cout << arr[i];
}

the code will give error (vector subscript out of range) because you are accessing the arr[10] which has not been assign yet.

rsync: how can I configure it to create target directory on server?

This answer uses bits of other answers, but hopefully it'll be a bit clearer as to the circumstances. You never specified what you were rsyncing - a single directory entry or multiple files.

So let's assume you are moving a source directory entry across, and not just moving the files contained in it.

Let's say you have a directory locally called data/myappdata/ and you have a load of subdirectories underneath this. You have data/ on your target machine but no data/myappdata/ - this is easy enough:

rsync -rvv /path/to/data/myappdata/ user@host:/remote/path/to/data/myappdata

You can even use a different name for the remote directory:

rsync -rvv --recursive /path/to/data/myappdata user@host:/remote/path/to/data/newdirname

If you're just moving some files and not moving the directory entry that contains them then you would do:

rsync -rvv /path/to/data/myappdata/*.txt user@host:/remote/path/to/data/myappdata/

and it will create the myappdata directory for you on the remote machine to place your files in. Again, the data/ directory must exist on the remote machine.

Incidentally, my use of -rvv flag is to get doubly verbose output so it is clear about what it does, as well as the necessary recursive behaviour.

Just to show you what I get when using rsync (3.0.9 on Ubuntu 12.04)

$ rsync -rvv *.txt [email protected]:/tmp/newdir/
opening connection using: ssh -l user remote.machine rsync --server -vvre.iLsf . /tmp/newdir/
[email protected]'s password:
sending incremental file list
created directory /tmp/newdir
delta-transmission enabled
bar.txt
foo.txt
total: matches=0  hash_hits=0  false_alarms=0 data=0

Hope this clears this up a little bit.

How to remove unique key from mysql table

First you need to know the exact name of the INDEX (Unique key in this case) to delete or update it.
INDEX names are usually same as column names. In case of more than one INDEX applied on a column, MySQL automatically suffixes numbering to the column names to create unique INDEX names.

For example if 2 indexes are applied on a column named customer_id

  1. The first index will be named as customer_id itself.
  2. The second index will be names as customer_id_2 and so on.

To know the name of the index you want to delete or update

SHOW INDEX FROM <table_name>

as suggested by @Amr

To delete an index

ALTER TABLE <table_name> DROP INDEX <index_name>;

Several ports (8005, 8080, 8009) required by Tomcat Server at localhost are already in use

Easiest solution

Single line command for killing multiple ports:

kill $(lsof -t -i:8005,8080,8009) // 8005, 8080 and 8009 are the ports to be freed.

How to set value to form control in Reactive Forms in Angular

Setting or Updating of Reactive Forms Form Control values can be done using both patchValue and setValue. However, it might be better to use patchValue in some instances.

patchValue does not require all controls to be specified within the parameters in order to update/set the value of your Form Controls. On the other hand, setValue requires all Form Control values to be filled in, and it will return an error if any of your controls are not specified within the parameter.

In this scenario, we will want to use patchValue, since we are only updating user and questioning:

this.qService.editQue([params["id"]]).subscribe(res => {
  this.question = res;
  this.editqueForm.patchValue({
    user: this.question.user,
    questioning: this.question.questioning
  });
});

EDIT: If you feel like doing some of ES6's Object Destructuring, you may be interested to do this instead

const { user, questioning } = this.question;

this.editqueForm.patchValue({
  user,
  questioning
});

Ta-dah!

How to use passive FTP mode in Windows command prompt?

For passive mode you need to use command "literal" ftp>literal PASV

How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9

As it allows to install more than one version of java, I had install many 3 versions unknowingly but it was point to latest version "11.0.2"

I could able to solve this issue with below steps to move to "1.8"

$java -version

openjdk version "11.0.2" 2019-01-15 OpenJDK Runtime Environment 18.9 (build 11.0.2+9) OpenJDK 64-Bit Server VM 18.9 (build 11.0.2+9, mixed mode)

cd /Library/Java/JavaVirtualMachines
ls

jdk1.8.0_201.jdk jdk1.8.0_202.jdk openjdk-11.0.2.jdk

sudo rm -rf openjdk-11.0.2.jdk
sudo rm -rf jdk1.8.0_201.jdk
ls

jdk1.8.0_202.jdk

java -version

java version "1.8.0_202-ea" Java(TM) SE Runtime Environment (build 1.8.0_202-ea-b03) Java HotSpot(TM) 64-Bit Server VM (build 25.202-b03, mixed mode)

Get size of an Iterable in Java

Why don't you simply use the size() method on your Collection to get the number of elements?

Iterator is just meant to iterate,nothing else.

What is the difference between WCF and WPF?

Windows Presentation Foundation (WPF)

Next-Generation User Experiences. The Windows Presentation Foundation, WPF, provides a unified framework for building applications and high-fidelity experiences in Windows Vista that blend application UI, documents, and media content. WPF offers developers 2D and 3D graphics support, hardware-accelerated effects, scalability to different form factors, interactive data visualization, and superior content readability.

Windows Communication Foundation (WCF)

Windows Communication Foundation (WCF) is Microsoft’s unified programming model for building service-oriented applications. It enables developers to build secure, reliable, transacted solutions that integrate across platforms and interoperate with existing investments.

How to set time zone of a java.util.Date?

java.util.Calendar is the usual way to handle time zones using just JDK classes. Apache Commons has some further alternatives/utilities that may be helpful. Edit Spong's note reminded me that I've heard really good things about Joda-Time (though I haven't used it myself).

How to get $(this) selected option in jQuery?

var cur_value = $('option:selected',this).text();

Convert list to dictionary using linq and not worrying about duplicates

You can also use the ToLookup LINQ function, which you then can use almost interchangeably with a Dictionary.

_people = personList
    .ToLookup(e => e.FirstandLastName, StringComparer.OrdinalIgnoreCase);
_people.ToDictionary(kl => kl.Key, kl => kl.First()); // Potentially unnecessary

This will essentially do the GroupBy in LukeH's answer, but will give the hashing that a Dictionary provides. So, you probably don't need to convert it to a Dictionary, but just use the LINQ First function whenever you need to access the value for the key.

Access denied for user 'root'@'localhost' with PHPMyAdmin

Here are few steps that must be followed carefully

  1. First of all make sure that the WAMP server is running if it is not running, start the server.
  2. Enter the URL http://localhost/phpmyadmin/setup in address bar of your browser.
  3. Create a folder named config inside C:\wamp\apps\phpmyadmin, the folder inside apps may have different name like phpmyadmin3.2.0.1

  4. Return to your browser in phpmyadmin setup tab, and click New server.New server

  5. Change the authentication type to ‘cookie’ and leave the username and password field empty but if you change the authentication type to ‘config’ enter the password for username root.

  6. Click save save

  7. Again click save in configuration file option.
  8. Now navigate to the config folder. Inside the folder there will be a file named config.inc.php. Copy the file and paste it out of the folder (if the file with same name is already there then override it) and finally delete the folder.
  9. Now you are done. Try to connect the mysql server again and this time you won’t get any error. --credits Bibek Subedi

Using sed to split a string with a delimiter

If you're using gnu sed then you can use \x0A for newline:

sed 's/:/\x0A/g' ~/Desktop/myfile.txt

How to convert a file into a dictionary?

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

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

HTML: Changing colors of specific words in a string of text

You could use the longer boringer way

_x000D_
_x000D_
<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">Enter the competition by</p><p style="font-size:14px; color:#ff00; font-weight:bold; font-style:italic;">summer</p> 
_x000D_
_x000D_
_x000D_

you get the point for the rest

Concrete Javascript Regex for Accented Characters (Diacritics)

You can remove the diacritics from alphabets by using:

var str = "résumé"
str.normalize('NFD').replace(/[\u0300-\u036f]/g, '') // returns resume

It will remove all the diacritical marks, and then perform your regex on it

Reference:

https://thread.engineering/2018-08-29-searching-and-sorting-text-with-diacritical-marks-in-javascript/

Excluding files/directories from Gulp task

Gulp uses micromatch under the hood for matching globs, so if you want to exclude any of the .min.js files, you can achieve the same by using an extended globbing feature like this:

src("'js/**/!(*.min).js")

Basically what it says is: grab everything at any level inside of js that doesn't end with *.min.js

Keras, how do I predict after I trained a model?

You must use the same Tokenizer you used to build your model!

Else this will give different vector to each word.

Then, I am using:

phrase = "not good"
tokens = myTokenizer.texts_to_matrix([phrase])

model.predict(np.array(tokens))

Twitter Bootstrap button click to toggle expand/collapse text section above button

html:

<h4 data-toggle-selector="#me">toggle</h4>
<div id="me">content here</div>

js:

$(function () {
    $('[data-toggle-selector]').on('click',function () {
        $($(this).data('toggle-selector')).toggle(300);
    })
})

Is there a Sleep/Pause/Wait function in JavaScript?

You can't (and shouldn't) block processing with a sleep function. However, you can use setTimeout to kick off a function after a delay:

setTimeout(function(){alert("hi")}, 1000);

Depending on your needs, setInterval might be useful, too.

Should I use pt or px?

Here you've got a very detailed explanation of their differences

http://kyleschaeffer.com/development/css-font-size-em-vs-px-vs-pt-vs/

The jist of it (from source)

Pixels are fixed-size units that are used in screen media (i.e. to be read on the computer screen). Pixel stands for "picture element" and as you know, one pixel is one little "square" on your screen. Points are traditionally used in print media (anything that is to be printed on paper, etc.). One point is equal to 1/72 of an inch. Points are much like pixels, in that they are fixed-size units and cannot scale in size.

In Java, how do I call a base class's method from the overriding method in a derived class?

class test
{
    void message()
    {
        System.out.println("super class");
    }
}

class demo extends test
{
    int z;
    demo(int y)
    {
        super.message();
        z=y;
        System.out.println("re:"+z);
    }
}
class free{
    public static void main(String ar[]){
        demo d=new demo(6);
    }
}

Persist javascript variables across pages?

I recommend web storage. Example:

// Storing the data: localStorage.setItem("variableName","Text"); // Receiving the data: localStorage.getItem("variableName");

Just replace variable with your variable name and text with what you want to store. According to W3Schools, it's better than cookies.

UPDATE with CASE and IN - Oracle

Got a solution that runs. Don't know if it is optimal though. What I do is to split the string according to http://blogs.oracle.com/aramamoo/2010/05/how_to_split_comma_separated_string_and_pass_to_in_clause_of_select_statement.html

Using:
select regexp_substr(' 1, 2 , 3 ','[^,]+', 1, level) from dual
connect by regexp_substr('1 , 2 , 3 ', '[^,]+', 1, level) is not null;

So my final code looks like this ($bp_gr1' are strings like 1,2,3):

UPDATE TAB1
SET    BUDGPOST_GR1 =
          CASE
             WHEN ( BUDGPOST IN (SELECT     REGEXP_SUBSTR ( '$BP_GR1',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                 FROM       DUAL
                                 CONNECT BY REGEXP_SUBSTR ( '$BP_GR1',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                               IS NOT NULL) )
             THEN
                'BP_GR1'
             WHEN ( BUDGPOST IN (SELECT     REGEXP_SUBSTR ( ' $BP_GR2',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                 FROM       DUAL
                                 CONNECT BY REGEXP_SUBSTR ( '$BP_GR2',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                               IS NOT NULL) )
             THEN
                'BP_GR2'
             WHEN ( BUDGPOST IN (SELECT     REGEXP_SUBSTR ( ' $BP_GR3',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                 FROM       DUAL
                                 CONNECT BY REGEXP_SUBSTR ( '$BP_GR3',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                               IS NOT NULL) )
             THEN
                'BP_GR3'
             WHEN ( BUDGPOST IN (SELECT     REGEXP_SUBSTR ( '$BP_GR4',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                 FROM       DUAL
                                 CONNECT BY REGEXP_SUBSTR ( '$BP_GR4',
                                                            '[^,]+',
                                                            1,
                                                            LEVEL )
                                               IS NOT NULL) )
             THEN
                'BP_GR4'
             ELSE
                'SAKNAR BUDGETGRUPP'
          END;

Is there a way to make it run faster?

C# - insert values from file into two arrays

var Text = File.ReadAllLines("Path"); foreach (var i in Text) {    var SplitText = i.Split().Where(x=> x.Lenght>1).ToList();    //@Array1 add SplitText[0]    //@Array2 add SpliteText[1]   }  

C++ equivalent of Java's toString?

You can also do it this way, allowing polymorphism:

class Base {
public:
   virtual std::ostream& dump(std::ostream& o) const {
      return o << "Base: " << b << "; ";
   }
private:
  int b;
};

class Derived : public Base {
public:
   virtual std::ostream& dump(std::ostream& o) const {
      return o << "Derived: " << d << "; ";
   }
private:
   int d;
}

std::ostream& operator<<(std::ostream& o, const Base& b) { return b.dump(o); }

How to get the unix timestamp in C#

You can also use Ticks. I'm coding for Windows Mobile so don't have the full set of methods. TotalSeconds is not available to me.

long epochTicks = new DateTime(1970, 1, 1).Ticks;
long unixTime = ((DateTime.UtcNow.Ticks - epochTicks) / TimeSpan.TicksPerSecond);

or

TimeSpan epochTicks = new TimeSpan(new DateTime(1970, 1, 1).Ticks);
TimeSpan unixTicks = new TimeSpan(DateTime.UtcNow.Ticks) - epochTicks;
double unixTime = unixTicks.TotalSeconds;

How can I sharpen an image in OpenCV?

For clarity in this topic, a few points really should be made:

  1. Sharpening images is an ill-posed problem. In other words, blurring is a lossy operation, and going back from it is in general not possible.

  2. To sharpen single images, you need to somehow add constraints (assumptions) on what kind of image it is you want, and how it has become blurred. This is the area of natural image statistics. Approaches to do sharpening hold these statistics explicitly or implicitly in their algorithms (deep learning being the most implicitly coded ones). The common approach of up-weighting some of the levels of a DOG or Laplacian pyramid decomposition, which is the generalization of Brian Burns answer, assumes that a Gaussian blurring corrupted the image, and how the weighting is done is connected to assumptions on what was in the image to begin with.

  3. Other sources of information can render the problem sharpening well-posed. Common such sources of information is video of a moving object, or multi-view setting. Sharpening in that setting is usually called super-resolution (which is a very bad name for it, but it has stuck in academic circles). There has been super-resolution methods in OpenCV since a long time.... although they usually dont work that well for real problems last I checked them out. I expect deep learning has produced some wonderful results here as well. Maybe someone will post in remarks on whats worthwhile out there.

How to make cross domain request

Do a cross-domain AJAX call

Your web-service must support method injection in order to do JSONP.

Your code seems fine and it should work if your web services and your web application hosted in the same domain.

When you do a $.ajax with dataType: 'jsonp' meaning that jQuery is actually adding a new parameter to the query URL.

For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do then jQuery will add ?callback={some_random_dynamically_generated_method}.

This method is more kind of a proxy actually attached in window object. This is nothing specific but does look something like this:

window.some_random_dynamically_generated_method = function(actualJsonpData) {
    //here actually has reference to the success function mentioned with $.ajax
    //so it just calls the success method like this: 
    successCallback(actualJsonData);
}

Check the following for more information

Make cross-domain ajax JSONP request with jQuery

SQL command to display history of queries

(Linux) Open your Terminal ctrl+alt+t run the command

 cat ~/.mysql_history

you will get all the previous mysql query history enjoy :)

How can I install the Beautiful Soup module on the Mac?

Brian beat me too it, but since I already have the transcript:

easy_install

aaron@ares ~$ sudo easy_install BeautifulSoup
Searching for BeautifulSoup
Best match: BeautifulSoup 3.0.7a
Processing BeautifulSoup-3.0.7a-py2.5.egg
BeautifulSoup 3.0.7a is already the active version in easy-install.pth

Using /Library/Python/2.5/site-packages/BeautifulSoup-3.0.7a-py2.5.egg
Processing dependencies for BeautifulSoup
Finished processing dependencies for BeautifulSoup

.. or the normal boring way:

aaron@ares ~/Downloads$ curl http://www.crummy.com/software/BeautifulSoup/download/BeautifulSoup.tar.gz > bs.tar.gz
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 71460  100 71460    0     0  84034      0 --:--:-- --:--:-- --:--:--  111k

aaron@ares ~/Downloads$ tar -xzvf bs.tar.gz 
BeautifulSoup-3.1.0.1/
BeautifulSoup-3.1.0.1/BeautifulSoup.py
BeautifulSoup-3.1.0.1/BeautifulSoup.py.3.diff
BeautifulSoup-3.1.0.1/BeautifulSoupTests.py
BeautifulSoup-3.1.0.1/BeautifulSoupTests.py.3.diff
BeautifulSoup-3.1.0.1/CHANGELOG
BeautifulSoup-3.1.0.1/README
BeautifulSoup-3.1.0.1/setup.py
BeautifulSoup-3.1.0.1/testall.sh
BeautifulSoup-3.1.0.1/to3.sh
BeautifulSoup-3.1.0.1/PKG-INFO
BeautifulSoup-3.1.0.1/BeautifulSoup.pyc
BeautifulSoup-3.1.0.1/BeautifulSoupTests.pyc

aaron@ares ~/Downloads$ cd BeautifulSoup-3.1.0.1/

aaron@ares ~/Downloads/BeautifulSoup-3.1.0.1$ sudo python setup.py install
running install
<... snip ...>

Python dictionary: Get list of values for list of keys

Try This:

mydict = {'one': 1, 'two': 2, 'three': 3}
mykeys = ['three', 'one','ten']
newList=[mydict[k] for k in mykeys if k in mydict]
print newList
[3, 1]

How do I enable --enable-soap in php on linux?

Getting SOAP working usually does not require compiling PHP from source. I would recommend trying that only as a last option.

For good measure, check to see what your phpinfo says, if anything, about SOAP extensions:

$ php -i | grep -i soap

to ensure that it is the PHP extension that is missing.

Assuming you do not see anything about SOAP in the phpinfo, see what PHP SOAP packages might be available to you.

In Ubuntu/Debian you can search with:

$ apt-cache search php | grep -i soap

or in RHEL/Fedora you can search with:

$ yum search php | grep -i soap

There are usually two PHP SOAP packages available to you, usually php-soap and php-nusoap. php-soap is typically what you get with configuring PHP with --enable-soap.

In Ubuntu/Debian you can install with:

$ sudo apt-get install php-soap

Or in RHEL/Fedora you can install with:

$ sudo yum install php-soap

After the installation, you might need to place an ini file and restart Apache.

how to get rid of notification circle in right side of the screen?

This stuff comes from ES file explorer

Just go into this app > settings

Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good

Static method in a generic class?

Something like the following would get you closer

class Clazz
{
   public static <U extends Clazz> void doIt(U thing)
   {
   }
}

EDIT: Updated example with more detail

public abstract class Thingo 
{

    public static <U extends Thingo> void doIt(U p_thingo)
    {
        p_thingo.thing();
    }

    protected abstract void thing();

}

class SubThingoOne extends Thingo
{
    @Override
    protected void thing() 
    {
        System.out.println("SubThingoOne");
    }
}

class SubThingoTwo extends Thingo
{

    @Override
    protected void thing() 
    {
        System.out.println("SuThingoTwo");
    }

}

public class ThingoTest 
{

    @Test
    public void test() 
    {
        Thingo t1 = new SubThingoOne();
        Thingo t2 = new SubThingoTwo();

        Thingo.doIt(t1);
        Thingo.doIt(t2);

        // compile error -->  Thingo.doIt(new Object());
    }
}

Creating a 3D sphere in Opengl using Visual C++

In OpenGL you don't create objects, you just draw them. Once they are drawn, OpenGL no longer cares about what geometry you sent it.

glutSolidSphere is just sending drawing commands to OpenGL. However there's nothing special in and about it. And since it's tied to GLUT I'd not use it. Instead, if you really need some sphere in your code, how about create if for yourself?

#define _USE_MATH_DEFINES
#include <GL/gl.h>
#include <GL/glu.h>
#include <vector>
#include <cmath>

// your framework of choice here

class SolidSphere
{
protected:
    std::vector<GLfloat> vertices;
    std::vector<GLfloat> normals;
    std::vector<GLfloat> texcoords;
    std::vector<GLushort> indices;

public:
    SolidSphere(float radius, unsigned int rings, unsigned int sectors)
    {
        float const R = 1./(float)(rings-1);
        float const S = 1./(float)(sectors-1);
        int r, s;

        vertices.resize(rings * sectors * 3);
        normals.resize(rings * sectors * 3);
        texcoords.resize(rings * sectors * 2);
        std::vector<GLfloat>::iterator v = vertices.begin();
        std::vector<GLfloat>::iterator n = normals.begin();
        std::vector<GLfloat>::iterator t = texcoords.begin();
        for(r = 0; r < rings; r++) for(s = 0; s < sectors; s++) {
                float const y = sin( -M_PI_2 + M_PI * r * R );
                float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
                float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );

                *t++ = s*S;
                *t++ = r*R;

                *v++ = x * radius;
                *v++ = y * radius;
                *v++ = z * radius;

                *n++ = x;
                *n++ = y;
                *n++ = z;
        }

        indices.resize(rings * sectors * 4);
        std::vector<GLushort>::iterator i = indices.begin();
        for(r = 0; r < rings; r++) for(s = 0; s < sectors; s++) {
                *i++ = r * sectors + s;
                *i++ = r * sectors + (s+1);
                *i++ = (r+1) * sectors + (s+1);
                *i++ = (r+1) * sectors + s;
        }
    }

    void draw(GLfloat x, GLfloat y, GLfloat z)
    {
        glMatrixMode(GL_MODELVIEW);
        glPushMatrix();
        glTranslatef(x,y,z);

        glEnableClientState(GL_VERTEX_ARRAY);
        glEnableClientState(GL_NORMAL_ARRAY);
        glEnableClientState(GL_TEXTURE_COORD_ARRAY);

        glVertexPointer(3, GL_FLOAT, 0, &vertices[0]);
        glNormalPointer(GL_FLOAT, 0, &normals[0]);
        glTexCoordPointer(2, GL_FLOAT, 0, &texcoords[0]);
        glDrawElements(GL_QUADS, indices.size(), GL_UNSIGNED_SHORT, &indices[0]);
        glPopMatrix();
    }
};

SolidSphere sphere(1, 12, 24);

void display()
{
    int const win_width  = …; // retrieve window dimensions from
    int const win_height = …; // framework of choice here
    float const win_aspect = (float)win_width / (float)win_height;

    glViewport(0, 0, win_width, win_height);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45, win_aspect, 1, 10);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

#ifdef DRAW_WIREFRAME
    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
#endif
    sphere.draw(0, 0, -5);

    swapBuffers();
}

int main(int argc, char *argv[])
{
    // initialize and register your framework of choice here
    return 0;
}

What to return if Spring MVC controller method doesn't return value?

you can return void, then you have to mark the method with @ResponseStatus(value = HttpStatus.OK) you don't need @ResponseBody

@RequestMapping(value = "/updateSomeData" method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.OK)
public void updateDataThatDoesntRequireClientToBeNotified(...) {
    ...
}

Only get methods return a 200 status code implicity, all others you have do one of three things:

  • Return void and mark the method with @ResponseStatus(value = HttpStatus.OK)
  • Return An object and mark it with @ResponseBody
  • Return an HttpEntity instance

Where are the Properties.Settings.Default stored?

One of my windows services is logged on as Local System in windows server 2016, and I can find the user.config under C:\Windows\SysWOW64\config\systemprofile\AppData\Local\{your application name}.

I think the easiest way is searching your application name on C drive and then check where is the user.config

/exclude in xcopy just for a file type

Change *.cs to .cs in the excludefileslist.txt

How to parse data in JSON format?

Following is simple example that may help you:

json_string = """
{
    "pk": 1, 
    "fa": "cc.ee", 
    "fb": {
        "fc": "", 
        "fd_id": "12345"
    }
}"""

import json
data = json.loads(json_string)
if data["fa"] == "cc.ee":
    data["fb"]["new_key"] = "cc.ee was present!"

print json.dumps(data)

The output for the above code will be:

{"pk": 1, "fb": {"new_key": "cc.ee was present!", "fd_id": "12345", 
 "fc": ""}, "fa": "cc.ee"}

Note that you can set the ident argument of dump to print it like so (for example,when using print json.dumps(data , indent=4)):

{
    "pk": 1, 
    "fb": {
        "new_key": "cc.ee was present!", 
        "fd_id": "12345", 
        "fc": ""
    }, 
    "fa": "cc.ee"
}

Cannot execute RUN mkdir in a Dockerfile

The problem is that /var/www doesn't exist either, and mkdir isn't recursive by default -- it expects the immediate parent directory to exist.

Use:

mkdir -p /var/www/app

...or install a package that creates a /var/www prior to reaching this point in your Dockerfile.

What is __init__.py for?

Files named __init__.py are used to mark directories on disk as Python package directories. If you have the files

mydir/spam/__init__.py
mydir/spam/module.py

and mydir is on your path, you can import the code in module.py as

import spam.module

or

from spam import module

If you remove the __init__.py file, Python will no longer look for submodules inside that directory, so attempts to import the module will fail.

The __init__.py file is usually empty, but can be used to export selected portions of the package under more convenient name, hold convenience functions, etc. Given the example above, the contents of the init module can be accessed as

import spam

based on this

How to replace blank (null ) values with 0 for all records?

UPDATE table SET column=0 WHERE column IS NULL

Uses for the '&quot;' entity in HTML

It is likely because they used a single function for escaping attributes and text nodes. &amp; doesn't do any harm so why complicate your code and make it more error-prone by having two escaping functions and having to pick between them?

How to use JavaScript source maps (.map files)?

Just wanted to focus on the last part of the question; How source map files are created? by listing the build tools I know that can create source maps.

  1. Grunt: using plugin grunt-contrib-uglify
  2. Gulp: using plugin gulp-uglify
  3. Google closure: using parameter --create_source_map

Best practices when running Node.js with port 80 (Ubuntu / Linode)

For port 80 (which was the original question), Daniel is exactly right. I recently moved to https and had to switch from iptables to a light nginx proxy managing the SSL certs. I found a useful answer along with a gist by gabrielhpugliese on how to handle that. Basically I

Hopefully that can save someone else some headaches. I'm sure there's a pure-node way of doing this, but nginx was quick and it worked.

How do I negate a test with regular expressions in a bash script?

You can also put the exclamation mark inside the brackets:

if [[ ! $PATH =~ $temp ]]

but you should anchor your pattern to reduce false positives:

temp=/mnt/silo/bin
pattern="(^|:)${temp}(:|$)"
if [[ ! "${PATH}" =~ ${pattern} ]]

which looks for a match at the beginning or end with a colon before or after it (or both). I recommend using lowercase or mixed case variable names as a habit to reduce the chance of name collisions with shell variables.

Specifying java version in maven - differences between properties and compiler plugin

Consider the alternative:

<properties>
    <javac.src.version>1.8</javac.src.version>
    <javac.target.version>1.8</javac.target.version>
</properties>

It should be the same thing of maven.compiler.source/maven.compiler.target but the above solution works for me, otherwise the second one gets the parent specification (I have a matrioska of .pom)

How to check if a socket is connected/disconnected in C#?

I made an extension method based on this MSDN article. This is how you can determine whether a socket is still connected.

public static bool IsConnected(this Socket client)
{
    bool blockingState = client.Blocking;

    try
    {
        byte[] tmp = new byte[1];

        client.Blocking = false;
        client.Send(tmp, 0, 0);
        return true;
    }
    catch (SocketException e)
    {
        // 10035 == WSAEWOULDBLOCK
        if (e.NativeErrorCode.Equals(10035))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    finally
    {
        client.Blocking = blockingState;
    }
}

Evaluate expression given as a string

The eval() function evaluates an expression, but "5+5" is a string, not an expression. Use parse() with text=<string> to change the string into an expression:

> eval(parse(text="5+5"))
[1] 10
> class("5+5")
[1] "character"
> class(parse(text="5+5"))
[1] "expression"

Calling eval() invokes many behaviours, some are not immediately obvious:

> class(eval(parse(text="5+5")))
[1] "numeric"
> class(eval(parse(text="gray")))
[1] "function"
> class(eval(parse(text="blue")))
Error in eval(expr, envir, enclos) : object 'blue' not found

See also tryCatch.

How to perform OR condition in django queryset?

Just adding this for multiple filters attaching to Q object, if someone might be looking to it. If a Q object is provided, it must precede the definition of any keyword arguments. Otherwise its an invalid query. You should be careful when doing it.

an example would be

from django.db.models import Q
User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True),category='income')

Here the OR condition and a filter with category of income is taken into account

How do you make a div tag into a link

You could use Javascript to achieve this effect. If you use a framework this sort of thing becomes quite simple. Here is an example in jQuery:

$('div#id').click(function (e) {
  // Do whatever you want
});

This solution has the distinct advantage of keeping the logic not in your markup.

How to view UTF-8 Characters in VIM or Gvim

On Microsoft Windows, gvim wouldn't allow you to select non-monospaced fonts. Unfortunately Latha is a non-monospaced font.

There is a hack way to make it happen: Using FontForge (you can download Windows binary from http://www.geocities.jp/meir000/fontforge/) to edit the Latha.ttf and mark it as a monospaced font. Doing like this:

  1. Load fontforge, select latha.ttf.
  2. Menu: Element -> Font Info
  3. Select "OS/2" from left-hand list on Font Info dialog
  4. Select "Panose" tab
  5. Set Proportion = Monospaced
  6. Save new TTF version of this font, try it out!

Good luck!