Programs & Examples On #Traceroute

traceroute traces the route taken by packets over a TCP/IP network. It is used as a network debugging tool to show where packets are being lost along the route.

trace a particular IP and port

Firstly, check the IP address that your application has bound to. It could only be binding to a local address, for example, which would mean that you'd never see it from a different machine regardless of firewall states.

You could try using a portscanner like nmap to see if the port is open and visible externally... it can tell you if the port is closed (there's nothing listening there), open (you should be able to see it fine) or filtered (by a firewall, for example).

Resolving ORA-4031 "unable to allocate x bytes of shared memory"

The following are not needed as they they not fix the error:

  1. ps -ef|grep oracle
  2. Find the smon and kill the pid for it
  3. SQL> startup mount
  4. SQL> create pfile from spfile;

Restarting the database will flush your pool and that solves a effect not the problem.

Fixate your large_pool so it can not go lower then a certain point or add memory and set a higher max memory.

How to declare and initialize a static const array as a class member?

// in foo.h
class Foo {
    static const unsigned char* Msg;
};

// in foo.cpp
static const unsigned char Foo_Msg_data[] = {0x00,0x01};
const unsigned char* Foo::Msg = Foo_Msg_data;

com.sun.jdi.InvocationException occurred invoking method

Disabling 'Show Logical Structure' button/icon of the upper right corner of the variables window in the eclipse debugger resolved it, in my case.

Server did not recognize the value of HTTP Header SOAPAction

I found out that my web reference was out of date and the code was calling a removed web service.

NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference

This is the error line:

if (called_from.equalsIgnoreCase("add")) {  --->38th error line

This means that called_from is null. Simple check if it is null above:

String called_from = getIntent().getStringExtra("called");

if(called_from == null) {
    called_from = "empty string";
}
if (called_from.equalsIgnoreCase("add")) {
    // do whatever
} else {
    // do whatever
}

That way, if called_from is null, it'll execute the else part of your if statement.

How to increment variable under DOS?

I built my answer thanks to previous contributors.

Not having time for a custom counter.exe, I downloaded sed for FREEDOS.

And then the batch code could be, emulating "wc -l" with the utility sed, something like this according to your loop (I just use it to increment through executions starting from "1" to n+1):

Just remember to manually create a file "test.txt" with written on the first row

0


sed -n '$=' test.txt > counter.txt
set /P Var=< counter.txt
echo 0 >> test.txt

Display Yes and No buttons instead of OK and Cancel in Confirm box?

No, it is not possible to change the content of the buttons in the dialog displayed by the confirm function. You can use Javascript to create a dialog that looks similar.

Hibernate - A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance

I ran into this when updating an entity with a JSON post request. The error occurred when I updated the entity without data about the children, even when there were none. Adding

"children": [],

to the request body solved the problem.

Disable same origin policy in Chrome

Using the current latest chrome version (Version 88.0.4324.182 (Official Build) (64-bit)), the only way I could make it work on windows 10 was to start chrome using the below flags (change the D:\temp to your liking). This solution will start chrome as a sandbox for tests and it will not affect the main chrome profile:

--disable-site-isolation-trials --disable-web-security --user-data-dir="D:\temp"

in windows, click the start button then copy paste the below:

chrome.exe  --disable-site-isolation-trials --disable-web-security --user-data-dir="D:\temp"

Extract digits from string - StringUtils Java

I always like using Guava String utils or similar for these kind of problems:

String theDigits = CharMatcher.inRange('0', '9').retainFrom("abc12 3def"); // 123

Using HTML data-attribute to set CSS background-image url

It is not best practise to mix up content with style, but a solution could be

<div class="thumb" style="background-image: url('images/img.jpg')"></div>

How to parse XML using jQuery?

I went the way of jQuery's .parseXML() however found that the XML path syntax of 'Page[Name="test"] > controls > test' wouldn't work (if anyone knows why please shout out!).

Instead I chained together the individual .find() results into something that looked like this:

$xmlDoc.find('Page[Name="test"]')
       .find('contols')
       .find('test')

The result achieves the same as what I would expect the one shot find.

How to test that a registered variable is not empty?

- name: set pkg copy dir name
  set_fact:
    PKG_DIR: >-
      {% if ansible_os_family == "RedHat" %}centos/*.rpm
      {%- elif ansible_distribution == "Ubuntu" %}ubuntu/*.deb
      {%- elif ansible_distribution == "Kylin Linux Advanced Server" %}kylin/*.deb
      {%- else %}{%- endif %}

How can I get the current network interface throughput statistics on Linux/UNIX?

nload is a great tool for monitoring bandwidth in real time and easily installed in Ubuntu or Debian with sudo apt-get install nload.

Device eth0 [10.10.10.5] (1/2):
=====================================================================================
Incoming:


                               .         ...|    
                               #         ####|   
                           .. |#|  ...   #####.         ..          Curr: 2.07 MBit/s
                          ###.###  #### #######|.     . ##      |   Avg: 1.41 MBit/s
                         ########|#########################.   ###  Min: 1.12 kBit/s
             ........    ###################################  .###  Max: 4.49 MBit/s
           .##########. |###################################|#####  Ttl: 1.94 GByte
Outgoing:
            ##########  ###########    ###########################
            ##########  ###########    ###########################
            ##########. ###########   .###########################
            ########### ###########  #############################
            ########### ###########..#############################
           ############ ##########################################
           ############ ##########################################
           ############ ##########################################  Curr: 63.88 MBit/s
           ############ ##########################################  Avg: 32.04 MBit/s
           ############ ##########################################  Min: 0.00 Bit/s
           ############ ##########################################  Max: 93.23 MBit/s
         ############## ##########################################  Ttl: 2.49 GByte

Another excellent tool is iftop, also easily apt-get'able:

             191Mb      381Mb                 572Mb       763Mb             954Mb     
+--------------------------------------------------------------------------------
box4.local            => box-2.local                      91.0Mb  27.0Mb  15.1Mb
                      <=                                  1.59Mb   761kb   452kb
box4.local            => box.local                         560b   26.8kb  27.7kb
                      <=                                   880b   31.3kb  32.1kb
box4.local            => userify.com                         0b   11.4kb  8.01kb
                      <=                                  1.17kb  2.39kb  1.75kb
box4.local            => b.resolvers.Level3.net              0b     58b    168b
                      <=                                     0b     83b    288b
box4.local            => stackoverflow.com                   0b     42b     21b
                      <=                                     0b     42b     21b
box4.local            => 224.0.0.251                         0b      0b    179b
                      <=                                     0b      0b      0b
224.0.0.251           => box-2.local                         0b      0b      0b
                      <=                                     0b      0b     36b
224.0.0.251           => box.local                           0b      0b      0b
                      <=                                     0b      0b     35b


---------------------------------------------------------------------------------
TX:           cum:   37.9MB   peak:   91.0Mb     rates:   91.0Mb  27.1Mb  15.2Mb
RX:                  1.19MB           1.89Mb              1.59Mb   795kb   486kb
TOTAL:               39.1MB           92.6Mb              92.6Mb  27.9Mb  15.6Mb

Don't forget about the classic and powerful sar and netstat utilities on older *nix!

Is it possible to get element from HashMap by its position?

HashMap - and the underlying data structure - hash tables, do not have a notion of position. Unlike a LinkedList or Vector, the input key is transformed to a 'bucket' where the value is stored. These buckets are not ordered in a way that makes sense outside the HashMap interface and as such, the items you put into the HashMap are not in order in the sense that you would expect with the other data structures

Initialize class fields in constructor or at declaration?

Being consistent is important, but this is the question to ask yourself: "Do I have a constructor for anything else?"

Typically, I am creating models for data transfers that the class itself does nothing except work as housing for variables.

In these scenarios, I usually don't have any methods or constructors. It would feel silly to me to create a constructor for the exclusive purpose of initializing my lists, especially since I can initialize them in-line with the declaration.

So as many others have said, it depends on your usage. Keep it simple, and don't make anything extra that you don't have to.

Best way to copy a database (SQL Server 2008)

If you want to take a copy of a live database, do the Backup/Restore method.

[In SQLS2000, not sure about 2008:] Just keep in mind that if you are using SQL Server accounts in this database, as opposed to Windows accounts, if the master DB is different or out of sync on the development server, the user accounts will not translate when you do the restore. I've heard about an SP to remap them, but I can't remember which one it was.

How to add a local repo and treat it as a remote repo

It appears that your format is incorrect:

If you want to share a locally created repository, or you want to take contributions from someone elses repository - if you want to interact in any way with a new repository, it's generally easiest to add it as a remote. You do that by running git remote add [alias] [url]. That adds [url] under a local remote named [alias].

#example
$ git remote
$ git remote add github [email protected]:schacon/hw.git
$ git remote -v

http://gitref.org/remotes/#remote

How to resume Fragment from BackStack if exists

I think this method my solve your problem:

public static void attachFragment ( int fragmentHolderLayoutId, Fragment fragment, Context context, String tag ) {


    FragmentManager manager = ( (AppCompatActivity) context ).getSupportFragmentManager ();
    FragmentTransaction ft = manager.beginTransaction ();

    if (manager.findFragmentByTag ( tag ) == null) { // No fragment in backStack with same tag..
        ft.add ( fragmentHolderLayoutId, fragment, tag );
        ft.addToBackStack ( tag );
        ft.commit ();
    }
    else {
        ft.show ( manager.findFragmentByTag ( tag ) ).commit ();
    }
}

which was originally posted in This Question

Trim leading and trailing spaces from a string in awk

If it is safe to assume only one set of spaces in column two (which is the original example):

awk '{print $1$2}' /tmp/input.txt

Adding another field, e.g. awk '{print $1$2$3}' /tmp/input.txt will catch two sets of spaces (up to three words in column two), and won't break if there are fewer.

If you have an indeterminate (large) number of space delimited words, I'd use one of the previous suggestions, otherwise this solution is the easiest you'll find using awk.

Viewing localhost website from mobile device

Here is how I managed to make it work for VS 2015 on Windows 10 pro using following steps. It works for both http and https websites. (below example assumes your ip address is 192.168.1.15 and your port number is 12345)

  1. Open project config file at /{project folder}/.vs/config/applicationhost.config and add a new binding address inside <binding> section as shown below (a binding for localhost is already there, just copy/paste the same line and replace localhost with your IP address)
    <bindings>     
       <binding protocol="http" bindingInformation="*:12345:localhost" />          
       <binding protocol="http" bindingInformation="*:12345:192.168.1.15" />  
    </bindings>
  1. Open Command Prompt window as administrator and run the following command.
    netsh http add urlacl url=http://192.168.1.15:12345/ user=everyone
  1. Open "Windows Defender Firewall and Advanced Security" select "Inbound Rules" click "New Rule..." select "Port" then add TCP port 12345 and click next to finish the process.

  2. Right-click on Visual Studio shortcut and select "Run as administrator", then open your project and press Ctrl+F5 to open the website.

  3. Inside browser address bar, replace localhost with 192.168.1.15 and hit enter to reload your website with the new address. Now you should also be able to access the website from your mobile browser using the same address as long as it's connected to the same wifi.

If it doesn't work, make sure visual studio is run as administrator. (step 4)

how to add key value pair in the JSON object already declared

Could you do the following:

obj = {
    "1":"aa",
    "2":"bb"
};


var newNum = "3";
var newVal = "cc";


obj[newNum] = newVal;



alert(obj["3"]); // this would alert 'cc'

Find out if string ends with another string in C++

Found this nice answer to the similar "startWith"-problem:

How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?

You can adopt the solution to only search at the last place in the string:

bool endsWith(const std::string& stack, const std::string& needle) {
    return stack.find(needle, stack.size() - needle.size()) != std::string::npos;
}

This way you can make it short, fast, use standard c++ and make it readable.

How to convert the time from AM/PM to 24 hour format in PHP?

If you use a Datetime format see http://php.net/manual/en/datetime.format.php

You can do this :

$date = new \DateTime();
echo date_format($date, 'Y-m-d H:i:s');
#output: 2012-03-24 17:45:12

echo date_format($date, 'G:ia');
#output: 05:45pm

How to move or copy files listed by 'find' command in unix?

If you're using GNU find,

find . -mtime 1 -exec cp -t ~/test/ {} +

This works as well as piping the output into xargs while avoiding the pitfalls of doing so (it handles embedded spaces and newlines without having to use find ... -print0 | xargs -0 ...).

Create a table without a header in Markdown

At least for the GitHub Flavoured Markdown, you can give the illusion by making all the non-header row entries bold with the regular __ or ** formatting:

|Regular | text | in header | turns bold |
|-|-|-|-|
| __So__ | __bold__ | __all__ | __table entries__ |
| __and__ | __it looks__ | __like a__ | __"headerless table"__ |

How to identify server IP address in PHP

Check the $_SERVER array

echo $_SERVER['SERVER_ADDR'];

SQL "between" not inclusive

cast(created_at as date)

That will work only in 2008 and newer versions of SQL Server

If you are using older version then use

convert(varchar, created_at, 101)

jQuery get mouse position within an element

Here is one that also gives you percent position of the point in case you need it. https://jsfiddle.net/Themezly/2etbhw01/

_x000D_
_x000D_
function ThzhotspotPosition(evt, el, hotspotsize, percent) {_x000D_
  var left = el.offset().left;_x000D_
  var top = el.offset().top;_x000D_
  var hotspot = hotspotsize ? hotspotsize : 0;_x000D_
  if (percent) {_x000D_
    x = (evt.pageX - left - (hotspot / 2)) / el.outerWidth() * 100 + '%';_x000D_
    y = (evt.pageY - top - (hotspot / 2)) / el.outerHeight() * 100 + '%';_x000D_
  } else {_x000D_
    x = (evt.pageX - left - (hotspot / 2));_x000D_
    y = (evt.pageY - top - (hotspot / 2));_x000D_
  }_x000D_
_x000D_
  return {_x000D_
    x: x,_x000D_
    y: y_x000D_
  };_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
$(function() {_x000D_
_x000D_
  $('.box').click(function(e) {_x000D_
_x000D_
    var hp = ThzhotspotPosition(e, $(this), 20, true); // true = percent | false or no attr = px_x000D_
_x000D_
    var hotspot = $('<div class="hotspot">').css({_x000D_
      left: hp.x,_x000D_
      top: hp.y,_x000D_
    });_x000D_
    $(this).append(hotspot);_x000D_
    $("span").text("X: " + hp.x + ", Y: " + hp.y);_x000D_
  });_x000D_
_x000D_
_x000D_
});
_x000D_
.box {_x000D_
  width: 400px;_x000D_
  height: 400px;_x000D_
  background: #efefef;_x000D_
  margin: 20px;_x000D_
  padding: 20px;_x000D_
  position: relative;_x000D_
  top: 20px;_x000D_
  left: 20px;_x000D_
}_x000D_
_x000D_
.hotspot {_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
  height: 20px;_x000D_
  width: 20px;_x000D_
  background: green;_x000D_
  border-radius: 20px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="box">_x000D_
  <p>Hotspot position is at: <span></span></p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Git push results in "Authentication Failed"

Try the following steps to Edit or Remove the saved credentials:

  1. Click Start
  2. Type: Credential Manager (On Windows 10, this is under "Start->Settings". Then search for "Credential Manager")
  3. See the Windows Credentials Manager shortcut and double-click it to open the application.
  4. Once the app is open, click on the Windows Credentials tab.
  5. Locate the credentials that you want to remove/update, they will start with "git:" and might begin with "ada:"
  6. Click on the credential entry, it will open a details view of the entry.
  7. Click Edit or Remove as required and confirm.
  8. Wash, rinse, repeat as necessary.

enter image description here

Can I obtain method parameter name using Java reflection?

To add my 2 cents; parameter info is available in a class file "for debugging" when you use javac -g to compile the source. And it is available to APT but you'll need an annotation so no use to you. (Somebody discussed something similar 4-5 years ago here: http://forums.java.net/jive/thread.jspa?messageID=13467&tstart=0 )

Overall in-short you can't get it unless you work on Source files directly (similar to what APT does at compile time).

How to monitor Java memory usage?

I would say that the consultant is right in the theory, and you are right in practice. As the saying goes:

In theory, theory and practice are the same. In practice, they are not.

The Java spec says that System.gc suggests to call garbage collection. In practice, it just spawns a thread and runs right away on the Sun JVM.

Although in theory you could be messing up some finely tuned JVM implementation of garbage collection, unless you are writing generic code intended to be deployed on any JVM out there, don't worry about it. If it works for you, do it.

How to send HTML-formatted email?

This works for me

msg.BodyFormat = MailFormat.Html;

and then you can use html in your body

msg.Body = "<em>It's great to use HTML in mail!!</em>"

How to implement private method in ES6 class with Traceur

I hope this can be helpful. :)

I. Declaring vars, functions inside IIFE(Immediately-invoked function expression), those can be used only in the anonymous function. (It can be good to use "let, const" keywords without using 'var' when you need to change code for ES6.)

let Name = (function() {
  const _privateHello = function() {
  }
  class Name {
    constructor() {
    }
    publicMethod() {
      _privateHello()
    }
  }
  return Name;
})();

II. WeakMap object can be good for memoryleak trouble.

Stored variables in the WeakMap will be removed when the instance will be removed. Check this article. (Managing the private data of ES6 classes)

let Name = (function() {
  const _privateName = new WeakMap();
})();

III. Let's put all together.

let Name = (function() {
  const _privateName = new WeakMap();
  const _privateHello = function(fullName) {
    console.log("Hello, " + fullName);
  }

  class Name {
    constructor(firstName, lastName) {
      _privateName.set(this, {firstName: firstName, lastName: lastName});
    }
    static printName(name) {
      let privateName = _privateName.get(name);
      let _fullname = privateName.firstName + " " + privateName.lastName;
      _privateHello(_fullname);
    }
    printName() {
      let privateName = _privateName.get(this);
      let _fullname = privateName.firstName + " " + privateName.lastName;
      _privateHello(_fullname);
    }
  }

  return Name;
})();

var aMan = new Name("JH", "Son");
aMan.printName(); // "Hello, JH Son"
Name.printName(aMan); // "Hello, JH Son"

How to use EOF to run through a text file in C?

I would suggest you to use fseek-ftell functions.

FILE *stream = fopen("example.txt", "r");

if(!stream) {
    puts("I/O error.\n");
    return;
}

fseek(stream, 0, SEEK_END);
long size = ftell(stream);
fseek(stream, 0, SEEK_SET);

while(1) {

    if(ftell(stream) == size) {
        break;
    }

    /* INSERT ROUTINE */

}

fclose(stream);

Hide Twitter Bootstrap nav collapse on click

Bootstrap sets a .in class on the Collapse element to trigger the animation – to open it. If you simply remove the .in class, the animation doesn't run, but will hide the element – not exactly what you want.

Likely faster to run an if statement to check if the default bootstrap class .in has been set on the element.

So this code just says:

if my element has the class .in applied, close it by triggering the default Bootstrap animation. Otherwise run the default Bootstrap action/animation of opening it

$('#navbar a').on('click touchstart', function() {
    // if .in class is set on element, the element is visible – you want to hide it
    if ($('#navbar').hasClass('in')) {
        // collapse toggle will remove the .in class and animate the element closed 
        $('#navbar').collapse('toggle');
    }
})

if, elif, else statement issues in Bash

You have some syntax issues with your script. Here is a fixed version:

#!/bin/bash

if [ "$seconds" -eq 0 ]; then
   timezone_string="Z"
elif [ "$seconds" -gt 0 ]; then
   timezone_string=$(printf "%02d:%02d" $((seconds/3600)) $(((seconds / 60) % 60)))
else
   echo "Unknown parameter"
fi

How can I disable HREF if onclick is executed?

You can use this simple code:

<a href="" onclick="return false;">add new action</a><br>

How to get a microtime in Node.js?

A rewrite to help quick understanding:

const hrtime = process.hrtime();     // [0] is seconds, [1] is nanoseconds

let nanoSeconds = (hrtime[0] * 1e9) + hrtime[1];    // 1 second is 1e9 nano seconds
console.log('nanoSeconds:  ' + nanoSeconds);
//nanoSeconds:  97760957504895

let microSeconds = parseInt(((hrtime[0] * 1e6) + (hrtime[1]) * 1e-3));
console.log('microSeconds: ' + microSeconds);
//microSeconds: 97760957504

let milliSeconds = parseInt(((hrtime[0] * 1e3) + (hrtime[1]) * 1e-6));
console.log('milliSeconds: ' + milliSeconds);
//milliSeconds: 97760957

Source: https://nodejs.org/api/process.html#process_process_hrtime_time

Java: method to get position of a match in a String?

I have some big code but working nicely....

   class strDemo
   { 
       public static void main(String args[])
       {
       String s1=new String("The Ghost of The Arabean Sea");
           String s2=new String ("The");
           String s6=new String ("ehT");
           StringBuffer s3;
           StringBuffer s4=new StringBuffer(s1);
           StringBuffer s5=new StringBuffer(s2);
           char c1[]=new char[30];
           char c2[]=new char[5];
           char c3[]=new char[5];
           s1.getChars(0,28,c1,0);
           s2.getChars(0,3,c2,0);
           s6.getChars(0,3,c3,0); s3=s4.reverse();      
           int pf=0,pl=0;
           char c5[]=new char[30];
           s3.getChars(0,28,c5,0);
           for(int i=0;i<(s1.length()-s2.length());i++)
           {
               int j=0;
               if(pf<=1)
               {
                  while (c1[i+j]==c2[j] && j<=s2.length())
                  {           
                    j++;
                    System.out.println(s2.length()+" "+j);
                    if(j>=s2.length())
                    {
                       System.out.println("first match of(The) :->"+i);

                     }
                     pf=pf+1;         
                  }   
             }                
       }       
         for(int i=0;i<(s3.length()-s6.length()+1);i++)
        {
            int j=0;
            if(pl<=1)
            {
             while (c5[i+j]==c3[j] && j<=s6.length())
             {
                 j++;
                 System.out.println(s6.length()+" "+j);
                 if(j>=s6.length())
                 {
                         System.out.println((s3.length()-i-3));
                         pl=pl+1;

                 }   
                }                 
              }  
           }  
         }
       }

WCF - How to Increase Message Size Quota

For me, all I had to do is add maxReceivedMessageSize="2147483647" to the client app.config. The server left untouched.

How can I get a List from some class properties with Java 8 Stream?

You can use map :

List<String> names = 
    personList.stream()
              .map(Person::getName)
              .collect(Collectors.toList());

EDIT :

In order to combine the Lists of friend names, you need to use flatMap :

List<String> friendNames = 
    personList.stream()
              .flatMap(e->e.getFriends().stream())
              .collect(Collectors.toList());

Should I set max pool size in database connection string? What happens if I don't?

"currently yes but i think it might cause problems at peak moments" I can confirm, that I had a problem where I got timeouts because of peak requests. After I set the max pool size, the application ran without any problems. IIS 7.5 / ASP.Net

How to turn NaN from parseInt into 0 for an empty string?

Does the job a lot cleaner than parseInt in my opinion, Use the +operator

var s = '';
console.log(+s);

var s = '1024'
+s
1024

s = 0
+s
0

s = -1
+s
-1

s = 2.456
+s
2.456

s = ''
+s
0

s = 'wtf'
+s
NaN

Scroll to the top of the page after render in react.js

If I assume you are rendering a chapter of say, a book per page, all you need to do is add this to your code. This worked for me like magic.

    componentDidUpdate(prevProps) {
      if (prevProps.currentChapter !== this.props.currentChapter) {
        window.scrollTo(0, 0);
      }
    }

With this, you have no need creating a ref on the component being rendered.

Secure random token in Node.js

crypto-random-string is a nice module for this.

const cryptoRandomString = require('crypto-random-string');
 
cryptoRandomString({length: 10});
// => '2cf05d94db'
 
cryptoRandomString({length: 10, type: 'base64'});
// => 'YMiMbaQl6I'
 
cryptoRandomString({length: 10, type: 'url-safe'});
// => 'YN-tqc8pOw'
 
cryptoRandomString({length: 10, type: 'numeric'});
// => '8314659141'
 
cryptoRandomString({length: 6, type: 'distinguishable'});
// => 'CDEHKM'
 
cryptoRandomString({length: 10, type: 'ascii-printable'});
// => '`#Rt8$IK>B'
 
cryptoRandomString({length: 10, type: 'alphanumeric'});
// => 'DMuKL8YtE7'
 
cryptoRandomString({length: 10, characters: 'abc'});
// => 'abaaccabac'

cryptoRandomString.async(options) add .async if you want to get a promise.

Installing OpenCV 2.4.3 in Visual C++ 2010 Express

1. Installing OpenCV 2.4.3

First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\.

OpenCV self-extractor

Wait until all files get extracted. It will create a new directory C:\opencv which contains OpenCV header files, libraries, code samples, etc.

Now you need to add the directory C:\opencv\build\x86\vc10\bin to your system PATH. This directory contains OpenCV DLLs required for running your code.

Open Control PanelSystemAdvanced system settingsAdvanced Tab → Environment variables...

enter image description here

On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin; (3), then click Ok.

On some computers, you may need to restart your computer for the system to recognize the environment path variables.

This will completes the OpenCV 2.4.3 installation on your computer.


2. Create a new project and set up Visual C++

Open Visual C++ and select FileNewProject...Visual C++Empty Project. Give a name for your project (e.g: cvtest) and set the project location (e.g: c:\projects).

New project dialog

Click Ok. Visual C++ will create an empty project.

VC++ empty project

Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest and select PropertiesVC++ Directories.

Project property dialog

Select Include Directories to add a new entry and type C:\opencv\build\include.

Include directories dialog

Click Ok to close the dialog.

Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib.

Library directories dialog

Click Ok to close the dialog.

Back to the property dialog, select LinkerInputAdditional Dependencies to add new entries. On the popup dialog, type the files below:

opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib

Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).

enter image description here

Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.

NOTE:

These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to repeat adding the OpenCV directories and in Additional Dependencies section, use:

opencv_core243.lib
opencv_imgproc243.lib
...

instead of:

opencv_core243d.lib
opencv_imgproc243d.lib
...

You've done setting up Visual C++, now is the time to write the real code. Right click your project and select AddNew Item...Visual C++C++ File.

Add new source file

Name your file (e.g: loadimg.cpp) and click Ok. Type the code below in the editor:

#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main()
{
    Mat im = imread("c:/full/path/to/lena.jpg");
    if (im.empty()) 
    {
        cout << "Cannot load image!" << endl;
        return -1;
    }
    imshow("Image", im);
    waitKey(0);
}

The code above will load c:\full\path\to\lena.jpg and display the image. You can use any image you like, just make sure the path to the image is correct.

Type F5 to compile the code, and it will display the image in a nice window.

First OpenCV program

And that is your first OpenCV program!


3. Where to go from here?

Now that your OpenCV environment is ready, what's next?

  1. Go to the samples dir → c:\opencv\samples\cpp.
  2. Read and compile some code.
  3. Write your own code.

how to specify new environment location for conda create

Use the --prefix or -p option to specify where to write the environment files. For example:

conda create --prefix /tmp/test-env python=2.7

Will create the environment named /tmp/test-env which resides in /tmp/ instead of the default .conda.

Remove stubborn underline from link

None of the answers worked for me. In my case there was a standard

a:-webkit-any-link {
text-decoration: underline;

in my code. Basically whatever link it is, the text color goes blue, and the link stays whatever it is.

So I added the code at the end of the header like this:

<head>
  </style>
    a:-webkit-any-link {
      text-decoration: none;
    }
  </style>
</head>

and problem is no more.

iOS start Background Thread

If you use performSelectorInBackground:withObject: to spawn a new thread, then the performed selector is responsible for setting up the new thread's autorelease pool, run loop and other configuration details – see "Using NSObject to Spawn a Thread" in Apple's Threading Programming Guide.

You'd probably be better off using Grand Central Dispatch, though:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [self getResultSetFromDB:docids];
});

GCD is a newer technology, and is more efficient in terms of memory overhead and lines of code.


Updated with a hat tip to Chris Nolet, who suggested a change that makes the above code simpler and keeps up with Apple's latest GCD code examples.

how to log in to mysql and query the database from linux terminal

To your first question:

mysql -u root -p

or

mysqladmin -u root -p "your_command"

depending on what you want to do. The password will be asked of you once you hit enter! I'm guessing you really want to use mysql and not mysqladmin.

For restarting or stopping the MySQL-server on linux, it depends on your installation, but in the common debian derivatives this will work for starting, stopping and restarting the service:

sudo /etc/init.d/mysql start
sudo /etc/init.d/mysql stop
sudo /etc/init.d/mysql restart
sudo /etc/init.d/mysql status

In some newer distros this might work as well if MySQL is set up as a deamon/service.

sudo service mysql start
sudo service mysql stop
sudo service mysql restart
sudo service mysql status

But the question is really impossible to answer without knowing your particular setup.

How do I make Java register a string input with spaces?

This is a sample implementation of taking input in java, I added some fault tolerance on just the salary field to show how it's done. If you notice, you also have to close the input stream .. Enjoy :-)

/* AUTHOR: MIKEQ
 * DATE: 04/29/2016
 * DESCRIPTION: Take input with Java using Scanner Class, Wow, stunningly fun. :-) 
 * Added example of error check on salary input.
 * TESTED: Eclipse Java EE IDE for Web Developers. Version: Mars.2 Release (4.5.2) 
 */

import java.util.Scanner;

public class userInputVersion1 {

    public static void main(String[] args) {

    System.out.println("** Taking in User input **");

    Scanner input = new Scanner(System.in);
    System.out.println("Please enter your name : ");
    String s = input.nextLine(); // getting a String value (full line)
    //String s = input.next(); // getting a String value (issues with spaces in line)

    System.out.println("Please enter your age : ");
    int i = input.nextInt(); // getting an integer

    // version with Fault Tolerance:
    System.out.println("Please enter your salary : ");
    while (!input.hasNextDouble())
    {
        System.out.println("Invalid input\n Type the double-type number:");
        input.next();
    }
    double d = input.nextDouble();    // need to check the data type?

    System.out.printf("\nName %s" +
            "\nAge: %d" +
            "\nSalary: %f\n", s, i, d);

    // close the scanner
    System.out.println("Closing Scanner...");
    input.close();
    System.out.println("Scanner Closed.");      
}
}

Primary key or Unique index?

In MSSQL, Primary keys should be monotonically increasing for best performance on the clustered index. Therefore an integer with identity insert is better than any natural key that might not be monotonically increasing.

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

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

import datetime
import time  

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

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

Suppress output of a function

invisible(cat("Dataset: ", dataset, fill = TRUE))
invisible(cat(" Width: " ,width, fill = TRUE))
invisible(cat(" Bin1:  " ,bin1interval, fill = TRUE))
invisible(cat(" Bin2:  " ,bin2interval, fill = TRUE))
invisible(cat(" Bin3:  " ,bin3interval, fill = TRUE))

produces output without NULL at the end of the line or on the next line

Dataset:  17 19 26 29 31 32 34 45 47 51 52 59 60 62 63
Width:  15.33333

Bin1:   17 32.33333
Bin2:   32.33333 47.66667
Bin3:   47.66667 63

Laravel: Using try...catch with DB::transaction()

In the case you need to manually 'exit' a transaction through code (be it through an exception or simply checking an error state) you shouldn't use DB::transaction() but instead wrap your code in DB::beginTransaction and DB::commit/DB::rollback():

DB::beginTransaction();

try {
    DB::insert(...);
    DB::insert(...);
    DB::insert(...);

    DB::commit();
    // all good
} catch (\Exception $e) {
    DB::rollback();
    // something went wrong
}

See the transaction docs.

SQL Query - SUM(CASE WHEN x THEN 1 ELSE 0) for multiple columns

I think you should make a subquery to do grouping. In this case inner subquery returns few rows and you don't need a CASE statement. So I think this is going to be faster:

select Detail.ReceiptDate AS 'DATE',
       SUM(TotalMailed),
       SUM(TotalReturnMail),
       SUM(TraceReturnedMail)

from
(

select SentDate AS 'ReceiptDate', 
       count('TotalMailed') AS TotalMailed, 
       0 as TotalReturnMail, 
       0 as TraceReturnedMail
from MailDataExtract
where sentdate is not null
GROUP BY SentDate

UNION ALL
select MDE.ReturnMailDate AS 'ReceiptDate', 
       0 AS TotalMailed, 
       count(TotalReturnMail) as TotalReturnMail, 
       0 as TraceReturnedMail
from MailDataExtract MDE
where MDE.ReturnMailDate is not null
GROUP BY  MDE.ReturnMailDate

UNION ALL

select MDE.ReturnMailDate AS 'ReceiptDate', 
       0 AS TotalMailed, 
       0 as TotalReturnMail, 
       count(TraceReturnedMail) as TraceReturnedMail

from MailDataExtract MDE
    inner join DTSharedData.dbo.ScanData SD 
        ON SD.ScanDataID = MDE.ReturnScanDataID
   where MDE.ReturnMailDate is not null AND SD.ReturnMailTypeID = 1
GROUP BY MDE.ReturnMailDate

) as Detail
GROUP BY Detail.ReceiptDate
ORDER BY 1

Failed to start mongod.service: Unit mongod.service not found

The second step of mongo installation is

echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list

Instead of this command do it manually

  1. cd /etc/apt/
  2. nano sources.list
  3. Write it deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.4 multiverse

And save the file,

Continue all process as in installation docs

It works for me:

How to filter data in dataview

DataView view = new DataView();
view.Table = DataSet1.Tables["Suppliers"];
view.RowFilter = "City = 'Berlin'";
view.RowStateFilter = DataViewRowState.ModifiedCurrent;
view.Sort = "CompanyName DESC";

// Simple-bind to a TextBox control
Text1.DataBindings.Add("Text", view, "CompanyName");

Ref: http://www.csharp-examples.net/dataview-rowfilter/

http://msdn.microsoft.com/en-us/library/system.data.dataview.rowfilter.aspx

How do I implement onchange of <input type="text"> with jQuery?

$("input").change(function () {
    alert("Changed!");
});

How to make a flex item not fill the height of the flex container?

When you create a flex container various default flex rules come into play.

Two of these default rules are flex-direction: row and align-items: stretch. This means that flex items will automatically align in a single row, and each item will fill the height of the container.

If you don't want flex items to stretch – i.e., like you wrote:

make its height the minimum required for holding its content

... then simply override the default with align-items: flex-start.

_x000D_
_x000D_
#a {_x000D_
  display: flex;_x000D_
  align-items: flex-start; /* NEW */_x000D_
}_x000D_
#a > div {_x000D_
  background-color: red;_x000D_
  padding: 5px;_x000D_
  margin: 2px;_x000D_
}_x000D_
#b {_x000D_
  height: auto;_x000D_
}
_x000D_
<div id="a">_x000D_
  <div id="b">left</div>_x000D_
  <div>_x000D_
    right<br>right<br>right<br>right<br>right<br>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here's an illustration from the flexbox spec that highlights the five values for align-items and how they position flex items within the container. As mentioned before, stretch is the default value.

enter image description here Source: W3C

How to pass variable from jade template file to a script file?

It's a little late but...

script.
  loginName="#{login}";

This is working fine in my script. In Express, I am doing this:

exports.index = function(req, res){
  res.render( 'index',  { layout:false, login: req.session.login } );
};

I guess the latest jade is different?

Merc.

edit: added "." after script to prevent Jade warning.

SQL Server default character encoding

The default character encoding for a SQL Server database is iso_1, which is ISO 8859-1. Note that the character encoding depends on the data type of a column. You can get an idea of what character encodings are used for the columns in a database as well as the collations using this SQL:

select data_type, character_set_catalog, character_set_schema, character_set_name, collation_catalog, collation_schema, collation_name, count(*) count
from information_schema.columns
group by data_type, character_set_catalog, character_set_schema, character_set_name, collation_catalog, collation_schema, collation_name;

If it's using the default, the character_set_name should be iso_1 for the char and varchar data types. Since nchar and nvarchar store Unicode data in UCS-2 format, the character_set_name for those data types is UNICODE.

Creating an IFRAME using JavaScript

It is better to process HTML as a template than to build nodes via JavaScript (HTML is not XML after all.) You can keep your IFRAME's HTML syntax clean by using a template and then appending the template's contents into another DIV.

<div id="placeholder"></div>

<script id="iframeTemplate" type="text/html">
    <iframe src="...">
        <!-- replace this line with alternate content -->
    </iframe>
</script>

<script type="text/javascript">
var element,
    html,
    template;

element = document.getElementById("placeholder");
template = document.getElementById("iframeTemplate");
html = template.innerHTML;

element.innerHTML = html;
</script>

window.location.href doesn't redirect

Make sure you're not sending a '#' at the end of your URL. In my case, that was preventing window.location.href from working.

How do I write stderr to a file while using "tee" with a pipe?

This may be useful for people finding this via google. Simply uncomment the example you want to try out. Of course, feel free to rename the output files.

#!/bin/bash

STATUSFILE=x.out
LOGFILE=x.log

### All output to screen
### Do nothing, this is the default


### All Output to one file, nothing to the screen
#exec > ${LOGFILE} 2>&1


### All output to one file and all output to the screen
#exec > >(tee ${LOGFILE}) 2>&1


### All output to one file, STDOUT to the screen
#exec > >(tee -a ${LOGFILE}) 2> >(tee -a ${LOGFILE} >/dev/null)


### All output to one file, STDERR to the screen
### Note you need both of these lines for this to work
#exec 3>&1
#exec > >(tee -a ${LOGFILE} >/dev/null) 2> >(tee -a ${LOGFILE} >&3)


### STDOUT to STATUSFILE, stderr to LOGFILE, nothing to the screen
#exec > ${STATUSFILE} 2>${LOGFILE}


### STDOUT to STATUSFILE, stderr to LOGFILE and all output to the screen
#exec > >(tee ${STATUSFILE}) 2> >(tee ${LOGFILE} >&2)


### STDOUT to STATUSFILE and screen, STDERR to LOGFILE
#exec > >(tee ${STATUSFILE}) 2>${LOGFILE}


### STDOUT to STATUSFILE, STDERR to LOGFILE and screen
#exec > ${STATUSFILE} 2> >(tee ${LOGFILE} >&2)


echo "This is a test"
ls -l sdgshgswogswghthb_this_file_will_not_exist_so_we_get_output_to_stderr_aronkjegralhfaff
ls -l ${0}

HttpClient.GetAsync(...) never returns when using await/async

These two schools are not really excluding.

Here is the scenario where you simply have to use

   Task.Run(() => AsyncOperation()).Wait(); 

or something like

   AsyncContext.Run(AsyncOperation);

I have a MVC action that is under database transaction attribute. The idea was (probably) to roll back everything done in the action if something goes wrong. This does not allow context switching, otherwise transaction rollback or commit is going to fail itself.

The library I need is async as it is expected to run async.

The only option. Run it as a normal sync call.

I am just saying to each its own.

Change working directory in my current shell context when running Node script

The correct way to change directories is actually with process.chdir(directory). Here's an example from the documentation:

console.log('Starting directory: ' + process.cwd());
try {
  process.chdir('/tmp');
  console.log('New directory: ' + process.cwd());
}
catch (err) {
  console.log('chdir: ' + err);
}

This is also testable in the Node.js REPL:

[monitor@s2 ~]$ node
> process.cwd()
'/home/monitor'
> process.chdir('../');
undefined
> process.cwd();
'/home'

No converter found capable of converting from type to type

Turns out, when the table name is different than the model name, you have to change the annotations to:

@Entity
@Table(name = "table_name")
class WhateverNameYouWant {
    ...

Instead of simply using the @Entity annotation.

What was weird for me, is that the class it was trying to convert to didn't exist. This worked for me.

Measuring code execution time

Stopwatch is designed for this purpose and is one of the best way to measure execution time in .NET.

var watch = System.Diagnostics.Stopwatch.StartNew();
/* the code that you want to measure comes here */
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;

Do not use DateTimes to measure execution time in .NET.

How to check type of files without extensions in python?

There are Python libraries that can recognize files based on their content (usually a header / magic number) and that don't rely on the file name or extension.

If you're addressing many different file types, you can use python-magic. That's just a Python binding for the well-established magic library. This has a good reputation and (small endorsement) in the limited use I've made of it, it has been solid.

There are also libraries for more specialized file types. For example, the Python standard library has the imghdr module that does the same thing just for image file types.

If you need dependency-free (pure Python) file type checking, see filetype.

How to return a result from a VBA function

VBA functions treat the function name itself as a sort of variable. So instead of using a "return" statement, you would just say:

test = 1

Notice, though, that this does not break out of the function. Any code after this statement will also be executed. Thus, you can have many assignment statements that assign different values to test, and whatever the value is when you reach the end of the function will be the value returned.

How to make a custom LinkedIn share button

The API is updated now and the previous API will be deprecated on 1st March, 2019.

To create a custom Share button for LinkedIn, you need to make POST calls now. You can read the updated documentation here for doing so.

Trying to add adb to PATH variable OSX

I use zsh and Android Studio. I use a variable for my Android SDK path and configure in the file ~/.zshrc:

export ANDROID_HOME=/Applications/Android\ Studio.app/sdk
export PATH="$ANDROID_HOME/platform-tools:$ANDROID_HOME/tools:$PATH"

Note: Make sure not to include single or double quotes around the specified path. If you do, it won't work.

Merge some list items in a Python List

Of course @Stephan202 has given a really nice answer. I am providing an alternative.

def compressx(min_index = 3, max_index = 6, x = ['a', 'b', 'c', 'd', 'e', 'f', 'g']):
    x = x[:min_index] + [''.join(x[min_index:max_index])] + x[max_index:]
    return x
compressx()

>>>['a', 'b', 'c', 'def', 'g']

You can also do the following.

x = x[:min_index] + [''.join(x[min_index:max_index])] + x[max_index:]
print(x)

>>>['a', 'b', 'c', 'def', 'g']

SMTP server response: 530 5.7.0 Must issue a STARTTLS command first

I had a false response for the following:

fputs($connection, 'STARTTLS'.$newLine);

turns out I use the wrong connection variable, so I just had to change it to:

fputs($smtpConnect, 'STARTTLS'.$newLine);

If using TLS remember to put HELO before and after:

fputs($smtpConnect, 'HELO '.$localhost . $newLine);
$response = fgets($smtpConnect, 515);
if($secure == 'tls')
{
    fputs($smtpConnect, 'STARTTLS'.$newLine);
    $response = fgets($smtpConnect, 515);
stream_socket_enable_crypto($smtpConnect, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);

// Say hello again!
    fputs($smtpConnect, 'HELO '.$localhost . $newLine);
    $response = fgets($smtpConnect, 515);
}

How to download a file from a website in C#

Also you can use DownloadFileAsync method in WebClient class. It downloads to a local file the resource with the specified URI. Also this method does not block the calling thread.

Sample:

    webClient.DownloadFileAsync(new Uri("http://www.example.com/file/test.jpg"), "test.jpg");

For more information:

http://csharpexamples.com/download-files-synchronous-asynchronous-url-c/

mysql update column with value from another table

In addition to this answer if you need to change tableB.value according to tableA.value dynamically you can do for example:

UPDATE tableB
INNER JOIN tableA ON tableB.name = tableA.name
SET tableB.value = IF(tableA.value > 0, tableA.value, tableB.value)
WHERE tableA.name = 'Joe'

What is the difference between JOIN and UNION?

JOIN:

A join is used for displaying columns with the same or different names from different tables. The output displayed will have all the columns shown individually. That is, the columns will be aligned next to each other.

UNION:

The UNION set operator is used for combining data from two tables which have columns with the same datatype. When a UNION is performed the data from both tables will be collected in a single column having the same datatype.

For example:

See the two tables shown below:

Table t1
Articleno article price manufacturer_id
1 hammer 3 $ 1
2 screwdriver 5 $ 2

Table t2
manufacturer_id manufacturer
1 ABC Gmbh
2 DEF Co KG

Now for performing a JOIN type the query is shown below.

SELECT articleno, article, manufacturer
FROM t1 JOIN t2 ON (t1.manufacturer_id =
t2.manufacturer_id);

articelno article manufacturer
1 hammer ABC GmbH
2 screwdriver DEF Co KG

That is a join.

UNION means that you have to tables or resultset with the same amount and type of columns and you add this to tables/resultsets together. Look at this example:

Table year2006
Articleno article price manufacturer_id
1 hammer 3 $ 1
2 screwdriver 5 $ 2

Table year2007
Articleno article price manufacturer_id
1 hammer 6 $ 3
2 screwdriver 7 $ 4

SELECT articleno, article, price, manufactruer_id
FROM year2006
UNION
SELECT articleno, article, price, manufacturer_id
FROM year2007

articleno article price manufacturer_id
1 hammer 3 $ 1
2 screwdriver 5 $ 2
1 hammer 6 $ 3
2 screwdriver 7 $ 4

Linux configure/make, --prefix?

Do configure --help and see what other options are available.

It is very common to provide different options to override different locations. By standard, --prefix overrides all of them, so you need to override config location after specifying the prefix. This course of actions usually works for every automake-based project.

The worse case scenario is when you need to modify the configure script, or even worse, generated makefiles and config.h headers. But yeah, for Xfce you can try something like this:

./configure --prefix=/home/me/somefolder/mybuild/output/target --sysconfdir=/etc 

I believe that should do it.

String contains another two strings

Because b + a ="someonedamage", try this to achieve :

if (d.Contains(b) && d.Contains(a))
{  
    Console.WriteLine(" " + d);
    Console.ReadLine();
}

git submodule tracking latest

Edit (2020.12.28): GitHub change default master branch to main branch since October 2020. See https://github.com/github/renaming


Update March 2013

Git 1.8.2 added the possibility to track branches.

"git submodule" started learning a new mode to integrate with the tip of the remote branch (as opposed to integrating with the commit recorded in the superproject's gitlink).

# add submodule to track master branch
git submodule add -b master [URL to Git repo];

# update your submodule
git submodule update --remote 

If you had a submodule already present you now wish would track a branch, see "how to make an existing submodule track a branch".

Also see Vogella's tutorial on submodules for general information on submodules.

Note:

git submodule add -b . [URL to Git repo];
                    ^^^

See git submodule man page:

A special value of . is used to indicate that the name of the branch in the submodule should be the same name as the current branch in the current repository.


See commit b928922727d6691a3bdc28160f93f25712c565f6:

submodule add: If --branch is given, record it in .gitmodules

This allows you to easily record a submodule.<name>.branch option in .gitmodules when you add a new submodule. With this patch,

$ git submodule add -b <branch> <repository> [<path>]
$ git config -f .gitmodules submodule.<path>.branch <branch>

reduces to

$ git submodule add -b <branch> <repository> [<path>]

This means that future calls to

$ git submodule update --remote ...

will get updates from the same branch that you used to initialize the submodule, which is usually what you want.

Signed-off-by: W. Trevor King [email protected]


Original answer (February 2012):

A submodule is a single commit referenced by a parent repo.
Since it is a Git repo on its own, the "history of all commits" is accessible through a git log within that submodule.

So for a parent to track automatically the latest commit of a given branch of a submodule, it would need to:

  • cd in the submodule
  • git fetch/pull to make sure it has the latest commits on the right branch
  • cd back in the parent repo
  • add and commit in order to record the new commit of the submodule.

gitslave (that you already looked at) seems to be the best fit, including for the commit operation.

It is a little annoying to make changes to the submodule due to the requirement to check out onto the correct submodule branch, make the change, commit, and then go into the superproject and commit the commit (or at least record the new location of the submodule).

Other alternatives are detailed here.

Request string without GET arguments

$uri_parts = explode('?', $_SERVER['REQUEST_URI'], 2);
$request_uri = $uri_parts[0];
echo $request_uri;

How to check if a file exists in Documents folder?

Apple recommends against relying on the fileExistAtPath: method. It's often better to just try to open a file and deal with the error if the file does not exist.

NSFileManager Class Reference

Note: Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. Doing so can cause odd behavior or race conditions. It's far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle those errors gracefully than it is to try to figure out ahead of time whether the operation will succeed. For more information on file system race conditions, see “Race Conditions and Secure File Operations” in Secure Coding Guide.

Source: Apple Developer API Reference

From the secure coding guide.

To prevent this, programs often check to make sure a temporary file with a specific name does not already exist in the target directory. If such a file exists, the application deletes it or chooses a new name for the temporary file to avoid conflict. If the file does not exist, the application opens the file for writing, because the system routine that opens a file for writing automatically creates a new file if none exists. An attacker, by continuously running a program that creates a new temporary file with the appropriate name, can (with a little persistence and some luck) create the file in the gap between when the application checked to make sure the temporary file didn’t exist and when it opens it for writing. The application then opens the attacker’s file and writes to it (remember, the system routine opens an existing file if there is one, and creates a new file only if there is no existing file). The attacker’s file might have different access permissions than the application’s temporary file, so the attacker can then read the contents. Alternatively, the attacker might have the file already open. The attacker could replace the file with a hard link or symbolic link to some other file (either one owned by the attacker or an existing system file). For example, the attacker could replace the file with a symbolic link to the system password file, so that after the attack, the system passwords have been corrupted to the point that no one, including the system administrator, can log in.

Adding data attribute to DOM

jQuery's .data() does a couple things but it doesn't add the data to the DOM as an attribute. When using it to grab a data attribute, the first thing it does is create a jQuery data object and sets the object's value to the data attribute. After that, it's essentially decoupled from the data attribute.

Example:

<div data-foo="bar"></div>

If you grabbed the value of the attribute using .data('foo'), it would return "bar" as you would expect. If you then change the attribute using .attr('data-foo', 'blah') and then later use .data('foo') to grab the value, it would return "bar" even though the DOM says data-foo="blah". If you use .data() to set the value, it'll change the value in the jQuery object but not in the DOM.

Basically, .data() is for setting or checking the jQuery object's data value. If you are checking it and it doesn't already have one, it creates the value based on the data attribute that is in the DOM. .attr() is for setting or checking the DOM element's attribute value and will not touch the jQuery data value. If you need them both to change you should use both .data() and .attr(). Otherwise, stick with one or the other.

Settings to Windows Firewall to allow Docker for Windows to share drive

I tried everything listed here and on https://github.com/docker/for-win/issues/360

Nothing worked for me.

I run my dev environment on a docker container, and while on Corporate VPN (Cisco AnyConnect), I need the to mount my local drive on the container to access my project files.

Here's a docker hack that worked for me. Add --publish 8000:8000 to your existing docker run command.

So

docker run -v C:/Users/kumar.joshi/KumarData:/mnt --name dev <image:latest>

will become

docker run -v C:/Users/kumar.joshi/KumarData:/mnt --name dev --publish 8000:8000 <image:latest>

Make sure the port is not used else you will get this error:

Bind for 0.0.0.0:8000 failed: port is already allocated

Center button under form in bootstrap

If you're using Bootstrap 4, try this:

<div class="mx-auto text-center">
    <button id="button" name="button" class="btn btn-primary">Press Me!</button>
</div>

Use different Python version with virtualenv

I use pyenv to manage my python version.

pyenv install 3.7.3
pyenv local 3.7.3

Check your python version:

$ python --version
Python 3.7.3

Create the virtual environment with venv:

python -m venv .

Then activate the Virtual Environment:

source bin/activate

Check your python version:

$ python --version
Python 3.7.3

You may need to remove the previous virtual environment

rm -rf bin

Remove blank attributes from an Object in Javascript

you can do shorter with ! condition

var r = {a: null, b: undefined, c:1};
for(var k in r)
   if(!r[k]) delete r[k];

Remember in usage : as @semicolor announce in comments: This would also delete properties if the value is an empty string, false or zero

Fragments within Fragments

If you find your nested fragment not being removed or being duplicated (eg. on Activity restart, on screen rotate) try changing:

transaction.add(R.id.placeholder, newFragment);

to

transaction.replace(R.id.placeholder, newFragment);

If above doesn't help, try:

Fragment f = getChildFragmentManager().findFragmentById(R.id.placeholder);

FragmentTransaction transaction = getChildFragmentManager().beginTransaction();

if (f == null) {
    Log.d(TAG, "onCreateView: fragment doesn't exist");
    newFragment= new MyFragmentType();
    transaction.add(R.id.placeholder, newFragment);
} else {
    Log.d(TAG, "onCreateView: fragment already exists");
    transaction.replace(R.id.placeholder, f);
}
transaction.commit();

Learnt here

Disable a Button

For those who Googled "disable a button" but may have more nuanced use cases:

Disable with visual effect: As others have said, this will prevent the button from being pressed and the system will automatically make it look disabled:

yourButton.isEnabled = false 

Disable without visual effect: Are you using a button in a case where it should look normal but not behave likes button by reacting to touches? Try this!

yourButton.userInteractionEnabled = false

Hide without disabling: This approach hides the button without disabling it (invisible but can still be tapped):

 yourButton.alpha = 0.0

Remove: This will remove the view entirely:

 yourButton.removeFromSuperView()

Tap something behind a button: Have two buttons stacked and you want the top button to temporarily act like it's not there? If you won't need the top button again, remove it. If you will need it again, try condensing its height or width to 0!

How can I set the max-width of a table cell using percentages?

the percent should be relative to an absolute size, try this :

_x000D_
_x000D_
table {
  width:200px;
}

td {
  width:65%;
  border:1px solid black;
}
_x000D_
<table>
  <tr>
    <td>Testasdas 3123 1 dasd as da</td>
    <td>A long string blah blah blah</td>
  </tr>
</table>
    
_x000D_
_x000D_
_x000D_

Open source face recognition for Android

You use class media.FaceDetector in android to detect face for free.

This is an example of face detection: https://github.com/betri28/FaceDetectCamera

WRONGTYPE Operation against a key holding the wrong kind of value php

Redis supports 5 data types. You need to know what type of value that a key maps to, as for each data type, the command to retrieve it is different.

Here are the commands to retrieve key value:

  • if value is of type string -> GET <key>
  • if value is of type hash -> HGETALL <key>
  • if value is of type lists -> lrange <key> <start> <end>
  • if value is of type sets -> smembers <key>
  • if value is of type sorted sets -> ZRANGEBYSCORE <key> <min> <max>

Use the TYPE command to check the type of value a key is mapping to:

  • type <key>

TortoiseSVN Error: "OPTIONS of 'https://...' could not connect to server (...)"

make sure when you add your proxy entries to the server file, you add them under the [global] group. (That seemed to make the difference for me under ubuntu.)

Change a branch name in a Git repo

If you're currently on the branch you want to rename:

git branch -m new_name 

Or else:

git branch -m old_name new_name 

You can check with:

git branch -a

As you can see, only the local name changed Now, to change the name also in the remote you must do:

git push origin :old_name

This removes the branch, then upload it with the new name:

git push origin new_name

Source: https://web.archive.org/web/20150929104013/http://blog.changecong.com:80/2012/10/rename-a-remote-branch-on-github

ORA-12528: TNS Listener: all appropriate instances are blocking new connections. Instance "CLRExtProc", status UNKNOWN

If you are using 11G XE with Windows, along with tns listener restart, make sure Windows Event Log service is started.

Failed to open the HAX device! HAX is not working and emulator runs in emulation mode emulator

I had the same problem recently.

First you need to install HAXM in the Android SDK Manager (from the error message I think you already did that). This will enable the emulator to use the HAXM framework, and for this it needs to open the HAX device. On your system this cannot be found, hence the error message.

To make this device available, you need to install the HAXM driver from Intel. You can find it here: http://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager (You also need to enable virtualization in your computer BIOS).

Hope this helps.

How to enable C# 6.0 feature in Visual Studio 2013?

A lot of the answers here were written prior to Roslyn (the open-source .NET C# and VB compilers) moving to .NET 4.6. So they won't help you if your project targets, say, 4.5.2 as mine did (inherited and can't be changed).

But you can grab a previous version of Roslyn from https://www.nuget.org/packages/Microsoft.Net.Compilers and install that instead of the latest version. I used 1.3.2. (I tried 2.0.1 - which appears to be the last version that runs on .NET 4.5 - but I couldn't get it to compile*.) Run this from the Package Manager console in VS 2013:

PM> Install-Package Microsoft.Net.Compilers -Version 1.3.2

Then restart Visual Studio. I had a couple of problems initially; you need to set the C# version back to default (C#6.0 doesn't appear in the version list but seems to have been made the default), then clean, save, restart VS and recompile.

Interestingly, I didn't have any IntelliSense errors due to the C#6.0 features used in the code (which were the reason for wanting C#6.0 in the first place).

* version 2.0.1 threw error The "Microsoft.CodeAnalysis.BuildTasks.Csc task could not be loaded from the assembly Microsoft.Build.Tasks.CodeAnalysis.dll. Could not load file or assembly 'Microsoft.Build.Utilities.Core, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified. Confirm that the declaration is correct, that the assembly and all its dependencies are available, and that the task contains a public class that implements Microsoft.Build.Framework.ITask.

UPDATE One thing I've noticed since posting this answer is that if you change any code during debug ("Edit and Continue"), you'll like find that your C#6.0 code will suddenly show as errors in what seems to revert to a pre-C#6.0 environment. This requires a restart of your debug session. VERY annoying especially for web applications.

How to return a complex JSON response with Node.js?

On express 3 you can use directly res.json({foo:bar})

res.json({ msgId: msg.fileName })

See the documentation

Loop through files in a directory using PowerShell

To get the content of a directory you can use

$files = Get-ChildItem "C:\Users\gerhardl\Documents\My Received Files\"

Then you can loop over this variable as well:

for ($i=0; $i -lt $files.Count; $i++) {
    $outfile = $files[$i].FullName + "out" 
    Get-Content $files[$i].FullName | Where-Object { ($_ -match 'step4' -or $_ -match 'step9') } | Set-Content $outfile
}

An even easier way to put this is the foreach loop (thanks to @Soapy and @MarkSchultheiss):

foreach ($f in $files){
    $outfile = $f.FullName + "out" 
    Get-Content $f.FullName | Where-Object { ($_ -match 'step4' -or $_ -match 'step9') } | Set-Content $outfile
}

Is it possible to remove the focus from a text input when a page loads?

A jQuery solution would be something like:

$(function () {
    $('input').blur();
});

jQuery scrollTop not working in Chrome but working in Firefox

// if we are not already in top then see if browser needs html or body as selector
var obj = $('html').scrollTop() !== 0 ? 'html' : 'body';

// then proper delegate using on, with following line:
$(obj).animate({ scrollTop: 0 }, "slow");

BUT, best approach is to scroll an id into your viewport using just native api (since you scroll to top anyway this can be just your outer div):

document.getElementById('wrapperIDhere').scrollIntoView(true);

Running powershell script within python script, how to make python print the powershell output while it is running

  1. Make sure you can run powershell scripts (it is disabled by default). Likely you have already done this. http://technet.microsoft.com/en-us/library/ee176949.aspx

    Set-ExecutionPolicy RemoteSigned
    
  2. Run this python script on your powershell script helloworld.py:

    # -*- coding: iso-8859-1 -*-
    import subprocess, sys
    
    p = subprocess.Popen(["powershell.exe", 
                  "C:\\Users\\USER\\Desktop\\helloworld.ps1"], 
                  stdout=sys.stdout)
    p.communicate()
    

This code is based on python3.4 (or any 3.x series interpreter), though it should work on python2.x series as well.

C:\Users\MacEwin\Desktop>python helloworld.py
Hello World

HttpClient not supporting PostAsJsonAsync method C#

If you are already using Newtonsoft.Json try this:

  // Alternative using WebApi.Client 5.2.7
  ////var response = await Client.PutAsJsonAsync(
  ////    "api/AgentCollection", user
  ////    requestListDto)

  var response = await Client.PostAsync("api/AgentCollection", new StringContent(
    JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json"));

Performance are better than JavaScriptSerializer. Take a look here https://www.newtonsoft.com/json/help/html/Introduction.htm

Get item in the list in Scala?

Why parentheses?

Here is the quote from the book programming in scala.

Another important idea illustrated by this example will give you insight into why arrays are accessed with parentheses in Scala. Scala has fewer special cases than Java. Arrays are simply instances of classes like any other class in Scala. When you apply parentheses surrounding one or more values to a variable, Scala will transform the code into an invocation of a method named apply on that variable. So greetStrings(i) gets transformed into greetStrings.apply(i). Thus accessing an element of an array in Scala is simply a method call like any other. This principle is not restricted to arrays: any application of an object to some arguments in parentheses will be transformed to an apply method call. Of course this will compile only if that type of object actually defines an apply method. So it's not a special case; it's a general rule.

Here are a few examples how to pull certain element (first elem in this case) using functional programming style.

  // Create a multdimension Array 
  scala> val a = Array.ofDim[String](2, 3)
  a: Array[Array[String]] = Array(Array(null, null, null), Array(null, null, null))
  scala> a(0) = Array("1","2","3")
  scala> a(1) = Array("4", "5", "6")
  scala> a
  Array[Array[String]] = Array(Array(1, 2, 3), Array(4, 5, 6))

  // 1. paratheses
  scala> a.map(_(0))
  Array[String] = Array(1, 4)
  // 2. apply
  scala> a.map(_.apply(0))
  Array[String] = Array(1, 4)
  // 3. function literal
  scala> a.map(a => a(0))
  Array[String] = Array(1, 4)
  // 4. lift
  scala> a.map(_.lift(0))
  Array[Option[String]] = Array(Some(1), Some(4))
  // 5. head or last 
  scala> a.map(_.head)
  Array[String] = Array(1, 4)

Getting The ASCII Value of a character in a C# string

This example might help you. by using simple casting you can get code behind urdu character.

string str = "?????";
        char ch = ' ';
        int number = 0;
        for (int i = 0; i < str.Length; i++)
        {
            ch = str[i];
            number = (int)ch;
            Console.WriteLine(number);
        }

What is WebKit and how is it related to CSS?

WebKit is a layout engine designed to allow web browsers to render web pages. The WebKit engine provides a set of classes to display web content in windows, and implements browser features such as following links when clicked by the user, managing a back-forward list, and managing a history of pages recently visited.

WebKit was originally created as a fork of KHTML as the layout engine for Apple's Safari; it is portable to many other computing platforms. It is also used in Google's Chrome Browser.

WebKit's WebCore and JavaScriptCore components are available under the GNU Lesser General Public License, and the rest of WebKit is available under a BSD-style license.

Source Wikipedia

For further information about layout engines you can look here

How do I get the current timezone name in Postgres 9.3?

You can access the timezone by the following script:

SELECT * FROM pg_timezone_names WHERE name = current_setting('TIMEZONE');
  • current_setting('TIMEZONE') will give you Continent / Capital information of settings
  • pg_timezone_names The view pg_timezone_names provides a list of time zone names that are recognized by SET TIMEZONE, along with their associated abbreviations, UTC offsets, and daylight-savings status.
  • name column in a view (pg_timezone_names) is time zone name.

output will be :

name- Europe/Berlin, 
abbrev - CET, 
utc_offset- 01:00:00, 
is_dst- false

Hex to ascii string conversion

Few characters like alphabets i-o couldn't be converted into respective ASCII chars . like in string '6631653064316f30723161' corresponds to fedora . but it gives fedra

Just modify hex_to_int() function a little and it will work for all characters. modified function is

int hex_to_int(char c)
{
    if (c >= 97)
        c = c - 32;
    int first = c / 16 - 3;
    int second = c % 16;
    int result = first * 10 + second;
    if (result > 9) result--;
    return result;
}

Now try it will work for all characters.

NumPy first and last element from array

arr = np.array([1,2,3,4])
arr[-1] # last element

Find all files with a filename beginning with a specified string?

If you want to restrict your search only to files you should consider to use -type f in your search

try to use also -iname for case-insensitive search

Example:

find /path -iname 'yourstring*' -type f

You could also perform some operations on results without pipe sign or xargs

Example:

Search for files and show their size in MB

find /path -iname 'yourstring*' -type f -exec du -sm {} \;

How do I get list of methods in a Python class?

If your method is a "regular" method and not a staticmethod, classmethod etc.
There is a little hack I came up with -

for k, v in your_class.__dict__.items():
    if "function" in str(v):
        print(k)

This can be extended to other type of methods by changing "function" in the if condition correspondingly.
Tested in Python 2.7 and Python 3.5.

select records from postgres where timestamp is in certain range

Another option to make PostgreSQL use an index for your original query, is to create an index on the expression you are using:

create index arrival_year on reservations ( extract(year from arrival) );

That will open PostgreSQL with the possibility to use an index for

select * 
FROM reservations 
WHERE extract(year from arrival) = 2012;

Note that the expression in the index must be exactly the same expression as used in the where clause to make this work.

Check if record exists from controller in Rails

Why your code does not work?

The where method returns an ActiveRecord::Relation object (acts like an array which contains the results of the where), it can be empty but it will never be nil.

Business.where(id: -1) 
 #=> returns an empty ActiveRecord::Relation ( similar to an array )
Business.where(id: -1).nil? # ( similar to == nil? )
 #=> returns false
Business.where(id: -1).empty? # test if the array is empty ( similar to .blank? )
 #=> returns true

How to test if at least one record exists?

Option 1: Using .exists?

if Business.exists?(user_id: current_user.id)
  # same as Business.where(user_id: current_user.id).exists?
  # ...
else
  # ...
end

Option 2: Using .present? (or .blank?, the opposite of .present?)

if Business.where(:user_id => current_user.id).present?
  # less efficiant than using .exists? (see generated SQL for .exists? vs .present?)
else
  # ...
end

Option 3: Variable assignment in the if statement

if business = Business.where(:user_id => current_user.id).first
  business.do_some_stuff
else
  # do something else
end

This option can be considered a code smell by some linters (Rubocop for example).

Option 3b: Variable assignment

business = Business.where(user_id: current_user.id).first
if business
  # ...
else
  # ...
end

You can also use .find_by_user_id(current_user.id) instead of .where(...).first


Best option:

  • If you don't use the Business object(s): Option 1
  • If you need to use the Business object(s): Option 3

Android 'Unable to add window -- token null is not for an application' exception

Try getParent() at the argument place of context like new AlertDialog.Builder(getParent()); Hope it will work, it worked for me.

Load local javascript file in chrome for testing?

Not sure why @user3133050 is voted down, that's all you need to do...

Here's the structure you need, based on your script tag's src, assuming you are trying to load moment.js into index.html:

/js/moment.js
/some-other-directory/index.html

The ../ looks "up" at the "some-other-directory" folder level, finds the js folder next to it, and loads the moment.js inside.

It sounds like your index.html is at root level, or nested even deeper.

If you're still struggling, create a test.js file in the same location as index.html, and add a <script src="test.js"></script> and see if that loads. If that fails, check your syntax. Tested in Chrome 46.

Python 2,3 Convert Integer to "bytes" Cleanly

You can use the struct's pack:

In [11]: struct.pack(">I", 1)
Out[11]: '\x00\x00\x00\x01'

The ">" is the byte-order (big-endian) and the "I" is the format character. So you can be specific if you want to do something else:

In [12]: struct.pack("<H", 1)
Out[12]: '\x01\x00'

In [13]: struct.pack("B", 1)
Out[13]: '\x01'

This works the same on both python 2 and python 3.

Note: the inverse operation (bytes to int) can be done with unpack.

Make sure that the controller has a parameterless public constructor error

What's happening is that you're bitten by this problem. Basically, what happened is that you didn't register your controllers explicitly in your container. Unity tries to resolve unregistered concrete types for you, but because it can't resolve it (caused by an error in your configuration), it return null. It is forced to return null, because Web API forces it to do so due to the IDependencyResolver contract. Since Unity returns null, Web API will try to create the controller itself, but since it doesn't have a default constructor it will throw the "Make sure that the controller has a parameterless public constructor" exception. This exception message is misleading and doesn't explain the real cause.

You would have seen a much clearer exception message if you registered your controllers explicitly, and that's why you should always register all root types explicitly.

But of course, the configuration error comes from you adding the second constructor to your DbContext. Unity always tries to pick the constructor with the most arguments, but it has no idea how to resolve this particular constructor.

So the real cause is that you are trying to use Unity's auto-wiring capabilities to create the DbContext. DbContext is a special type that shouldn't be auto-wired. It is a framework type and you should therefore fallback to registering it using a factory delegate:

container.Register<DashboardDbContext>(
    new InjectionFactory(c => new DashboardDbContext())); 

How can I select all children of an element except the last child?

You can use the negation pseudo-class :not() against the :last-child pseudo-class. Being introduced CSS Selectors Level 3, it doesn't work in IE8 or below:

:not(:last-child) { /* styles */ }

Send POST data using XMLHttpRequest

There's some duplicates that touch on this, and nobody really expounds on it. I'll borrow the accepted answer example to illustrate

http.open('POST', url, true);
http.send('lorem=ipsum&name=binny');

I oversimplified this (I use http.onload(function() {}) instead of that answer's older methodology) for the sake of illustration. If you use this as-is, you'll find your server is probably interpreting the POST body as a string and not actual key=value parameters (i.e. PHP won't show any $_POST variables). You must pass the form header in to get that, and do that before http.send()

http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

If you're using JSON and not URL-encoded data, pass application/json instead

Java ResultSet how to check if there are any results

I think the easiest way for checking result set is via CollectionUtils under package org.apache.commons.collections.CollectionUtils

if(CollectionUtils.isNotEmpty(resultList)){
  /**
  * do some stuff
  */
}

This will check for null as well as empty result set condition.

For more detail information you can refer to the following doc. CollectionUtils

type checking in javascript

Try this code:

 alert(typeof(1) == "number");

How can I ssh directly to a particular directory?

going one step further with the -t idea. I keep a set of scripts calling the one below to go to specific places in my frequently visited hosts. I keep them all in ~/bin and keep that directory in my path.

#!/bin/bash

# does ssh session switching to particular directory
# $1, hostname from config file 
# $2, directory to move to after login
# can save this as say 'con' then
# make another script calling this one, e.g.
# con myhost repos/i2c

ssh -t $1 "cd $2; exec \$SHELL --login"

Remove certain characters from a string

One issue with REPLACE will be where city names contain the district name. You can use something like.

SELECT SUBSTRING(O.Ort, LEN(C.CityName) + 2, 8000)
FROM   dbo.tblOrtsteileGeo O
       JOIN dbo.Cities C
         ON C.foo = O.foo
WHERE  O.GKZ = '06440004' 

Call method when home button pressed

The Home button is a very dangerous button to override and, because of that, Android will not let you override its behavior the same way you do the BACK button.

Take a look at this discussion.

You will notice that the home button seems to be implemented as a intent invocation, so you'll end up having to add an intent category to your activity. Then, any time the user hits home, your app will show up as an option. You should consider what it is you are looking to accomplish with the home button. If its not to replace the default home screen of the device, I would be wary of overloading the HOME button, but it is possible (per discussion in above thread.)

How to customize Bootstrap 3 tab color

I think you should edit the anchor tag on bootstrap.css. Otherwise give customized style to the anchor tag with !important (to override the default style on bootstrap.css).

Example code

_x000D_
_x000D_
.nav {_x000D_
    background-color: #000 !important;_x000D_
}_x000D_
_x000D_
.nav>li>a {_x000D_
    background-color: #666 !important;_x000D_
    color: #fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">_x000D_
_x000D_
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<div role="tabpanel">_x000D_
_x000D_
  <!-- Nav tabs -->_x000D_
  <ul class="nav nav-tabs" role="tablist">_x000D_
    <li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Home</a></li>_x000D_
    <li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">Profile</a></li>_x000D_
    <li role="presentation"><a href="#messages" aria-controls="messages" role="tab" data-toggle="tab">Messages</a></li>_x000D_
    <li role="presentation"><a href="#settings" aria-controls="settings" role="tab" data-toggle="tab">Settings</a></li>_x000D_
  </ul>_x000D_
_x000D_
  <!-- Tab panes -->_x000D_
  <div class="tab-content">_x000D_
    <div role="tabpanel" class="tab-pane active" id="home">...</div>_x000D_
    <div role="tabpanel" class="tab-pane" id="profile">tab1</div>_x000D_
    <div role="tabpanel" class="tab-pane" id="messages">tab2</div>_x000D_
    <div role="tabpanel" class="tab-pane" id="settings">tab3</div>_x000D_
  </div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fiddle: http://jsfiddle.net/zjjpocv6/2/

Java8: HashMap<X, Y> to HashMap<X, Z> using Stream / Map-Reduce / Collector

Here are some variations on Sotirios Delimanolis' answer, which was pretty good to begin with (+1). Consider the following:

static <X, Y, Z> Map<X, Z> transform(Map<? extends X, ? extends Y> input,
                                     Function<Y, Z> function) {
    return input.keySet().stream()
        .collect(Collectors.toMap(Function.identity(),
                                  key -> function.apply(input.get(key))));
}

A couple points here. First is the use of wildcards in the generics; this makes the function somewhat more flexible. A wildcard would be necessary if, for example, you wanted the output map to have a key that's a superclass of the input map's key:

Map<String, String> input = new HashMap<String, String>();
input.put("string1", "42");
input.put("string2", "41");
Map<CharSequence, Integer> output = transform(input, Integer::parseInt);

(There is also an example for the map's values, but it's really contrived, and I admit that having the bounded wildcard for Y only helps in edge cases.)

A second point is that instead of running the stream over the input map's entrySet, I ran it over the keySet. This makes the code a little cleaner, I think, at the cost of having to fetch values out of the map instead of from the map entry. Incidentally, I initially had key -> key as the first argument to toMap() and this failed with a type inference error for some reason. Changing it to (X key) -> key worked, as did Function.identity().

Still another variation is as follows:

static <X, Y, Z> Map<X, Z> transform1(Map<? extends X, ? extends Y> input,
                                      Function<Y, Z> function) {
    Map<X, Z> result = new HashMap<>();
    input.forEach((k, v) -> result.put(k, function.apply(v)));
    return result;
}

This uses Map.forEach() instead of streams. This is even simpler, I think, because it dispenses with the collectors, which are somewhat clumsy to use with maps. The reason is that Map.forEach() gives the key and value as separate parameters, whereas the stream has only one value -- and you have to choose whether to use the key or the map entry as that value. On the minus side, this lacks the rich, streamy goodness of the other approaches. :-)

How to select all instances of selected region in Sublime Text

Note: You should not edit the default settings, because they get reset on updates/upgrades. For customization, you should override any setting by using the user bindings.

On Mac:

  • Sublime Text 2 > Preferences > Key Bindings-Default
  • Sublime Text 3 > Preferences > Key Bindings

This opens a document that you can edit the keybindings for Sublime.

If you search "ctrl+super+g" you find this:

{ "keys": ["ctrl+super+g"], "command": "find_all_under" },

Python - Move and overwrite files and folders

Use copy() instead, which is willing to overwrite destination files. If you then want the first tree to go away, just rmtree() it separately once you are done iterating over it.

http://docs.python.org/library/shutil.html#shutil.copy

http://docs.python.org/library/shutil.html#shutil.rmtree

Update:

Do an os.walk() over the source tree. For each directory, check if it exists on the destination side, and os.makedirs() it if it is missing. For each file, simply shutil.copy() and the file will be created or overwritten, whichever is appropriate.

C#: How would I get the current time into a string?

I'd just like to point out something in these answers. In a date/time format string, '/' will be replaced with whatever the user's date separator is, and ':' will be replaced with whatever the user's time separator is. That is, if I've defined my date separator to be '.' (in the Regional and Language Options control panel applet, "intl.cpl"), and my time separator to be '?' (just pretend I'm crazy like that), then

DateTime.Now.ToString("MM/dd/yyyy h:mm tt")

would return

01.05.2009 6?01 PM

In most cases, this is what you want, because you want to respect the user's settings. If, however, you require the format be something specific (say, if it's going to parsed back out by somebody else down the wire), then you need to escape these special characters:

DateTime.Now.ToString("MM\\/dd\\/yyyy h\\:mm tt")

or

DateTime.Now.ToString(@"MM\/dd\/yyyy h\:mm tt")

which would now return

01/05/2009 6:01 PM

EDIT:

Then again, if you really want to respect the user's settings, you should use one of the standard date/time format strings, so that you respect not only the user's choices of separators, but also the general format of the date and/or time.

DateTime.Now.ToShortDateString()
DateTime.Now.ToString("d")

Both would return "1/5/2009" using standard US options, or "05/01/2009" using standard UK options, for instance.

DateTime.Now.ToLongDateString()
DateTime.Now.ToString("D")

Both would return "Monday, January 05, 2009" in US locale, or "05 January 2009" in UK.

DateTime.Now.ToShortTimeString()
DateTime.Now.ToString("t");

"6:01 PM" in US, "18:01" in UK.

DateTime.Now.ToLongTimeString()
DateTime.Now.ToString("T");

"6:01:04 PM" in US, "18:01:04" in UK.

DateTime.Now.ToString()
DateTime.Now.ToString("G");

"1/5/2009 6:01:04 PM" in US, "05/01/2009 18:01:04" in UK.

Many other options are available. See docs for standard date and time format strings and custom date and time format strings.

Can't perform a React state update on an unmounted component

I had this warning possibly because of calling setState from an effect hook (This is discussed in these 3 issues linked together).

Anyway, upgrading the react version removed the warning.

What is an undefined reference/unresolved external symbol error and how do I fix it?

Different architectures

You may see a message like:

library machine type 'x64' conflicts with target machine type 'X86'

In that case, it means that the available symbols are for a different architecture than the one you are compiling for.

On Visual Studio, this is due to the wrong "Platform", and you need to either select the proper one or install the proper version of the library.

On Linux, it may be due to the wrong library folder (using lib instead of lib64 for instance).

On MacOS, there is the option of shipping both architectures in the same file. It may be that the link expects both versions to be there, but only one is. It can also be an issue with the wrong lib/lib64 folder where the library is picked up.

Java: How to set Precision for double value?

To expand on @EJP, the concept of 'precision' when dealing with doubles is extremely fraught. As discussed in https://stackoverflow.com/a/3730040/390153 you can't even represent 0.1 as a double regardless of the precision, for the same reason you can't represent 1/3 in base 10 with finite precision.

You need to consider the problem you are trying to solve, and consider:

a) Should I be using doubles in the first place; if precision is a relevant concept, then using doubles may well be a mistake.

b) If doubles are appropriate, what do I mean by precision? If you are only talking about display, wrap the logic in a display function and you will only need to deal with it in one place; ie. apply the DRY principle.

Regular expression to match balanced parentheses

"""
Here is a simple python program showing how to use regular
expressions to write a paren-matching recursive parser.

This parser recognises items enclosed by parens, brackets,
braces and <> symbols, but is adaptable to any set of
open/close patterns.  This is where the re package greatly
assists in parsing. 
"""

import re


# The pattern below recognises a sequence consisting of:
#    1. Any characters not in the set of open/close strings.
#    2. One of the open/close strings.
#    3. The remainder of the string.
# 
# There is no reason the opening pattern can't be the
# same as the closing pattern, so quoted strings can
# be included.  However quotes are not ignored inside
# quotes.  More logic is needed for that....


pat = re.compile("""
    ( .*? )
    ( \( | \) | \[ | \] | \{ | \} | \< | \> |
                           \' | \" | BEGIN | END | $ )
    ( .* )
    """, re.X)

# The keys to the dictionary below are the opening strings,
# and the values are the corresponding closing strings.
# For example "(" is an opening string and ")" is its
# closing string.

matching = { "(" : ")",
             "[" : "]",
             "{" : "}",
             "<" : ">",
             '"' : '"',
             "'" : "'",
             "BEGIN" : "END" }

# The procedure below matches string s and returns a
# recursive list matching the nesting of the open/close
# patterns in s.

def matchnested(s, term=""):
    lst = []
    while True:
        m = pat.match(s)

        if m.group(1) != "":
            lst.append(m.group(1))

        if m.group(2) == term:
            return lst, m.group(3)

        if m.group(2) in matching:
            item, s = matchnested(m.group(3), matching[m.group(2)])
            lst.append(m.group(2))
            lst.append(item)
            lst.append(matching[m.group(2)])
        else:
            raise ValueError("After <<%s %s>> expected %s not %s" %
                             (lst, s, term, m.group(2)))

# Unit test.

if __name__ == "__main__":
    for s in ("simple string",
              """ "double quote" """,
              """ 'single quote' """,
              "one'two'three'four'five'six'seven",
              "one(two(three(four)five)six)seven",
              "one(two(three)four)five(six(seven)eight)nine",
              "one(two)three[four]five{six}seven<eight>nine",
              "one(two[three{four<five>six}seven]eight)nine",
              "oneBEGINtwo(threeBEGINfourENDfive)sixENDseven",
              "ERROR testing ((( mismatched ))] parens"):
        print "\ninput", s
        try:
            lst, s = matchnested(s)
            print "output", lst
        except ValueError as e:
            print str(e)
    print "done"

How to set up Automapper in ASP.NET Core

At the latest versions of asp.net core you should use the following initialization:

services.AddAutoMapper(typeof(YourMappingProfileClass));

cancelling a handler.postdelayed process

I do this to post a delayed runnable:

myHandler.postDelayed(myRunnable, SPLASH_DISPLAY_LENGTH); 

And this to remove it: myHandler.removeCallbacks(myRunnable);

Live Video Streaming with PHP

There are a lot of "off-the-shelf" 'servers' that will run in your environment. Most of these utilize the aforementioned Flex or Silverlight to implement the actual video itself but I'm pretty sure all will run under LAMP/PHP.

The challenges will picking the best software from everything that's available and getting your hosting-provider to let you stream video (it goes without saying that streaming is heavy on bandwidth).

How to inspect Javascript Objects

Here is my object inspector that is more readable. Because the code takes to long to write down here you can download it at http://etto-aa-js.googlecode.com/svn/trunk/inspector.js

Use like this :

document.write(inspect(object));

Remove Null Value from String array in java

A gc-friendly piece of code:

public static<X> X[] arrayOfNotNull(X[] array) {
    for (int p=0, N=array.length; p<N; ++p) {
        if (array[p] == null) {
            int m=p; for (int i=p+1; i<N; ++i) if (array[i]!=null) ++m;
            X[] res = Arrays.copyOf(array, m);
            for (int i=p+1; i<N; ++i) if (array[i]!=null) res[p++] = array[i];
            return res;
        }
    }
    return array;
}

It returns the original array if it contains no nulls. It does not modify the original array.

SQL Server Profiler - How to filter trace to only display events from one database?

Under Trace properties > Events Selection tab > select show all columns. Now under column filters, you should see the database name. Enter the database name for the Like section and you should see traces only for that database.

How do you specify table padding in CSS? ( table, not cell padding )

table {
    background: #fff;
    box-shadow: 0 0 0 10px #fff;
    margin: 10px;
    width: calc(100% - 20px); 
}

Install Windows Service created in Visual Studio

You need to open the Service.cs file in the designer, right click it and choose the menu-option "Add Installer".

It won't install right out of the box... you need to create the installer class first.

Some reference on service installer:

How to: Add Installers to Your Service Application

Quite old... but this is what I am talking about:

Windows Services in C#: Adding the Installer (part 3)

By doing this, a ProjectInstaller.cs will be automaticaly created. Then you can double click this, enter the designer, and configure the components:

  • serviceInstaller1 has the properties of the service itself: Description, DisplayName, ServiceName and StartType are the most important.

  • serviceProcessInstaller1 has this important property: Account that is the account in which the service will run.

For example:

this.serviceProcessInstaller1.Account = ServiceAccount.LocalSystem;

How to restore the permissions of files and directories within git if they have been modified?

i know this is old, but i came from google and i didn't find an answer

i have a simple solution if you have no change you want to keep :

git config core.fileMode true
git reset --hard HEAD

Selector on background color of TextView

For who is searching to do it without creating a background sector, just add those lines to the TextView

android:background="?android:attr/selectableItemBackground"
android:clickable="true"

Also to make it selectable use:

android:textIsSelectable="true"

Uncaught (in promise) TypeError: Failed to fetch and Cors error

Adding mode:'no-cors' to the request header guarantees that no response will be available in the response

Adding a "non standard" header, line 'access-control-allow-origin' will trigger a OPTIONS preflight request, which your server must handle correctly in order for the POST request to even be sent

You're also doing fetch wrong ... fetch returns a "promise" for a Response object which has promise creators for json, text, etc. depending on the content type...

In short, if your server side handles CORS correctly (which from your comment suggests it does) the following should work

function send(){
    var myVar = {"id" : 1};
    console.log("tuleb siia", document.getElementById('saada').value);
    fetch("http://localhost:3000", {
        method: "POST",
        headers: {
            "Content-Type": "text/plain"
        },
        body: JSON.stringify(myVar)
    }).then(function(response) {
        return response.json();
    }).then(function(muutuja){
        document.getElementById('väljund').innerHTML = JSON.stringify(muutuja);
    });
}

however, since your code isn't really interested in JSON (it stringifies the object after all) - it's simpler to do

function send(){
    var myVar = {"id" : 1};
    console.log("tuleb siia", document.getElementById('saada').value);
    fetch("http://localhost:3000", {
        method: "POST",
        headers: {
            "Content-Type": "text/plain"
        },
        body: JSON.stringify(myVar)
    }).then(function(response) {
        return response.text();
    }).then(function(muutuja){
        document.getElementById('väljund').innerHTML = muutuja;
    });
}

Get hostname of current request in node.js Express

You can use the os Module:

var os = require("os");
os.hostname();

See http://nodejs.org/docs/latest/api/os.html#os_os_hostname

Caveats:

  1. if you can work with the IP address -- Machines may have several Network Cards and unless you specify it node will listen on all of them, so you don't know on which NIC the request came in, before it comes in.

  2. Hostname is a DNS matter -- Don't forget that several DNS aliases can point to the same machine.

Change keystore password from no password to a non blank password

Add -storepass to keytool arguments.

keytool -storepasswd -storepass '' -keystore mykeystore.jks

But also notice that -list command does not always require a password. I could execute follow command in both cases: without password or with valid password

$JAVA_HOME/bin/keytool -list -keystore $JAVA_HOME/jre/lib/security/cacerts

Declaring a xsl variable and assigning value to it

No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:variable name="mapping">
    <item key="1" v1="A" v2="B" />
    <item key="2" v1="X" v2="Y" />
  </xsl:variable>
  <xsl:variable name="mappingNode"
                select="document('')//xsl:variable[@name = 'mapping']" />

  <xsl:template match="....">
    <xsl:variable name="testVariable" select="'1'" />

    <xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />

    <xsl:variable name="variable1" select="$values/@v1" />
    <xsl:variable name="variable2" select="$values/@v2" />
  </xsl:template>
</xsl:stylesheet>

In fact, once you've got the values variable, you may not even need separate variable1 and variable2 variables. You could just use $values/@v1 and $values/@v2 instead.

Cannot find JavaScriptSerializer in .Net 4.0

Just so you know, I am using Visual Studio 2013 and have had the same problem until I used the Project Properties to switch to 3.5 framework and back to 4.5. This for some reason registered the .dll properly and I could use the System.Web.Extensions.

enter image description here

enter image description here

Why isn't textarea an input[type="textarea"]?

I realize this is an older post, but thought this might be helpful to anyone wondering the same question:

While the previous answers are no doubt valid, there is a more simple reason for the distinction between textarea and input.

As mentioned previously, HTML is used to describe and give as much semantic structure to web content as possible, including input forms. A textarea may be used for input, however a textarea can also be marked as read only via the readonly attribute. The existence of such an attribute would not make any sense for an input type, and thus the distinction.

How to use underscore.js as a template engine?

I wanted to share one more important finding.

use of <%= variable => would result in cross-site scripting vulnerability. So its more safe to use <%- variable -> instead.

We had to replace <%= with <%- to prevent cross-site scripting attacks. Not sure, whether this will it have any impact on the performance

Find the PID of a process that uses a port on Windows

If you want to do this programmatically you can use some of the options given to you as follows in a PowerShell script:

$processPID =  $($(netstat -aon | findstr "9999")[0] -split '\s+')[-1]
taskkill /f /pid $processPID

However; be aware that the more accurate you can be the more precise your PID result will be. If you know which host the port is supposed to be on you can narrow it down a lot. netstat -aon | findstr "0.0.0.0:9999" will only return one application and most llikely the correct one. Only searching on the port number may cause you to return processes that only happens to have 9999 in it, like this:

TCP    0.0.0.0:9999                        0.0.0.0:0       LISTENING       15776
UDP    [fe80::81ad:9999:d955:c4ca%2]:1900  *:*                             12331

The most likely candidate usually ends up first, but if the process has ended before you run your script you may end up with PID 12331 instead and killing the wrong process.

How to use bluetooth to connect two iPhone?

If I remember correctly, Bluetooth defines certain roles that devices can take. Most cell phones only support a certain number of roles. For instance, I can have a Bluetooth stereo headset that connects to my phone to receive audio, but just because my cell phone has Bluetooth does mean that it supports BEING a speaker for a different device - it doesn't advertise its capabilities of having a speaker for use by other Bluetooth devices.

I assume you want to transfer files between two iPhones? Transferring files via Bluetooth does seem like functionality that I would put in the iPhone, but I'm not Apple so I don't know for sure. In fact, yes, it seems that file transfer is not supported except in jailbroken phones:

http://gizmodo.com/5138797/iphone-bluetooth-file-transfer-coming-soon-yes

You'll probably get similar answers for Bluetooth Dial-Up Networking. I'd imagine they kept the Bluetooth commands out of the SDK for various reasons and you'll have to jailbreak your phone to get the functionality back.

Build android release apk on Phonegap 3.x CLI

You could try this command, it should build and run the app (so .apk should be created) :

phonegap local run android

Preventing an image from being draggable or selectable without using JS

A generic solution especially for Windows Edge browser (as the -ms-user-select: none; CSS rule doesn't work):

window.ondragstart = function() {return false}

Note: This can save you having to add draggable="false" to every img tag when you still need the click event (i.e. you can't use pointer-events: none), but don't want the drag icon image to appear.

How do I test which class an object is in Objective-C?

If you want to check for a specific class then you can use

if([MyClass class] == [myClassObj class]) {
//your object is instance of MyClass
}

store and retrieve a class object in shared preference

Not possible.

You can only store, simple values in SharedPrefences SharePreferences.Editor

What particularly about the class do you need to save?

How to get UTC value for SYSDATE on Oracle

select sys_extract_utc(systimestamp) from dual;

Won't work on Oracle 8, though.

How to delete a workspace in Perforce (using p4v)?

In P4V click View > Workspaces

If the workspace to be deleted is not visible in the list you may have to uncheck the box Show only workspaces available for use on this computer

Right-click the workspace to be deleted and choose Edit Workspace 'My_workspace'

On the Advanced tab uncheck the box Locked: only the owner can edit workspace settings > then click OK

Now back on the Workspaces tab of Perforce right-click the workspace to be deleted and choose Delete Workspace 'My_workspace'

P4V should remove the item from the drop-down list when clicking on it.

There is a case where a previously deleted workspace remains in the drop-down list, and P4V displays the following error:

P4V Workspace Switch Error. This workspace cannot be used on this computer either because the host field does not match your computer name or the workspace root cannot be used on this computer.

If this error occurs, the workspace(possibly on another host) may have only been unloaded. Click the P4V Workspaces Recycle bin

P4V Recycle

In the resulting Unloaded Workspaces window right-click the offending workspace and choose Delete Workspace 'My_workspace'. P4V should now remove the workspace item from the drop-down list.

Rollback transaction after @Test

The answers mentioning adding @Transactional are correct, but for simplicity you could just have your test class extends AbstractTransactionalJUnit4SpringContextTests.

how to execute a scp command with the user name and password in one line

Using sshpass works best. To just include your password in scp use the ' ':

scp user1:'password'@xxx.xxx.x.5:sys_config /var/www/dev/

Maven build failed: "Unable to locate the Javac Compiler in: jre or jdk issue"

Make sure the "-vm" in your eclipse.ini is on two sperate lines, ie:

-vm
C:\Program Files\Java\jdk1.6.0_06

Difference between OData and REST web services

The OData protocol is built on top of the AtomPub protocol. The AtomPub protocol is one of the best examples of REST API design. So, in a sense you are right - the OData is just another REST API and each OData implementation is a REST-ful web service.

The difference is that OData is a specific protocol; REST is architecture style and design pattern.

Difference between rake db:migrate db:reset and db:schema:load

You could simply look in the Active Record Rake tasks as that is where I believe they live as in this file. https://github.com/rails/rails/blob/fe1f4b2ad56f010a4e9b93d547d63a15953d9dc2/activerecord/lib/active_record/tasks/database_tasks.rb

What they do is your question right?

That depends on where they come from and this is just and example to show that they vary depending upon the task. Here we have a different file full of tasks.

https://github.com/rails/rails/blob/fe1f4b2ad56f010a4e9b93d547d63a15953d9dc2/activerecord/Rakefile

which has these tasks.

namespace :db do
  task create: ["db:mysql:build", "db:postgresql:build"]
  task drop: ["db:mysql:drop", "db:postgresql:drop"]
end

This may not answer your question but could give you some insight into go ahead and look the source over especially the rake files and tasks. As they do a pretty good job of helping you use rails they don't always document the code that well. We could all help there if we know what it is supposed to do.

How to add a jar in External Libraries in android studio

The "official way" to add a jar into your android project as an external library, is to add the jar in dependencies { } section in build.gradle.

If you've done all of the above, and none of the above works, then there are two other possibilities:

  1. If Android Studio or some other IDE doesn't give red underlined errors in editor but runs in error in the Java Compiler, CHECK YOUR JAR. Your jar may not have a proper Manifest included therefore the compiler doesn't know what the jar can provide/don't know it's package name
  2. Maybe it's folder structure is messed up. The folder structure doesn't match with its package name. package a.b.c; should be matching to folder a > folder b > folder c.
  3. The package name has some conflict. (Trust me, this happened to me and it took hours to figure it out.)

However, if you are going with cordova, here are some tips of adding external jars.

"build-extras.gradle" is the better way to manage your gradle file.

Here are the steps to manage extra settings in cordova-based android project:

  1. Adding your jar into build-extras.gradle:
    //Other settings go here, e.g.: buildscript { ... }
    ext.postBuildExtras = {
    // you may have some other settings, e.g.: android { ... }
            dependencies {
                    compile files('libs/abc.jar')
            }
    }
    

(More detailed steps here: Extending the cordova gradle file to include google services )

  1. In terminal, do:

cordova build android

What is considered a good response time for a dynamic, personalized web application?

It depends on what keeps your users happy. For example, Gmail takes quite a while to open at first, but users wait because it is worth waiting for.

Append to the end of a Char array in C++

If your arrays are character arrays(which seems to be the case), You need a strcat().
Your destination array should have enough space to accommodate the appended data though.

In C++, You are much better off using std::string and then you can use std::string::append()

Index was out of range. Must be non-negative and less than the size of the collection parameter name:index

This error is caused when you have enabled paging in Grid view. If you want to delete a record from grid then you have to do something like this.

int index = Convert.ToInt32(e.CommandArgument);
int i = index % 20;
// Here 20 is my GridView's Page Size.
GridViewRow row = gvMainGrid.Rows[i];
int id = Convert.ToInt32(gvMainGrid.DataKeys[i].Value);
new GetData().DeleteRecord(id);
GridView1.DataSource = RefreshGrid();
GridView1.DataBind();

Hope this answers the question.

How to Execute SQL Script File in Java?

Try this code:

String strProc =
         "DECLARE \n" +
         "   sys_date DATE;"+
         "" +
         "BEGIN\n" +
         "" +
         "   SELECT SYSDATE INTO sys_date FROM dual;\n" +
         "" +
         "END;\n";

try{
    DriverManager.registerDriver ( new oracle.jdbc.driver.OracleDriver () );
    Connection connection = DriverManager.getConnection ("jdbc:oracle:thin:@your_db_IP:1521:your_db_SID","user","password");  
    PreparedStatement psProcToexecute = connection.prepareStatement(strProc);
    psProcToexecute.execute();
}catch (Exception e) {
    System.out.println(e.toString());  
}

How to strip all whitespace from string

Alternatively,

"strip my spaces".translate( None, string.whitespace )

And here is Python3 version:

"strip my spaces".translate(str.maketrans('', '', string.whitespace))

What are 'get' and 'set' in Swift?

variable declares and call like this in a class

class X {
    var x: Int = 3

}
var y = X()
print("value of x is: ", y.x)

//value of x is:  3

now you want to program to make the default value of x more than or equal to 3. Now take the hypothetical case if x is less than 3, your program will fail. so, you want people to either put 3 or more than 3. Swift got it easy for you and it is important to understand this bit-advance way of dating the variable value because they will extensively use in iOS development. Now let's see how get and set will be used here.

class X {
    var _x: Int = 3
    var x: Int {
        get {
            return _x
        }
        set(newVal) {  //set always take 1 argument
            if newVal >= 3 {
             _x = newVal //updating _x with the input value by the user
            print("new value is: ", _x)
            }
            else {
                print("error must be greater than 3")
            }
        }
    }
}
let y = X()
y.x = 1
print(y.x) //error must be greater than 3
y.x = 8 // //new value is: 8

if you still have doubts, just remember, the use of get and set is to update any variable the way we want it to be updated. get and set will give you better control to rule your logic. Powerful tool hence not easily understandable.

How to use npm with ASP.NET Core

Instead of trying to serve the node modules folder, you can also use Gulp to copy what you need to wwwroot.

https://docs.asp.net/en/latest/client-side/using-gulp.html

This might help too

Visual Studio 2015 ASP.NET 5, Gulp task not copying files from node_modules

Difference between Width:100% and width:100vw?

vw and vh stand for viewport width and viewport height respectively.

The difference between using width: 100vw instead of width: 100% is that while 100% will make the element fit all the space available, the viewport width has a specific measure, in this case the width of the available screen, including the document margin.

If you set the style body { margin: 0 }, 100vw should behave the same as 100%.

Additional notes

Using vw as unit for everything in your website, including font sizes and heights, will make it so that the site is always displayed proportionally to the device's screen width regardless of it's resolution. This makes it super easy to ensure your website is displayed properly in both workstation and mobile.

You can set font-size: 1vw (or whatever size suits your project) in your body CSS and everything specified in rem units will automatically scale according to the device screen, so it's easy to port existing projects and even frameworks (such as Bootstrap) to this concept.

How to make IPython notebook matplotlib plot inline

I have to agree with foobarbecue (I don't have enough recs to be able to simply insert a comment under his post):

It's now recommended that python notebook isn't started wit the argument --pylab, and according to Fernando Perez (creator of ipythonnb) %matplotlib inline should be the initial notebook command.

See here: http://nbviewer.ipython.org/github/ipython/ipython/blob/1.x/examples/notebooks/Part%203%20-%20Plotting%20with%20Matplotlib.ipynb

Return JsonResult from web api without its properties

When using WebAPI, you should just return the Object rather than specifically returning Json, as the API will either return JSON or XML depending on the request.

I am not sure why your WebAPI is returning an ActionResult, but I would change the code to something like;

public IEnumerable<ListItems> GetAllNotificationSettings()
{
    var result = new List<ListItems>();
    // Filling the list with data here...

    // Then I return the list
    return result;
}

This will result in JSON if you are calling it from some AJAX code.

P.S WebAPI is supposed to be RESTful, so your Controller should be called ListItemController and your Method should just be called Get. But that is for another day.

How to see the CREATE VIEW code for a view in PostgreSQL?

Kept having to return here to look up pg_get_viewdef (how to remember that!!), so searched for a more memorable command... and got it:

\d+ viewname

You can see similar sorts of commands by typing \? at the pgsql command line.

Bonus tip: The emacs command sql-postgres makes pgsql a lot more pleasant (edit, copy, paste, command history).

Please initialize the log4j system properly. While running web service

Those messages are something tricky, enough so that people created this to make it clearer: https://issues.apache.org/bugzilla/show_bug.cgi?id=25747

What's tricky about them is that the warnings are written if Log4j can't find its log4j.properties (or log4j.xml) file, but also if the file is fine and dandy but its content is not complete from a configuration point of view.

The following paragraph is taken from here: http://svn.apache.org/repos/asf/logging/log4j/tags/v1_2_9/docs/TROUBLESHOOT.html

Logging output is written to a target by using an appender. If no appenders are attached to a category nor to any of its ancestors, you will get the following message when trying to log:

log4j: No appenders could be found for category (some.category.name).
log4j: Please initialize the log4j system properly.

Log4j does not have a default logging target. It is the user's responsibility to ensure that all categories can inherit an appender. This can be easily achieved by attaching an appender to the root category.

You can find info on how to configure the root logger (log4j.rootLogger) in the log4j documentation, basically adding something as simple as this at the beginning of the file:

log4j.rootLogger=debug, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

This should clear those WARN messages you get on startup (make sure you don't already have an appender named stdout; also be carefull of what level you give the root logger, debug will be very verbose and every library in your app will start writing stuff to the console).

As about the log4j.properties/log4j.xml, I suggest you place this file in /WEB-INF/classes as it is important to have it exposed for different tweaks (activating/deactivating logs, changing log levels etc). You can have it inside a JAR in the classpath also (as you specified in your comment), but it will be enclosed in the archive (hopefully in the right place inside the archive) and won't be as easy to handle as if it were in /WEB-INF/classes.

How to create query parameters in Javascript?

Just like to revisit this almost 10 year old question. In this era of off-the-shelf programming, your best bet is to set your project up using a dependency manager (npm). There is an entire cottage industry of libraries out there that encode query strings and take care of all the edge cases. This is one of the more popular ones -

https://www.npmjs.com/package/query-string

How can I completely remove TFS Bindings

Sometime, the binding info is cached

To clear Team Explorer's cache:

Go to C:\Users\<user>\AppData\Local\Microsoft\Team Foundation\2.0
Delete or rename the Cache folder.

This come from a website I could not find now. Thanks for that guy for the tip.

How to check if a service is running on Android?

I have slightly modified one of the solutions presented above, but passing the class instead of a generic string name, in order to be sure to compare strings coming out from the same method class.getName()

public class ServiceTools {
    private static String LOG_TAG = ServiceTools.class.getName();

    public static boolean isServiceRunning(Context context,Class<?> serviceClass){
        final ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        final List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);

        for (RunningServiceInfo runningServiceInfo : services) {
            Log.d(Constants.TAG, String.format("Service:%s", runningServiceInfo.service.getClassName()));
            if (runningServiceInfo.service.getClassName().equals(serviceClass.getName())){
                return true;
            }
        }
        return false;
    }
}

and then

Boolean isServiceRunning = ServiceTools.isServiceRunning(
                    MainActivity.this.getApplicationContext(),
                    BackgroundIntentService.class);

Best Python IDE on Linux

I haven't played around with it much but eclipse/pydev feels nice.

How to add headers to OkHttp request interceptor?

here is a useful gist from lfmingo

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

httpClient.addInterceptor(new Interceptor() {

    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request original = chain.request();

        Request request = original.newBuilder()
            .header("User-Agent", "Your-App-Name")
            .header("Accept", "application/vnd.yourapi.v1.full+json")
            .method(original.method(), original.body())
            .build();

        return chain.proceed(request);
    }
}

OkHttpClient client = httpClient.build();

Retrofit retrofit = new Retrofit.Builder()  
    .baseUrl(API_BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .client(client)
    .build();

Java POI : How to read Excel cell value and not the formula computing it?

For formula cells, excel stores two things. One is the Formula itself, the other is the "cached" value (the last value that the forumla was evaluated as)

If you want to get the last cached value (which may no longer be correct, but as long as Excel saved the file and you haven't changed it it should be), you'll want something like:

 for(Cell cell : row) {
     if(cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
        System.out.println("Formula is " + cell.getCellFormula());
        switch(cell.getCachedFormulaResultType()) {
            case Cell.CELL_TYPE_NUMERIC:
                System.out.println("Last evaluated as: " + cell.getNumericCellValue());
                break;
            case Cell.CELL_TYPE_STRING:
                System.out.println("Last evaluated as \"" + cell.getRichStringCellValue() + "\"");
                break;
        }
     }
 }

How to get complete month name from DateTime

You can do as mservidio suggested, or even better, keep track of your culture using this overload:

DateTime.Now.ToString("MMMM", CultureInfo.InvariantCulture);

Should operator<< be implemented as a friend or as a member function?

friend operator = equal rights as class

friend std::ostream& operator<<(std::ostream& os, const Object& object) {
    os << object._atribute1 << " " << object._atribute2 << " " << atribute._atribute3 << std::endl;
    return os;
}

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

I don't think you can do it with one rsync command, but you can 'pre-create' the extra directory first like this:

rsync --recursive emptydir/ destination/newdir

where 'emptydir' is a local empty directory (which you might have to create as a temporary directory first).

It's a bit of a hack, but it works for me.

cheers

Chris

Get difference between two dates in months using Java

You can use Joda time library for Java. It would be much easier to calculate time-diff between dates with it.

Sample snippet for time-diff:

Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();

CentOS: Copy directory to another directory

For copy directory use following command

cp -r source    Destination

For example

cp -r  /home/hasan   /opt 

For copy file use command without -r

cp   /home/file    /home/hasan/

Concatenating strings in Razor

Use the parentesis syntax of Razor:

@(Model.address + " " + Model.city)

or

@(String.Format("{0} {1}", Model.address, Model.city))

Update: With C# 6 you can also use the $-Notation (officially interpolated strings):

@($"{Model.address} {Model.city}")

The PowerShell -and conditional operator

You can simplify it to

if ($user_sam -and $user_case) {
  ...
}

because empty strings coerce to $false (and so does $null, for that matter).

How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

This code will do what you're looking for. It's based on examples found here and here.

The autofmt_xdate() call is particularly useful for making the x-axis labels readable.

import numpy as np
from matplotlib import pyplot as plt

fig = plt.figure()

width = .35
ind = np.arange(len(OY))
plt.bar(ind, OY, width=width)
plt.xticks(ind + width / 2, OX)

fig.autofmt_xdate()

plt.savefig("figure.pdf")

enter image description here

Remove special symbols and extra spaces and replace with underscore using the replace method

var str = "hello world & hello universe"

In order to replace both Spaces and Symbols in one shot, we can use the below regex code.

str.replaceAll("\\W+","")

Note: \W -> represents Not Words (includes spaces/special characters) | + -> one or many matches

Try it!

Android ListView with Checkbox and all clickable

Set the CheckBox as focusable="false" in your XML layout. Otherwise it will steal click events from the list view.

Of course, if you do this, you need to manually handle marking the CheckBox as checked/unchecked if the list item is clicked instead of the CheckBox, but you probably want that anyway.

1064 error in CREATE TABLE ... TYPE=MYISAM

CREATE TABLE `admnih` (
  `id` int(255) NOT NULL auto_increment,
  `asim` varchar(255) NOT NULL default '',
  `brid` varchar(255) NOT NULL default '',
  `rwtbah` int(1) NOT NULL default '0',
  `esmmwkeh` varchar(255) NOT NULL default '',
  `mrwr` varchar(255) NOT NULL default '',
  `tid` int(255) NOT NULL default '0',
  `alksmfialdlil` int(255) NOT NULL default '0',
  `tariktsjil` varchar(255) NOT NULL default '',
  `aimwke` varchar(255) NOT NULL default '',
  `twkie` text NOT NULL,
  `rwtbahkasah` int(255) NOT NULL default '0',
  PRIMARY KEY  (`id`)
) TYPE=MyISAM AUTO_INCREMENT=2 ;

How to open a txt file and read numbers in Java

A much shorter alternative is below:

Path filePath = Paths.get("file.txt");
Scanner scanner = new Scanner(filePath);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
    if (scanner.hasNextInt()) {
        integers.add(scanner.nextInt());
    } else {
        scanner.next();
    }
}

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. Although default delimiter is whitespace, it successfully found all integers separated by new line character.

How to decode jwt token in javascript without using a library?

all features of jwt.io doesn't support all languages. In NodeJs you can use

var decoded = jwt.decode(token);

Editor does not contain a main type

A simpler way is to close the project and reopen it.