Programs & Examples On #Lookup

Look up is related to indexes and hash tables. It is the action of accessing fastly to an item in a large collection thanks to a index (a so-called lookup table).

How can I lookup a Java enum from its String value?

Use the valueOf method which is automatically created for each Enum.

Verbosity.valueOf("BRIEF") == Verbosity.BRIEF

For arbitrary values start with:

public static Verbosity findByAbbr(String abbr){
    for(Verbosity v : values()){
        if( v.abbr().equals(abbr)){
            return v;
        }
    }
    return null;
}

Only move on later to Map implementation if your profiler tells you to.

I know it's iterating over all the values, but with only 3 enum values it's hardly worth any other effort, in fact unless you have a lot of values I wouldn't bother with a Map it'll be fast enough.

How can I see if a Perl hash already has a certain key?

You can just go with:

if(!$strings{$string}) ....

How to get the index of an item in a list in a single step?

If you don't want to use LINQ, then:

int index;
for (int i = 0; i < myList.Count; i++)
{
    if (myList[i].Prop == oProp)
    {
       index = i;
       break;
    }
}

this way you are iterating list only once.

pandas loc vs. iloc vs. at vs. iat?

df = pd.DataFrame({'A':['a', 'b', 'c'], 'B':[54, 67, 89]}, index=[100, 200, 300])

df

                        A   B
                100     a   54
                200     b   67
                300     c   89
In [19]:    
df.loc[100]

Out[19]:
A     a
B    54
Name: 100, dtype: object

In [20]:    
df.iloc[0]

Out[20]:
A     a
B    54
Name: 100, dtype: object

In [24]:    
df2 = df.set_index([df.index,'A'])
df2

Out[24]:
        B
    A   
100 a   54
200 b   67
300 c   89

In [25]:    
df2.ix[100, 'a']

Out[25]:    
B    54
Name: (100, a), dtype: int64

How to do vlookup and fill down (like in Excel) in R?

Solution #2 of @Ben's answer is not reproducible in other more generic examples. It happens to give the correct lookup in the example because the unique HouseType in houses appear in increasing order. Try this:

hous <- read.table(header = TRUE,   stringsAsFactors = FALSE,   text="HouseType HouseTypeNo
  Semi            1
  ECIIsHome       17
  Single          2
  Row             3
  Single          2
  Apartment       4
  Apartment       4
  Row             3")

largetable <- data.frame(HouseType = as.character(sample(unique(hous$HouseType), 1000, replace = TRUE)), stringsAsFactors = FALSE)
lookup <- unique(hous)

Bens solution#2 gives

housenames <- as.numeric(1:length(unique(hous$HouseType)))
names(housenames) <- unique(hous$HouseType)
base2 <- data.frame(HouseType = largetable$HouseType,
                    HouseTypeNo = (housenames[largetable$HouseType]))

which when

unique(base2$HouseTypeNo[ base2$HouseType=="ECIIsHome" ])
[1] 2

when the correct answer is 17 from the lookup table

The correct way to do it is

 hous <- read.table(header = TRUE,   stringsAsFactors = FALSE,   text="HouseType HouseTypeNo
      Semi            1
      ECIIsHome       17
      Single          2
      Row             3
      Single          2
      Apartment       4
      Apartment       4
      Row             3")

largetable <- data.frame(HouseType = as.character(sample(unique(hous$HouseType), 1000, replace = TRUE)), stringsAsFactors = FALSE)

housenames <- tapply(hous$HouseTypeNo, hous$HouseType, unique)
base2 <- data.frame(HouseType = largetable$HouseType,
  HouseTypeNo = (housenames[largetable$HouseType]))

Now the lookups are performed correctly

unique(base2$HouseTypeNo[ base2$HouseType=="ECIIsHome" ])
ECIIsHome 
       17

I tried to edit Bens answer but it gets rejected for reasons I cannot understand.

Working with dictionaries/lists in R

You do not even need lists if your "number" values are all of the same mode. If I take Dirk Eddelbuettel's example:

> foo <- c(12, 22, 33)
> names(foo) <- c("tic", "tac", "toe")
> foo
tic tac toe
 12  22  33
> names(foo)
[1] "tic" "tac" "toe"

Lists are only required if your values are either of mixed mode (for example characters and numbers) or vectors.

For both lists and vectors, an individual element can be subsetted by name:

> foo["tac"]
tac 
 22 

Or for a list:

> foo[["tac"]]
[1] 22

How can I add new keys to a dictionary?

first to check whether the key already exists

a={1:2,3:4}
a.get(1)
2
a.get(5)
None

then you can add the new key and value

How to detect the physical connected state of a network cable/connector?

Some precisions and tricks

  1. I do all this as normal user (not root)

  2. Grab infos from dmesg

    Using dmesg is one of the 1st things to do for inquiring current state of system:

    dmesg | sed '/eth.*Link is/h;${x;p};d'
    

    could answer something like:

    [936536.904154] e1000e: eth0 NIC Link is Down
    

    or

    [936555.596870] e1000e: eth0 NIC Link is Up 100 Mbps Full Duplex, Flow Control: Rx/Tx
    

    depending on state, message could vary depending on hardware and drivers used.

    Nota: this could by written dmesg|grep eth.*Link.is|tail -n1 but I prefer using sed.

    dmesg | sed '/eth.*Link is/h;${x;s/^.*Link is //;p};d'
    Up 100 Mbps Full Duplex, Flow Control: Rx/Tx
    
    dmesg | sed '/eth.*Link is/h;${x;s/^.*Link is //;p};d'
    Down
    
  3. Test around /sys pseudo filesystem

    Reading or writting under /syscould break your system, especially if run as root! You've been warned ;-)

    This is a pooling method, not a real event tracking.

    cd /tmp
    grep -H . /sys/class/net/eth0/* 2>/dev/null >ethstate
    while ! read -t 1;do
        grep -H . /sys/class/net/eth0/* 2>/dev/null |
            diff -u ethstate - |
            tee >(patch -p0) |
            grep ^+
      done
    

    Could render something like (once you've unplugged and plugged back, depending ):

    +++ -   2016-11-18 14:18:29.577094838 +0100
    +/sys/class/net/eth0/carrier:0
    +/sys/class/net/eth0/carrier_changes:9
    +/sys/class/net/eth0/duplex:unknown
    +/sys/class/net/eth0/operstate:down
    +/sys/class/net/eth0/speed:-1
    +++ -   2016-11-18 14:18:48.771581903 +0100
    +/sys/class/net/eth0/carrier:1
    +/sys/class/net/eth0/carrier_changes:10
    +/sys/class/net/eth0/duplex:full
    +/sys/class/net/eth0/operstate:up
    +/sys/class/net/eth0/speed:100
    

    (Hit Enter to exit loop)

    Nota: This require patch to be installed.

  4. In fine, there must already be something about this...

    Depending on Linux Installation, you could add if-up and if-down scripts to be able to react to this kind of events.

    On Debian based (like Ubuntu), you could store your scripts into

    /etc/network/if-down.d
    /etc/network/if-post-down.d
    /etc/network/if-pre-up.d
    /etc/network/if-up.d
    

    see man interfaces for more infos.

HTML - how can I show tooltip ONLY when ellipsis is activated

This was my solution, works as a charm!

    $(document).on('mouseover', 'input, span', function() {
      var needEllipsis = $(this).css('text-overflow') && (this.offsetWidth < this.scrollWidth);
      var hasNotTitleAttr = typeof $(this).attr('title') === 'undefined';
      if (needEllipsis === true) {
          if(hasNotTitleAttr === true){
            $(this).attr('title', $(this).val());
          }
      }
      if(needEllipsis === false && hasNotTitleAttr == false){
        $(this).removeAttr('title');
      }
  });

Convert list to array in Java

I came across this code snippet that solves it.

//Creating a sample ArrayList 
List<Long> list = new ArrayList<Long>();

//Adding some long type values
list.add(100l);
list.add(200l);
list.add(300l);

//Converting the ArrayList to a Long
Long[] array = (Long[]) list.toArray(new Long[list.size()]);

//Printing the results
System.out.println(array[0] + " " + array[1] + " " + array[2]);

The conversion works as follows:

  1. It creates a new Long array, with the size of the original list
  2. It converts the original ArrayList to an array using the newly created one
  3. It casts that array into a Long array (Long[]), which I appropriately named 'array'

Log4j2 configuration - No log4j2 configuration file found

In my case I had to put it in the bin folder of my project even the fact that my classpath is set to the src folder. I have no idea why, but it's worth a try.

Bitbucket git credentials if signed up with Google

You should do a one-time setup of creating an "App password" in Bitbucket web UI with permissions to at least read your repositories and then use it in the command line.

How-to:

  1. Login to Bitbucket
  2. Click on your profile image on the right (now on the bottom left)
  3. Choose Bitbucket settings (now Personal settings)
  4. Under Access management section look for the App passwords option (https://bitbucket.org/account/settings/app-passwords/)
  5. Create an app password with permissions at least to Read under Repositories section. A password will be generated for you. Remember to save it, it will be shown only once!
  6. The username will be your Google username.

Jquery: how to sleep or delay?

How about .delay() ?

http://api.jquery.com/delay/

$("#test").animate({"top":"-=80px"},1500)
          .delay(1000)
          .animate({"opacity":"0"},500);

Default value in Go's method

No, there is no way to specify defaults. I believer this is done on purpose to enhance readability, at the cost of a little more time (and, hopefully, thought) on the writer's end.

I think the proper approach to having a "default" is to have a new function which supplies that default to the more generic function. Having this, your code becomes clearer on your intent. For example:

func SaySomething(say string) {
    // All the complicated bits involved in saying something
}

func SayHello() {
    SaySomething("Hello")
}

With very little effort, I made a function that does a common thing and reused the generic function. You can see this in many libraries, fmt.Println for example just adds a newline to what fmt.Print would otherwise do. When reading someone's code, however, it is clear what they intend to do by the function they call. With default values, I won't know what is supposed to be happening without also going to the function to reference what the default value actually is.

C# "as" cast vs classic cast

Null comparison is MUCH faster than throwing and catching exception. Exceptions have significant overhead - stack trace must be assembled etc.

Exceptions should represent an unexpected state, which often doesn't represent the situation (which is when as works better).

Decode Base64 data in Java

This is a late answer, but Joshua Bloch committed his Base64 class (when he was working for Sun, ahem, Oracle) under the java.util.prefs package. This class existed since JDK 1.4.

E.g.

String currentString = "Hello World";
String base64String = java.util.prefs.Base64.byteArrayToBase64(currentString.getBytes("UTF-8"));

how to delete all cookies of my website in php

<?php
      parse_str(http_build_query($_COOKIE),$arr);
      foreach ($arr as $k=>$v) {
        setCookie("$k","",1000,"/");
      }

Asynchronous vs synchronous execution, what does it really mean?

A different english definition of Synchronize is Here

Coordinate; combine.

I think that is a better definition than of "Happening at the same time". That one is also a definition, but I don't think it is the one that fits the way it is used in Computer Science.

So an asynchronous task is not co-coordinated with other tasks, whereas a synchronous task IS co-coordinated with other tasks, so one finishes before another starts.

How that is achieved is a different question.

Disable cache for some images

Simple, send one header location.

My site, contains one image, and after upload the image, there not change, then I add this code:

<?php header("Location: pagelocalimage.php"); ?>

Work's for me.

Can't change z-index with JQuery

Setting the style.zIndex property has no effect on non-positioned elements, that is, the element must be either absolutely positioned, relatively positioned, or fixed.

So I would try:

$(this).parent().css('position', 'relative');
$(this).parent().css('z-index', 3000);

How can query string parameters be forwarded through a proxy_pass with nginx?

github gist https://gist.github.com/anjia0532/da4a17f848468de5a374c860b17607e7

#set $token "?"; # deprecated

set $token ""; # declar token is ""(empty str) for original request without args,because $is_args concat any var will be `?`

if ($is_args) { # if the request has args update token to "&"
    set $token "&";
}

location /test {
    set $args "${args}${token}k1=v1&k2=v2"; # update original append custom params with $token
    # if no args $is_args is empty str,else it's "?"
    # http is scheme
    # service is upstream server
    #proxy_pass http://service/$uri$is_args$args; # deprecated remove `/`
    proxy_pass http://service$uri$is_args$args; # proxy pass
}

#http://localhost/test?foo=bar ==> http://service/test?foo=bar&k1=v1&k2=v2

#http://localhost/test/ ==> http://service/test?k1=v1&k2=v2

Cloning specific branch

a git repository has several branches. Each branch follows a development line, and it has its origin in another branch at some point in time (except the first branch, typically called master, that it starts as the default branch until someone changes, what almost never happens)

If you are new with git, remember those 2 fundamentals. Now, you just need to clone the repository, and it will be in some branch. if the branch is the one you are looking for, awesome. If not, you just need to change to the other branch - this is called checkout. Just type git checkout <branch-name>

In some cases you want to get updates for a specific branch. Just do git pull origin <branch-name> and it will 'download' the new commits (changes). If you didn't do any changes, it should go easy. If you also introduced changes on that branches, conflicts may appear. let me know if you need more info on this case also

Regular expression containing one word or another

You can use a single group for seconds/minutes. The following expression may suit your needs:

([0-9]+)\s*(seconds|minutes)

Online demo

File is universal (three slices), but it does not contain a(n) ARMv7-s slice error for static libraries on iOS, anyway to bypass?

In case this happens to someone. I built my own library to use with a third party code. While I was building it to deliver, I accidentally left my iPhone 4S plugged in, and so Xcode built my library only for the plugged architecture instead of following the project settings. Remove any plugged in devices and rebuilt the library, link it, and you should be all right.

Hope it helps.

How to jquery alert confirm box "yes" & "no"

See following snippet :

_x000D_
_x000D_
$(document).on("click", "a.deleteText", function() {_x000D_
    if (confirm('Are you sure ?')) {_x000D_
        $(this).prev('span.text').remove();_x000D_
    }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div class="container">_x000D_
    <span class="text">some text</span>_x000D_
    <a href="#" class="deleteText"><span class="delete-icon"> x Delete </span></a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Include an SVG (hosted on GitHub) in MarkDown

Just like this worked for me on Github.

![Imgae Caption](ImageAddressOnGitHub.svg)

or

<img src="ImageAddressOnGitHub.svg">

Making RGB color in Xcode

You already got the right answer, but if you dislike the UIColor interface like me, you can do this:

#import "UIColor+Helper.h"
// ...
myLabel.textColor = [UIColor colorWithRGBA:0xA06105FF];

UIColor+Helper.h:

#import <UIKit/UIKit.h>

@interface UIColor (Helper)
+ (UIColor *)colorWithRGBA:(NSUInteger)color;
@end

UIColor+Helper.m:

#import "UIColor+Helper.h"

@implementation UIColor (Helper)

+ (UIColor *)colorWithRGBA:(NSUInteger)color
{
    return [UIColor colorWithRed:((color >> 24) & 0xFF) / 255.0f
                           green:((color >> 16) & 0xFF) / 255.0f
                            blue:((color >> 8) & 0xFF) / 255.0f
                           alpha:((color) & 0xFF) / 255.0f];
}

@end

Swap two variables without using a temporary variable

C# 7 introduced tuples which enables swapping two variables without a temporary one:

int a = 10;
int b = 2;
(a, b) = (b, a);

This assigns b to a and a to b.

Struct memory layout in C

It's implementation-specific, but in practice the rule (in the absence of #pragma pack or the like) is:

  • Struct members are stored in the order they are declared. (This is required by the C99 standard, as mentioned here earlier.)
  • If necessary, padding is added before each struct member, to ensure correct alignment.
  • Each primitive type T requires an alignment of sizeof(T) bytes.

So, given the following struct:

struct ST
{
   char ch1;
   short s;
   char ch2;
   long long ll;
   int i;
};
  • ch1 is at offset 0
  • a padding byte is inserted to align...
  • s at offset 2
  • ch2 is at offset 4, immediately after s
  • 3 padding bytes are inserted to align...
  • ll at offset 8
  • i is at offset 16, right after ll
  • 4 padding bytes are added at the end so that the overall struct is a multiple of 8 bytes. I checked this on a 64-bit system: 32-bit systems may allow structs to have 4-byte alignment.

So sizeof(ST) is 24.

It can be reduced to 16 bytes by rearranging the members to avoid padding:

struct ST
{
   long long ll; // @ 0
   int i;        // @ 8
   short s;      // @ 12
   char ch1;     // @ 14
   char ch2;     // @ 15
} ST;

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

If you use require.js AMD loader:

// path config
requirejs.config({
  paths: {
    jquery: '//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/core.js',
    tether: '//cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min',
    bootstrap: '//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/js/bootstrap.min',
  },
  shim: {
    bootstrap: {
      deps: ['jquery']
    }
  }
});

//async loading
requirejs(['tether'], function (Tether) {
  window.Tether = Tether;
  requirejs(['bootstrap']);
});

How to gzip all files in all sub-directories into one compressed file in bash

@amitchhajer 's post works for GNU tar. If someone finds this post and needs it to work on a NON GNU system, they can do this:

tar cvf - folderToCompress | gzip > compressFileName

To expand the archive:

zcat compressFileName | tar xvf -

Check If only numeric values were entered in input. (jQuery)

This isn't an exact answer to the question, but one other option for phone validation, is to ensure the number gets entered in the format you are expecting.

Here is a function I have worked on that when set to the onInput event, will strip any non-numerical inputs, and auto-insert dashes at the "right" spot, assuming xxx-xxx-xxxx is the desired output.

<input oninput="formatPhone()">

function formatPhone(e) {
    var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
    e.target.value = !x[2] ? x[1] : x[1] + '-' + x[2] + (x[3] ? '-' + x[3] : '');
}

Git commit in terminal opens VIM, but can't get back to terminal

This is in answer to your question...

I'd also like to know how to make it open up in Sublime Text 2 instead

For Windows:

git config --global core.editor "'C:/Program Files/Sublime Text 2/sublime_text.exe'"

Check that the path for sublime_text.exe is correct and adjust if needed.

For Mac/Linux:

git config --global core.editor "subl -n -w"

If you get an error message such as:

error: There was a problem with the editor 'subl -n -w'.

Create the alias for subl

sudo ln -s /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl /usr/local/bin/subl

Again check that the path matches for your machine.

For Sublime Text simply save cmd S and close the window cmd W to return to git.

Client to send SOAP request and receive response

I normally use another way to do the same

using System.Xml;
using System.Net;
using System.IO;

public static void CallWebService()
{
    var _url = "http://xxxxxxxxx/Service1.asmx";
    var _action = "http://xxxxxxxx/Service1.asmx?op=HelloWorld";

    XmlDocument soapEnvelopeXml = CreateSoapEnvelope();
    HttpWebRequest webRequest = CreateWebRequest(_url, _action);
    InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);

    // begin async call to web request.
    IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);

    // suspend this thread until call is complete. You might want to
    // do something usefull here like update your UI.
    asyncResult.AsyncWaitHandle.WaitOne();

    // get the response from the completed web request.
    string soapResult;
    using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
    {
        using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
        {
            soapResult = rd.ReadToEnd();
        }
        Console.Write(soapResult);        
    }
}

private static HttpWebRequest CreateWebRequest(string url, string action)
{
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
    webRequest.Headers.Add("SOAPAction", action);
    webRequest.ContentType = "text/xml;charset=\"utf-8\"";
    webRequest.Accept = "text/xml";
    webRequest.Method = "POST";
    return webRequest;
}

private static XmlDocument CreateSoapEnvelope()
{
    XmlDocument soapEnvelopeDocument = new XmlDocument();
    soapEnvelopeDocument.LoadXml(
    @"<SOAP-ENV:Envelope xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" 
               xmlns:xsi=""http://www.w3.org/1999/XMLSchema-instance"" 
               xmlns:xsd=""http://www.w3.org/1999/XMLSchema"">
        <SOAP-ENV:Body>
            <HelloWorld xmlns=""http://tempuri.org/"" 
                SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"">
                <int1 xsi:type=""xsd:integer"">12</int1>
                <int2 xsi:type=""xsd:integer"">32</int2>
            </HelloWorld>
        </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>");
    return soapEnvelopeDocument;
}

private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
    using (Stream stream = webRequest.GetRequestStream())
    {
        soapEnvelopeXml.Save(stream);
    }
}

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

With default Github repository import it is possible, but just make sure the two factor authentication is not enabled in Gitlab.

Thanks

How to have an automatic timestamp in SQLite?

Just declare a default value for a field:

CREATE TABLE MyTable(
    ID INTEGER PRIMARY KEY,
    Name TEXT,
    Other STUFF,
    Timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
);

However, if your INSERT command explicitly sets this field to NULL, it will be set to NULL.

Foreign Key to non-primary key

As others have pointed out, ideally, the foreign key would be created as a reference to a primary key (usually an IDENTITY column). However, we don't live in an ideal world, and sometimes even a "small" change to a schema can have significant ripple effects to the application logic.

Consider the case of a Customer table with a SSN column (and a dumb primary key), and a Claim table that also contains a SSN column (populated by business logic from the Customer data, but no FK exists). The design is flawed, but has been in use for several years, and three different applications have been built on the schema. It should be obvious that ripping out Claim.SSN and putting in a real PK-FK relationship would be ideal, but would also be a significant overhaul. On the other hand, putting a UNIQUE constraint on Customer.SSN, and adding a FK on Claim.SSN, could provide referential integrity, with little or no impact on the applications.

Don't get me wrong, I'm all for normalization, but sometimes pragmatism wins over idealism. If a mediocre design can be helped with a band-aid, surgery might be avoided.

Javascript sleep/delay/wait function

You could use the following code, it does a recursive call into the function in order to properly wait for the desired time.

function exportar(page,miliseconds,totalpages)
{
    if (page <= totalpages)
    {
        nextpage = page + 1;
        console.log('fnExcelReport('+ page +'); nextpage = '+ nextpage + '; miliseconds = '+ miliseconds + '; totalpages = '+ totalpages );
        fnExcelReport(page);
        setTimeout(function(){
            exportar(nextpage,miliseconds,totalpages);
        },miliseconds);
    };
}

windows batch file rename

Use REN Command

Ren is for rename

ren ( where the file is located ) ( the new name )

example

ren C:\Users\&username%\Desktop\aaa.txt bbb.txt

it will change aaa.txt to bbb.txt

Your code will be :

ren (file located)AAA_a001.jpg a001.AAA.jpg

ren (file located)BBB_a002.jpg a002.BBB.jpg

ren (file located)CCC_a003.jpg a003.CCC.jpg

and so on

IT WILL NOT WORK IF THERE IS SPACES!

Hope it helps :D

How to sort in-place using the merge sort algorithm?

This is my C version:

void mergesort(int *a, int len) {
  int temp, listsize, xsize;

  for (listsize = 1; listsize <= len; listsize*=2) {
    for (int i = 0, j = listsize; (j+listsize) <= len; i += (listsize*2), j += (listsize*2)) {
      merge(& a[i], listsize, listsize);
    }
  }

  listsize /= 2;

  xsize = len % listsize;
  if (xsize > 1)
    mergesort(& a[len-xsize], xsize);

  merge(a, listsize, xsize);
}

void merge(int *a, int sizei, int sizej) {
  int temp;
  int ii = 0;
  int ji = sizei;
  int flength = sizei+sizej;

  for (int f = 0; f < (flength-1); f++) {
    if (sizei == 0 || sizej == 0)
      break;

    if (a[ii] < a[ji]) {
      ii++;
      sizei--;
    }
    else {
      temp = a[ji];

      for (int z = (ji-1); z >= ii; z--)
        a[z+1] = a[z];  
      ii++;

      a[f] = temp;

      ji++;
      sizej--;
    }
  }
}

TypeError: 'list' object cannot be interpreted as an integer

since it's a list it cannot be taken directly into range function as the singular integer value of the list is missing.

use this

for i in range(len(myList)):

with this, we get the singular integer value which can be used easily

Can I display the value of an enum with printf()?

As a string, no. As an integer, %d.

Unless you count:

static char* enumStrings[] = { /* filler 0's to get to the first value, */
                               "enum0", "enum1", 
                               /* filler for hole in the middle: ,0 */
                               "enum2", "enum3", .... };

...

printf("The value is %s\n", enumStrings[thevalue]);

This won't work for something like an enum of bit masks. At that point, you need a hash table or some other more elaborate data structure.

How to convert .pfx file to keystore with private key?

Justin(above) is accurate. However, keep in mind that depending on who you get the certificate from (intermediate CA, root CA involved or not) or how the pfx is created/exported, sometimes they could be missing the certificate chain. After Import, You would have a certificate of PrivateKeyEntry type, but with a chain of length of 1.

To fix this, there are several options. The easier option in my mind is to import and export the pfx file in IE(choosing the option of Including all the certificates in the chain). The import and export process of certificates in IE should be very easy and well documented elsewhere.

Once exported, import the keystore as Justin pointed above. Now, you would have a keystore with certificate of type PrivateKeyEntry and with a certificate chain length of more than 1.

Certain .Net based Web service clients error out(unable to establish trust relationship), if you don't do the above.

execJs: 'Could not find a JavaScript runtime' but execjs AND therubyracer are in Gemfile

when i generate rails g controller i got the same error. After that when do the following changes on Gemfile(in rails 4) everything went smooth.The changes i made was

gem 'execjs'
gem 'therubyracer', "0.11.4"
After that i can able to run the server and able to do all basic operations on the application.

Why can't I duplicate a slice with `copy()`?

The builtin copy(dst, src) copies min(len(dst), len(src)) elements.

So if your dst is empty (len(dst) == 0), nothing will be copied.

Try tmp := make([]int, len(arr)) (Go Playground):

arr := []int{1, 2, 3}
tmp := make([]int, len(arr))
copy(tmp, arr)
fmt.Println(tmp)
fmt.Println(arr)

Output (as expected):

[1 2 3]
[1 2 3]

Unfortunately this is not documented in the builtin package, but it is documented in the Go Language Specification: Appending to and copying slices:

The number of elements copied is the minimum of len(src) and len(dst).

Edit:

Finally the documentation of copy() has been updated and it now contains the fact that the minimum length of source and destination will be copied:

Copy returns the number of elements copied, which will be the minimum of len(src) and len(dst).

Node Sass couldn't find a binding for your current environment

Just run the comment thats it.

npm rebuild node-sass

enjoy your coding...

Unmarshaling nested JSON objects

I was working on something like this. But is working only with structures generated from proto. https://github.com/flowup-labs/grpc-utils

in your proto

message Msg {
  Firstname string = 1 [(gogoproto.jsontag) = "name.firstname"];
  PseudoFirstname string = 2 [(gogoproto.jsontag) = "lastname"];
  EmbedMsg = 3  [(gogoproto.nullable) = false, (gogoproto.embed) = true];
  Lastname string = 4 [(gogoproto.jsontag) = "name.lastname"];
  Inside string  = 5 [(gogoproto.jsontag) = "name.inside.a.b.c"];
}

message EmbedMsg{
   Opt1 string = 1 [(gogoproto.jsontag) = "opt1"];
}

Then your output will be

{
"lastname": "Three",
"name": {
    "firstname": "One",
    "inside": {
        "a": {
            "b": {
                "c": "goo"
            }
        }
    },
    "lastname": "Two"
},
"opt1": "var"
}

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Was able to fix the issue by updating NVIDIA device drivers to the latest (v446.14). NVIDIA drivers download link here.

Spring RequestMapping for controllers that produce and consume JSON

There are 2 annotations in Spring: @RequestBody and @ResponseBody. These annotations consumes, respectively produces JSONs. Some more info here.

How can I change the version of npm using nvm?

Changing npm versions on linux based OSs isn't a straight forward one command process yet. I have done following to switch back to older version of npm. This should work to get any version of npm working. First install the version of npm you want to use:

sudo npm install -g [email protected]

Remove the sym link in /usr/local/bin/

sudo rm /usr/local/bin/npm

Recreate the sym link using the desired version of npm you have installed

sudo ln -s /usr/bin/[email protected] /usr/local/bin/npm

jQuery datepicker to prevent past date

This should work <input type="text" id="datepicker">

var dateToday = new Date();
$("#datepicker").datepicker({
    minDate: dateToday,
    onSelect: function(selectedDate) {
    var option = this.id == "datepicker" ? "minDate" : "maxDate",
    instance = $(this).data("datepicker"),
    date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
    dates.not(this).datepicker("option", option, date);
    }
});

How to add /usr/local/bin in $PATH on Mac

To make the edited value of path persists in the next sessions

cd ~/
touch .bash_profile
open .bash_profile

That will open the .bash_profile in editor, write inside the following after adding what you want to the path separating each value by column.

export PATH=$PATH:/usr/local/git/bin:/usr/local/bin:

Save, exit, restart your terminal and enjoy

dotnet ef not found in .NET Core 3

I had the same problem. I resolved, uninstalling all de the versions in my pc and then reinstall dotnet.

Android: Bitmaps loaded from gallery are rotated in ImageView

Solved it in my case with this code using help of this post:

            Bitmap myBitmap = getBitmap(imgFile.getAbsolutePath());

            try {
                ExifInterface exif = new ExifInterface(imgFile.getAbsolutePath());
                int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
                Log.d("EXIF", "Exif: " + orientation);
                Matrix matrix = new Matrix();
                if (orientation == 6) {
                    matrix.postRotate(90);
                }
                else if (orientation == 3) {
                    matrix.postRotate(180);
                }
                else if (orientation == 8) {
                    matrix.postRotate(270);
                }
                myBitmap = Bitmap.createBitmap(myBitmap, 0, 0, myBitmap.getWidth(), myBitmap.getHeight(), matrix, true); // rotating bitmap
            }
            catch (Exception e) {

            }
            ImageView img = (ImageView) findViewById(R.id.imgTakingPic);
            img.setImageBitmap(myBitmap);

Hope it saves someone's time!

CSS Animation and Display None

How do I have a div not take up space until it is timed to come in (using CSS for the timing.)

Here is my solution to the same problem.

Moreover I have an onclick on the last frame loading another slideshow, and it must not be clickable until the last frame is visible.

Basically my solution is to keep the div 1 pixel high using a scale(0.001), zooming it when I need it. If you don't like the zoom effect you can restore the opacity to 1 after zooming the slide.

#Slide_TheEnd {

    -webkit-animation-delay: 240s;
    animation-delay: 240s;

    -moz-animation-timing-function: linear;
    -webkit-animation-timing-function: linear;
    animation-timing-function: linear;

    -moz-animation-duration: 20s;
    -webkit-animation-duration: 20s;
    animation-duration: 20s;

    -moz-animation-name: Slide_TheEnd;
    -webkit-animation-name: Slide_TheEnd;
    animation-name: Slide_TheEnd;

    -moz-animation-iteration-count: 1;
    -webkit-animation-iteration-count: 1;
    animation-iteration-count: 1;

    -moz-animation-direction: normal;
    -webkit-animation-direction: normal;
    animation-direction: normal;

    -moz-animation-fill-mode: forwards;
    -webkit-animation-fill-mode: forwards;
    animation-fill-mode: forwards;

    transform: scale(0.001);
    background: #cf0;
    text-align: center;
    font-size: 10vh;
    opacity: 0;
}

@-moz-keyframes Slide_TheEnd {
    0% { opacity: 0;  transform: scale(0.001); }
    10% { opacity: 1; transform: scale(1); }
    95% { opacity: 1; transform: scale(1); }
    100% { opacity: 0;  transform: scale(0.001); }
}

Other keyframes are removed for the sake of bytes. Please disregard the odd coding, it is made by a php script picking values from an array and str_replacing a template: I'm too lazy to retype everything for every proprietary prefix on a 100+ divs slideshow.

How to unpack pkl file?

Generally

Your pkl file is, in fact, a serialized pickle file, which means it has been dumped using Python's pickle module.

To un-pickle the data you can:

import pickle


with open('serialized.pkl', 'rb') as f:
    data = pickle.load(f)

For the MNIST data set

Note gzip is only needed if the file is compressed:

import gzip
import pickle


with gzip.open('mnist.pkl.gz', 'rb') as f:
    train_set, valid_set, test_set = pickle.load(f)

Where each set can be further divided (i.e. for the training set):

train_x, train_y = train_set

Those would be the inputs (digits) and outputs (labels) of your sets.

If you want to display the digits:

import matplotlib.cm as cm
import matplotlib.pyplot as plt


plt.imshow(train_x[0].reshape((28, 28)), cmap=cm.Greys_r)
plt.show()

mnist_digit

The other alternative would be to look at the original data:

http://yann.lecun.com/exdb/mnist/

But that will be harder, as you'll need to create a program to read the binary data in those files. So I recommend you to use Python, and load the data with pickle. As you've seen, it's very easy. ;-)

How to remove &quot; from my Json in javascript?

Accepted answer is right, however I had a trouble with that. When I add in my code, checking on debugger, I saw that it changes from

result.replace(/&quot;/g,'"')

to

result.replace(/&#34;/g,'"')

Instead of this I use that:

result.replace(/(&quot\;)/g,"\"")

By this notation it works.

Append column to pandas dataframe

You can also use:

dat1 = pd.concat([dat1, dat2], axis=1)

Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint

I had the same issue for my angular project, then I make it work in Chrome by changing the setting. Go to Chrome setting -->site setting -->Insecure content --> click add button of allow, then add your domain name [*.]XXXX.biz

Now problem will be solved.

jQuery autocomplete with callback ajax json

$(document).on('keyup','#search_product',function(){
    $( "#search_product" ).autocomplete({
      source:function(request,response){
                  $.post("<?= base_url('ecommerce/autocomplete') ?>",{'name':$( "#search_product" ).val()}).done(function(data, status){

                    response(JSON.parse(data));
        });
      }
    });
});

PHP code :

public function autocomplete(){
    $name=$_POST['name'];
    $result=$this->db->select('product_name,sku_code')->like('product_name',$name)->get('product_list')->result_array();
    $names=array();
    foreach($result as $row){
        $names[]=$row['product_name'];
    }
    echo json_encode($names);
}

Sql query to insert datetime in SQL Server

You will want to use the YYYYMMDD for unambiguous date determination in SQL Server.

insert into table1(approvaldate)values('20120618 10:34:09 AM');

If you are married to the dd-mm-yy hh:mm:ss xm format, you will need to use CONVERT with the specific style.

insert into table1 (approvaldate)
       values (convert(datetime,'18-06-12 10:34:09 PM',5));

5 here is the style for Italian dates. Well, not just Italians, but that's the culture it's attributed to in Books Online.

trim left characters in sql server?

select substring( field, 1, 5 ) from sometable

How to install older version of node.js on Windows?

Go here and find the version you want to install and then download the correct msi file and run the installer. You cannot install node by running this command, also the error you receive is stating that npm is not on your path which suggests machine doesn't currently have node installed on it

How to initialize a vector with fixed length in R

?vector

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

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

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

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

> length(X)
[1] 10

Pandas: Return Hour from Datetime Column Directly

For posterity: as of 0.15.0, there is a handy .dt accessor you can use to pull such values from a datetime/period series (in the above case, just sales.timestamp.dt.hour!

How to Navigate from one View Controller to another using Swift

In my experience navigationController was nil so I changed my code to this:

let next = self.storyboard?.instantiateViewControllerWithIdentifier("DashboardController") as! DashboardController
self.presentViewController(next, animated: true, completion: nil)

Don't forget to set ViewController StoryBoard Id in StoryBoard -> identity inspector

Android Layout Weight

One more reason I found (vague as it may sound). The below did not work.

LinearLayout vertical

LinearLayout height fillparent + weight

LinearLayout height fillparent + weight

LinearLayout height fillparent + weight

EndLinearLayout

What did work was

RelativeLayout

LinearLayout vertical

LinearLayout height fillparent + weight

LinearLayout height fillparent + weight

LinearLayout height fillparent + weight

EndLinearLayout

EndRelativeLayout

It sounds vague by a root layout with Linear and weights under it did not work. And when I say "did not work", I mean, that after I viewed the graphical layout between various resolutions the screen consistency broke big time.

Removing all script tags from html with JS Regular Expression

You can try

$("your_div_id").remove();  

or

 $("your_div_id").html(""); 

How to get current route in react-router 2.0.0-rc5

As of version 3.0.0, you can get the current route by calling:

this.context.router.location.pathname

Sample code is below:

var NavLink = React.createClass({
    contextTypes: {
        router: React.PropTypes.object
    },

    render() {   
        return (
            <Link {...this.props}></Link>
        );
    }
});

Execute a file with arguments in Python shell

Actually, wouldn't we want to do this?

import sys
sys.argv = ['abc.py','arg1', 'arg2']
execfile('abc.py')

Calculating the angle between the line defined by two points

Assumptions: x is the horizontal axis, and increases when moving from left to right. y is the vertical axis, and increases from bottom to top. (touch_x, touch_y) is the point selected by the user. (center_x, center_y) is the point at the center of the screen. theta is measured counter-clockwise from the +x axis. Then:

delta_x = touch_x - center_x
delta_y = touch_y - center_y
theta_radians = atan2(delta_y, delta_x)

Edit: you mentioned in a comment that y increases from top to bottom. In that case,

delta_y = center_y - touch_y

But it would be more correct to describe this as expressing (touch_x, touch_y) in polar coordinates relative to (center_x, center_y). As ChrisF mentioned, the idea of taking an "angle between two points" is not well defined.

How can I get device ID for Admob

To get the Hash Device ID

inside the oncreate

String android_id = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
        String deviceId = md5(android_id).toUpperCase();
Log.i("device id=",deviceId);

then add this class for md5 ()

public String md5(String s) {
        try {
            // Create MD5 Hash
            MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
            digest.update(s.getBytes());
            byte messageDigest[] = digest.digest();

            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            for (int i=0; i<messageDigest.length; i++)
                hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

Looking for a good Python Tree data structure

I found a module written by Brett Alistair Kromkamp which was not completed. I finished it and make it public on github and renamed it as treelib (original pyTree):

https://github.com/caesar0301/treelib

May it help you....

How to calculate UILabel width based on text length?

The selected answer is correct for iOS 6 and below.

In iOS 7, sizeWithFont:constrainedToSize:lineBreakMode: has been deprecated. It is now recommended you use boundingRectWithSize:options:attributes:context:.

CGRect expectedLabelSize = [yourString boundingRectWithSize:sizeOfRect
                                                    options:<NSStringDrawingOptions>
                                                 attributes:@{
                                                    NSFontAttributeName: yourString.font
                                                    AnyOtherAttributes: valuesForAttributes
                                                 }
                                                    context:(NSStringDrawingContext *)];

Note that the return value is a CGRect not a CGSize. Hopefully that'll be of some assistance to people using it in iOS 7.

How to get a jqGrid cell value when editing

You can use getCol to get the column values as an array then index into it by the row you are interested in.

var col = $('#grid').jqGrid('getCol', 'Sales', false);

var val = col[row];

The Use of Multiple JFrames: Good or Bad Practice?

The multiple JFrame approach has been something I've implemented since I began programming Swing apps. For the most part, I did it in the beginning because I didn't know any better. However, as I matured in my experience and knowledge as a developer and as began to read and absorb the opinions of so many more experienced Java devs online, I made an attempt to shift away from the multiple JFrame approach (both in current projects and future projects) only to be met with... get this... resistance from my clients! As I began implementing modal dialogs to control "child" windows and JInternalFrames for separate components, my clients began to complain! I was quite surprised, as I was doing what I thought was best-practice! But, as they say, "A happy wife is a happy life." Same goes for your clients. Of course, I am a contractor so my end-users have direct access to me, the developer, which is obviously not a common scenario.

So, I'm going to explain the benefits of the multiple JFrame approach, as well as myth-bust some of the cons that others have presented.

  1. Ultimate flexibility in layout - By allowing separate JFrames, you give your end-user the ability to spread out and control what's on his/her screen. The concept feels "open" and non-constricting. You lose this when you go towards one big JFrame and a bunch of JInternalFrames.
  2. Works well for very modularized applications - In my case, most of my applications have 3 - 5 big "modules" that really have nothing to do with each other whatsoever. For instance, one module might be a sales dashboard and one might be an accounting dashboard. They don't talk to each other or anything. However, the executive might want to open both and them being separate frames on the taskbar makes his life easier.
  3. Makes it easy for end-users to reference outside material - Once, I had this situation: My app had a "data viewer," from which you could click "Add New" and it would open a data entry screen. Initially, both were JFrames. However, I wanted the data entry screen to be a JDialog whose parent was the data viewer. I made the change, and immediately I received a call from an end-user who relied heavily on the fact that he could minimize or close the viewer and keep the editor open while he referenced another part of the program (or a website, I don't remember). He's not on a multi-monitor, so he needed the entry dialog to be first and something else to be second, with the data viewer completely hidden. This was impossible with a JDialog and certainly would've been impossible with a JInternalFrame as well. I begrudgingly changed it back to being separate JFrames for his sanity, but it taught me an important lesson.
  4. Myth: Hard to code - This is not true in my experience. I don't see why it would be any easier to create a JInternalFrame than a JFrame. In fact, in my experience, JInternalFrames offer much less flexibility. I have developed a systematic way of handling the opening & closing of JFrames in my apps that really works well. I control the frame almost completely from within the frame's code itself; the creation of the new frame, SwingWorkers that control the retrieval of data on background threads and the GUI code on EDT, restoring/bringing to front the frame if the user tries to open it twice, etc. All you need to open my JFrames is call a public static method open() and the open method, combined with a windowClosing() event handles the rest (is the frame already open? is it not open, but loading? etc.) I made this approach a template so it's not difficult to implement for each frame.
  5. Myth/Unproven: Resource Heavy - I'd like to see some facts behind this speculative statement. Although, perhaps, you could say a JFrame needs more space than a JInternalFrame, even if you open up 100 JFrames, how many more resources would you really be consuming? If your concern is memory leaks because of resources: calling dispose() frees all resources used by the frame for garbage collection (and, again I say, a JInternalFrame should invoke exactly the same concern).

I've written a lot and I feel like I could write more. Anyways, I hope I don't get down-voted simply because it's an unpopular opinion. The question is clearly a valuable one and I hope I've provided a valuable answer, even if it isn't the common opinion.

A great example of multiple frames/single document per frame (SDI) vs single frame/multiple documents per frame (MDI) is Microsoft Excel. Some of MDI benefits:

  • it is possible to have a few windows in non rectangular shape - so they don't hide desktop or other window from another process (e.g. web browser)
  • it is possible to open a window from another process over one Excel window while writing in second Excel window - with MDI, trying to write in one of internal windows will give focus to the entire Excel window, hence hiding window from another process
  • it is possible to have different documents on different screens, which is especially useful when screens do not have the same resolution

SDI (Single-Document Interface, i.e., every window can only have a single document):

enter image description here

MDI (Multiple-Document Interface, i.e., every window can have multiple documents):

enter image description here

DateTime.TryParseExact() rejecting valid formats

This is the Simple method, Use ParseExact

CultureInfo provider = CultureInfo.InvariantCulture;
DateTime result;
String dateString = "Sun 08 Jun 2013 8:30 AM -06:00";
String format = "ddd dd MMM yyyy h:mm tt zzz";
result = DateTime.ParseExact(dateString, format, provider);

This should work for you.

Moving x-axis to the top of a plot in matplotlib

You want set_ticks_position rather than set_label_position:

ax.xaxis.set_ticks_position('top') # the rest is the same

This gives me:

enter image description here

How do I compile C++ with Clang?

The command clang is for C, and the command clang++ is for C++.

python re.split() to split by spaces, commas, and periods, but not in cases like 1,000 or 1.50

So you want to split on spaces, and on commas and periods that aren't surrounded by numbers. This should work:

r" |(?<![0-9])[.,](?![0-9])"

Read text file into string. C++ ifstream

To read a whole line from a file into a string, use std::getline like so:

 std::ifstream file("my_file");
 std::string temp;
 std::getline(file, temp);

You can do this in a loop to until the end of the file like so:

 std::ifstream file("my_file");
 std::string temp;
 while(std::getline(file, temp)) {
      //Do with temp
 }

References

http://en.cppreference.com/w/cpp/string/basic_string/getline

http://en.cppreference.com/w/cpp/string/basic_string

How do I request a file but not save it with Wget?

Curl does that by default without any parameters or flags, I would use it for your purposes:

curl $url > /dev/null 2>&1

Curl is more about streams and wget is more about copying sites based on this comparison.

JavaScript Form Submit - Confirm or Cancel Submission Dialog Box

Simple and easy :

_x000D_
_x000D_
<form onSubmit="return confirm('Do you want to submit?') ">_x000D_
  <input type="submit" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

how to enable sqlite3 for php?

This will drown here, but I fixed my problems with this:

As far as I have found out, there is a faulty file in /usr/local/lib called libsqlite3.so.0 which points to libsqlite3.so.0.8.6. It's been installed through the php7.3-* packages as far as I can tell.

I renamed the file in case it was needed for something. With the command:

cd /usr/local/lib sudo mv libsqlite3.so.0 ./libsqlite3.so.0.back

But you can also just delete it: rm libsqlite3.so.0

The thread that lead me to the answer: link

This solved my problems, and I hope they solve yours as well :)

Programmatically get the version number of a DLL

To get it for the assembly that was started (winform, console app, etc...)

using System.Reflection;
...
Assembly.GetEntryAssembly().GetName().Version

How to make Java work with SQL Server?

Maybe a little late, but using different drivers altogether is overkill for a case of user error:

db.dbConnect("jdbc:sqlserver://localhost:1433/muff", "user", "pw" );

should be either one of these:

db.dbConnect("jdbc:sqlserver://localhost\muff", "user", "pw" );

(using named pipe) or:

db.dbConnect("jdbc:sqlserver://localhost:1433", "user", "pw" );

using port number directly; you can leave out 1433 because it's the default port, leaving:

db.dbConnect("jdbc:sqlserver://localhost", "user", "pw" );

How can I convert bigint (UNIX timestamp) to datetime in SQL Server?

If the time is in milliseconds and one need to preserve them:

DECLARE @value VARCHAR(32) = '1561487667713';

SELECT DATEADD(MILLISECOND, CAST(RIGHT(@value, 3) AS INT) - DATEDIFF(MILLISECOND,GETDATE(),GETUTCDATE()), DATEADD(SECOND, CAST(LEFT(@value, 10) AS INT), '1970-01-01T00:00:00'))

Regex to match a 2-digit number (to validate Credit/Debit Card Issue number)

You can use the start (^) and end ($) of line indicators:

^[0-9]{2}$

Some language also have functions that allows you to match against an entire string, where-as you were using a find function. Matching against the entire string will make your regex work as an alternative to the above. The above regex will also work, but the ^ and $ will be redundant.

Easy way to dismiss keyboard?

A slightly more robust method I needed to use recently:

- (void) dismissKeyboard {
    NSArray *windows = [UIApplication sharedApplication].windows;

    for(UIWindow *window in windows) [window endEditing:true];

    //  Or if you're only working with one UIWindow:

    [[UIApplication sharedApplication].keyWindow endEditing:true];
}

I found some of the other "global" methods didn't work (for example, UIWebView & WKWebView refused to resign).

Key existence check in HashMap

Do you mean that you've got code like

if(map.containsKey(key)) doSomethingWith(map.get(key))

all over the place ? Then you should simply check whether map.get(key) returned null and that's it. By the way, HashMap doesn't throw exceptions for missing keys, it returns null instead. The only case where containsKey is needed is when you're storing null values, to distinguish between a null value and a missing value, but this is usually considered bad practice.

How might I schedule a C# Windows Service to perform a task daily?

As others already wrote, a timer is the best option in the scenario you described.

Depending on your exact requirements, checking the current time every minute may not be necessary. If you do not need to perform the action exactly at midnight, but just within one hour after midnight, you can go for Martin's approach of only checking if the date has changed.

If the reason you want to perform your action at midnight is that you expect a low workload on your computer, better take care: The same assumption is often made by others, and suddenly you have 100 cleanup actions kicking off between 0:00 and 0:01 a.m.

In that case you should consider starting your cleanup at a different time. I usually do those things not at clock hour, but at half hours (1.30 a.m. being my personal preference)

Two versions of python on linux. how to make 2.7 the default

All OS comes with a default version of python and it resides in /usr/bin. All scripts that come with the OS (e.g. yum) point this version of python residing in /usr/bin. When you want to install a new version of python you do not want to break the existing scripts which may not work with new version of python.

The right way of doing this is to install the python as an alternate version.

e.g.
wget http://www.python.org/ftp/python/2.7.3/Python-2.7.3.tar.bz2 
tar xf Python-2.7.3.tar.bz2
cd Python-2.7.3
./configure --prefix=/usr/local/
make && make altinstall

Now by doing this the existing scripts like yum still work with /usr/bin/python. and your default python version would be the one installed in /usr/local/bin. i.e. when you type python you would get 2.7.3

This happens because. $PATH variable has /usr/local/bin before usr/bin.

/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin

If python2.7 still does not take effect as the default python version you would need to do

export PATH="/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin"

How do I iterate through table rows and cells in JavaScript?

Using a single for loop:

var table = document.getElementById('tableID');  
var count = table.rows.length;  
for(var i=0; i<count; i++) {    
    console.log(table.rows[i]);    
}

How to add elements of a Java8 stream into an existing List

Erik Allik already gave very good reasons, why you will most likely not want to collect elements of a stream into an existing List.

Anyway, you can use the following one-liner, if you really need this functionality.

But as Stuart Marks explains in his answer, you should never do this, if the streams might be parallel streams - use at your own risk...

list.stream().collect(Collectors.toCollection(() -> myExistingList));

Multi-select dropdown list in ASP.NET

Try this server control which inherits directly from CheckBoxList (free, open source): http://dropdowncheckboxes.codeplex.com/

Giving multiple URL patterns to Servlet Filter

In case you are using the annotation method for filter definition (as opposed to defining them in the web.xml), you can do so by just putting an array of mappings in the @WebFilter annotation:

/**
 * Filter implementation class LoginFilter
 */
@WebFilter(urlPatterns = { "/faces/Html/Employee","/faces/Html/Admin", "/faces/Html/Supervisor"})
public class LoginFilter implements Filter {
    ...

And just as an FYI, this same thing works for servlets using the servlet annotation too:

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet({"/faces/Html/Employee", "/faces/Html/Admin", "/faces/Html/Supervisor"})
public class LoginServlet extends HttpServlet {
    ...

Force overwrite of local file with what's in origin repo?

If you want to overwrite only one file:

git fetch
git checkout origin/master <filepath>

If you want to overwrite all changed files:

git fetch
git reset --hard origin/master

(This assumes that you're working on master locally and you want the changes on the origin's master - if you're on a branch, substitute that in instead.)

How to store array or multiple values in one column

Well, there is an array type in recent Postgres versions (not 100% about PG 7.4). You can even index them, using a GIN or GIST index. The syntaxes are:

create table foo (
  bar  int[] default '{}'
);

select * from foo where bar && array[1] -- equivalent to bar && '{1}'::int[]

create index on foo using gin (bar); -- allows to use an index in the above query

But as the prior answer suggests, it will be better to normalize properly.

How to serialize Object to JSON?

After JAVAEE8 published , now you can use the new JAVAEE API JSON-B (JSR367)

Maven dependency :

<dependency>
    <groupId>javax.json.bind</groupId>
    <artifactId>javax.json.bind-api</artifactId>
    <version>1.0</version>
</dependency>

<dependency>
    <groupId>org.eclipse</groupId>
    <artifactId>yasson</artifactId>
    <version>1.0</version>
</dependency>

<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1</version>
</dependency>

Here is some code snapshot :

Jsonb jsonb = JsonbBuilder.create();
// Two important API : toJson fromJson
String result = jsonb.toJson(listaDePontos);

JSON-P is also updated to 1.1 and more easy to use. JSON-P 1.1 (JSR374)

Maven dependency :

<dependency>
    <groupId>javax.json</groupId>
    <artifactId>javax.json-api</artifactId>
    <version>1.1</version>
</dependency>

<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1</version>
</dependency>

Here is the runnable code snapshot :

String data = "{\"name\":\"Json\","
                + "\"age\": 29,"
                + " \"phoneNumber\": [10000,12000],"
                + "\"address\": \"test\"}";
        JsonObject original = Json.createReader(new StringReader(data)).readObject();
        /**getValue*/
        JsonPointer pAge = Json.createPointer("/age");
        JsonValue v = pAge.getValue(original);
        System.out.println("age is " + v.toString());
        JsonPointer pPhone = Json.createPointer("/phoneNumber/1");
        System.out.println("phoneNumber 2 is " + pPhone.getValue(original).toString());

What does it mean if a Python object is "subscriptable" or not?

I had this same issue. I was doing

arr = []
arr.append["HI"]

So using [ was causing error. It should be arr.append("HI")

Aborting a stash pop in Git

I'm posting here hoping that others my find my answer helpful. I had a similar problem when I tried to do a stash pop on a different branch than the one I had stashed from. On my case I had no files that were uncommitted or in the index but still got into the merge conflicts case (same case as @pid). As others pointed out previously, the failed git stash pop did indeed retain my stash, then A quick git reset HEAD plus going back to my original branch and doing the stash from there did resolve my problem.

How to create a JPA query with LEFT OUTER JOIN

If you have entities A and B without any relation between them and there is strictly 0 or 1 B for each A, you could do:

select a, (select b from B b where b.joinProperty = a.joinProperty) from A a

This would give you an Object[]{a,b} for a single result or List<Object[]{a,b}> for multiple results.

How to delete an SVN project from SVN repository

Disposing of a Working Copy

Subversion doesn't track either the state or the existence of working copies on the server, so there's no server overhead to keeping working copies around. Likewise, there's no need to let the server know that you're going to delete a working copy.

If you're likely to use a working copy again, there's nothing wrong with just leaving it on disk until you're ready to use it again, at which point all it takes is an svn update to bring it up to date and ready for use.

However, if you're definitely not going to use a working copy again, you can safely delete the entire thing using whatever directory removal capabilities your operating system offers. We recommend that before you do so you run svn status and review any files listed in its output that are prefixed with a ? to make certain that they're not of importance.

from: http://svnbook.red-bean.com/en/1.7/svn.tour.cleanup.html

adding x and y axis labels in ggplot2

[Note: edited to modernize ggplot syntax]

Your example is not reproducible since there is no ex1221new (there is an ex1221 in Sleuth2, so I guess that is what you meant). Also, you don't need (and shouldn't) pull columns out to send to ggplot. One advantage is that ggplot works with data.frames directly.

You can set the labels with xlab() and ylab(), or make it part of the scale_*.* call.

library("Sleuth2")
library("ggplot2")
ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area() + 
  xlab("My x label") +
  ylab("My y label") +
  ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

enter image description here

ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area("Nitrogen") + 
  scale_x_continuous("My x label") +
  scale_y_continuous("My y label") +
  ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

enter image description here

An alternate way to specify just labels (handy if you are not changing any other aspects of the scales) is using the labs function

ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area() + 
  labs(size= "Nitrogen",
       x = "My x label",
       y = "My y label",
       title = "Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

which gives an identical figure to the one above.

Could not load type from assembly error

I experienced the same as above after removing signing of assemblies in the solution. The projects would not build.

I found that one of the projects referenced the StrongNamer NuGet package, which modifies the build process and tries to sign non-signed Nuget packages.

After removing the StrongNamer package I was able to build the project again without signing/strong-naming the assemblies.

Script to get the HTTP status code of a list of urls?

This relies on widely available wget, present almost everywhere, even on Alpine Linux.

wget --server-response --spider --quiet "${url}" 2>&1 | awk 'NR==1{print $2}'

The explanations are as follow :

--quiet

Turn off Wget's output.

Source - wget man pages

--spider

[ ... ] it will not download the pages, just check that they are there. [ ... ]

Source - wget man pages

--server-response

Print the headers sent by HTTP servers and responses sent by FTP servers.

Source - wget man pages

What they don't say about --server-response is that those headers output are printed to standard error (sterr), thus the need to redirect to stdin.

The output sent to standard input, we can pipe it to awk to extract the HTTP status code. That code is :

  • the second ($2) non-blank group of characters: {$2}
  • on the very first line of the header: NR==1

And because we want to print it... {print $2}.

wget --server-response --spider --quiet "${url}" 2>&1 | awk 'NR==1{print $2}'

Can someone explain the dollar sign in Javascript?

When using jQuery, the usage of $ symbol as a prefix in the variable name is merely by convention; it is completely optional and serves only to indicate that the variable holds a jQuery object, as in your example.

This means that when another jQuery function needs to be called on the object, you wouldn't need to wrap it in $() again. For instance, compare these:

// the usual way
var item = $(this).parent().parent().find('input');
$(item).hide(); // this is a double wrap, but required for code readability
item.hide(); // this works but is very unclear how a jQuery function is getting called on this 

// with $ prefix
var $item = $(this).parent().parent().find('input');
$item.hide(); // direct call is clear
$($item).hide(); // this works too, but isn't necessary

With the $ prefix the variables already holding jQuery objects are instantly recognizable and the code more readable, and eliminates double/multiple wrapping with $().

How to find out if a file exists in C# / .NET?

Give full path as input. Avoid relative paths.

 return File.Exists(FinalPath);

Quantile-Quantile Plot using SciPy

I think that scipy.stats.probplot will do what you want. See the documentation for more detail.

import numpy as np 
import pylab 
import scipy.stats as stats

measurements = np.random.normal(loc = 20, scale = 5, size=100)   
stats.probplot(measurements, dist="norm", plot=pylab)
pylab.show()

Result

enter image description here

Centering a button vertically in table cell, using Twitter Bootstrap

Add vertical-align: middle; to the td element that contains the button

<td style="vertical-align:middle;">  <--add this to center vertically
  <a href="#" class="btn btn-primary">
    <i class="icon-check icon-white"></i>
  </a>
</td>

How to set background color of a button in Java GUI?

You may or may not have to use setOpaque method to ensure that the colors show up by passing true to the method.

Javascript get Object property Name

If you want to get the key name of myVar object then you can use Object.keys() for this purpose.

var result = Object.keys(myVar); 

alert(result[0]) // result[0] alerts typeA

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

Had the same problem, it was indeed caused by weblogic stupidly using its own opensaml implementation. To solve it, you have to tell it to load classes from WEB-INF/lib for this package in weblogic.xml:

    <prefer-application-packages>
        <package-name>org.opensaml.*</package-name>
    </prefer-application-packages>

maybe <prefer-web-inf-classes>true</prefer-web-inf-classes> would work too.

How do I measure time elapsed in Java?

I built a formatting function based on stuff I stole off SO. I needed a way of "profiling" stuff in log messages, so I needed a fixed length duration message.

public static String GetElapsed(long aInitialTime, long aEndTime, boolean aIncludeMillis)
{
  StringBuffer elapsed = new StringBuffer();

  Map<String, Long> units = new HashMap<String, Long>();

  long milliseconds = aEndTime - aInitialTime;

  long seconds = milliseconds / 1000;
  long minutes = milliseconds / (60 * 1000);
  long hours = milliseconds / (60 * 60 * 1000);
  long days = milliseconds / (24 * 60 * 60 * 1000);

  units.put("milliseconds", milliseconds);
  units.put("seconds", seconds);
  units.put("minutes", minutes);
  units.put("hours", hours);
  units.put("days", days);

  if (days > 0)
  {
    long leftoverHours = hours % 24;
    units.put("hours", leftoverHours);
  }

  if (hours > 0)
  {
    long leftoeverMinutes = minutes % 60;
    units.put("minutes", leftoeverMinutes);
  }

  if (minutes > 0)
  {
    long leftoverSeconds = seconds % 60;
    units.put("seconds", leftoverSeconds);
  }

  if (seconds > 0)
  {
    long leftoverMilliseconds = milliseconds % 1000;
    units.put("milliseconds", leftoverMilliseconds);
  }

  elapsed.append(PrependZeroIfNeeded(units.get("days")) + " days ")
      .append(PrependZeroIfNeeded(units.get("hours")) + " hours ")
      .append(PrependZeroIfNeeded(units.get("minutes")) + " minutes ")
      .append(PrependZeroIfNeeded(units.get("seconds")) + " seconds ")
      .append(PrependZeroIfNeeded(units.get("milliseconds")) + " ms");

  return elapsed.toString();

}

private static String PrependZeroIfNeeded(long aValue)
{
  return aValue < 10 ? "0" + aValue : Long.toString(aValue);
}

And a test class:

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import junit.framework.TestCase;

public class TimeUtilsTest extends TestCase
{

  public void testGetElapsed()
  {
    long start = System.currentTimeMillis();
    GregorianCalendar calendar = (GregorianCalendar) Calendar.getInstance();
    calendar.setTime(new Date(start));

    calendar.add(Calendar.MILLISECOND, 610);
    calendar.add(Calendar.SECOND, 35);
    calendar.add(Calendar.MINUTE, 5);
    calendar.add(Calendar.DAY_OF_YEAR, 5);

    long end = calendar.getTimeInMillis();

    assertEquals("05 days 00 hours 05 minutes 35 seconds 610 ms", TimeUtils.GetElapsed(start, end, true));

  }

}

CSS Printing: Avoiding cut-in-half DIVs between pages?

One pitfall I ran into was a parent element having the 'overflow' attribute set to 'auto'. This negates child div elements with the page-break-inside attribute in the print version. Otherwise, page-break-inside: avoid works fine on Chrome for me.

SQL Server - Adding a string to a text column (concat equivalent)

The + (String Concatenation) does not work on SQL Server for the image, ntext, or text data types.

In fact, image, ntext, and text are all deprecated.

ntext, text, and image data types will be removed in a future version of MicrosoftSQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.

That said if you are using an older version of SQL Server than you want to use UPDATETEXT to perform your concatenation. Which Colin Stasiuk gives a good example of in his blog post String Concatenation on a text column (SQL 2000 vs SQL 2005+).

phonegap open link in browser

At last this post helps me on iOS: http://www.excellentwebworld.com/phonegap-open-a-link-in-safari-or-external-browser/.

Open "CDVwebviewDelegate.m" file and search "shouldStartLoadWithRequest", then add this code to the beginning of the function:

if([[NSString stringWithFormat:@"%@",request.URL] rangeOfString:@"file"].location== NSNotFound) {
    [[UIApplication sharedApplication] openURL:[request URL]];
    return NO;
}

While using navigator.app.loadUrl("http://google.com", {openExternal : true}); for Android is OK.

Via Cordova 3.3.0.

Select mysql query between date?

select * from *table_name* where *datetime_column* between '01/01/2009' and curdate()

or using >= and <= :

select * from *table_name* where *datetime_column* >= '01/01/2009' and *datetime_column* <= curdate()

Batch file to copy directories recursively

You may write a recursive algorithm in Batch that gives you exact control of what you do in every nested subdirectory:

@echo off
call :treeProcess
goto :eof

:treeProcess
rem Do whatever you want here over the files of this subdir, for example:
copy *.* C:\dest\dir
for /D %%d in (*) do (
    cd %%d
    call :treeProcess
    cd ..
)
exit /b

Windows Batch File Looping Through Directories to Process Files?

How to Call Controller Actions using JQuery in ASP.NET MVC

the previous response is ASP.NET only

you need a reference to jquery (perhaps from a CDN): http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js

and then a similar block of code but simpler...

$.ajax({ url: '/Controller/Action/Id',
         success: function(data) { alert(data); }, 
         statusCode : {
             404: function(content) { alert('cannot find resource'); },
             500: function(content) { alert('internal server error'); }
         }, 
         error: function(req, status, errorObj) {
               // handle status === "timeout"
               // handle other errors
         }
});

I've added some necessary handlers, 404 and 500 happen all the time if you are debugging code. Also, a lot of other errors, such as timeout, will filter out through the error handler.

ASP.NET MVC Controllers handle requests, so you just need to request the correct URL and the controller will pick it up. This code sample with work in environments other than ASP.NET

How to filter files when using scp to copy dir recursively?

scp -i /home/<user>/.ssh/id_rsa -o "StrictHostKeyChecking=no" -rp /source/directory/path/[!.]* <target_user>@<target_system:/destination/directory/path

understanding private setters

It's rather simple. Private setters allow you to create read-only public or protected properties.

That's it. That's the only reason.

Yes, you can create a read-only property by only specifying the getter, but with auto-implmeneted properties you are required to specify both get and set, so if you want an auto-implemented property to be read-only, you must use private setters. There is no other way to do it.

It's true that Private setters were not created specificlly for auto-implemented read-only properties, but their use is a bit more esoteric for other reasons, largely centering around read-only properties and the use of reflection and serialization.

How do I show/hide a UIBarButtonItem?

This is long way down the answer list, but just in case somebody wants an easy copy and paste for the swift solution, here it is

func hideToolbarItem(button: UIBarButtonItem, withToolbar toolbar: UIToolbar) {
    var toolbarButtons: [UIBarButtonItem] = toolbar.items!
    toolbarButtons.removeAtIndex(toolbarButtons.indexOf(button)!)
    toolbar.setItems(toolbarButtons, animated: true)
}

func showToolbarItem(button: UIBarButtonItem, inToolbar toolbar: UIToolbar, atIndex index: Int) {
    var toolbarButtons: [UIBarButtonItem] = toolbar.items!
    if !toolbarButtons.contains(button) {
        toolbarButtons.insert(button, atIndex: index)
        toolbar.setItems(toolbarButtons, animated:true);
    }
}

How to use LINQ to select object with minimum or maximum property value

So you are asking for ArgMin or ArgMax. C# doesn't have a built-in API for those.

I've been looking for a clean and efficient (O(n) in time) way to do this. And I think I found one:

The general form of this pattern is:

var min = data.Select(x => (key(x), x)).Min().Item2;
                            ^           ^       ^
              the sorting key           |       take the associated original item
                                Min by key(.)

Specially, using the example in original question:

For C# 7.0 and above that supports value tuple:

var youngest = people.Select(p => (p.DateOfBirth, p)).Min().Item2;

For C# version before 7.0, anonymous type can be used instead:

var youngest = people.Select(p => new {age = p.DateOfBirth, ppl = p}).Min().ppl;

They work because both value tuple and anonymous type have sensible default comparers: for (x1, y1) and (x2, y2), it first compares x1 vs x2, then y1 vs y2. That's why the built-in .Min can be used on those types.

And since both anonymous type and value tuple are value types, they should be both very efficient.

NOTE

In my above ArgMin implementations I assumed DateOfBirth to take type DateTime for simplicity and clarity. The original question asks to exclude those entries with null DateOfBirth field:

Null DateOfBirth values are set to DateTime.MaxValue in order to rule them out of the Min consideration (assuming at least one has a specified DOB).

It can be achieved with a pre-filtering

people.Where(p => p.DateOfBirth.HasValue)

So it's immaterial to the question of implementing ArgMin or ArgMax.

NOTE 2

The above approach has a caveat that when there are two instances that have the same min value, then the Min() implementation will try to compare the instances as a tie-breaker. However, if the class of the instances does not implement IComparable, then a runtime error will be thrown:

At least one object must implement IComparable

Luckily, this can still be fixed rather cleanly. The idea is to associate a distanct "ID" with each entry that serves as the unambiguous tie-breaker. We can use an incremental ID for each entry. Still using the people age as example:

var youngest = Enumerable.Range(0, int.MaxValue)
               .Zip(people, (idx, ppl) => (ppl.DateOfBirth, idx, ppl)).Min().Item3;

jQuery add class .active on menu

No other "addClass" methods worked for me when adding a class to an 'a' element on menu except this one:

$(function () {
        var url = window.location.pathname,
    urlRegExp = new RegExp(url.replace(/\/$/, '') + "$");  
        $('a').each(function () {
                            if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
                $(this).addClass('active');
            }
        });
    });

This took me four hours to find it.

Check if a specific tab page is selected (active)

For whatever reason the above would not work for me. This is what did:

if (tabControl.SelectedTab.Name == "tabName" )
{
     .. do stuff
}

where tabControl.SelectedTab.Name is the name attribute assigned to the page in the tabcontrol itself.

Best way to create unique token in Rails?

def generate_token
    self.token = Digest::SHA1.hexdigest("--#{ BCrypt::Engine.generate_salt }--")
end

How to search JSON data in MySQL?

If you have MySQL version >= 5.7, then you can try this:

SELECT JSON_EXTRACT(name, "$.id") AS name
FROM table
WHERE JSON_EXTRACT(name, "$.id") > 3

Output:

+-------------------------------+
| name                          | 
+-------------------------------+
| {"id": "4", "name": "Betty"}  | 
+-------------------------------+


Please check MySQL reference manual for more details:
https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html

How to split elements of a list?

Do not use list as variable name. You can take a look at the following code too:

clist = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847', 'element5']
clist = [x[:x.index('\t')] if '\t' in x else x for x in clist]

Or in-place editing:

for i,x in enumerate(clist):
    if '\t' in x:
        clist[i] = x[:x.index('\t')]

Convert MFC CString to integer

CString s;
int i;
i = _wtoi(s); // if you use wide charater formats
i = _atoi(s); // otherwise

In AVD emulator how to see sdcard folder? and Install apk to AVD?

I have used the following procedure.

Procedure to install the apk files in Android Emulator(AVD):

Check your installed directory(ex: C:\Program Files (x86)\Android\android-sdk\platform-tools), whether it has the adb.exe or not). If not present in this folder, then download the attachment here, extract the zip files. You will get adb files, copy and paste those three files inside tools folder

Run AVD manager from C:\Program Files (x86)\Android\android-sdk and start the Android Emulator.

Copy and paste the apk file inside the C:\Program Files (x86)\Android\android-sdk\platform-tools

  • Go to Start -> Run -> cmd

  • Type cd “C:\Program Files (x86)\Android\android-sdk\platform-tools”

  • Type adb install example.apk

  • After getting success command

  • Go to Application icon in Android emulator, we can see the your application

Finding sum of elements in Swift array

In Swift 4 You can also constrain the sequence elements to Numeric protocol to return the sum of all elements in the sequence as follow

extension Sequence where Element: Numeric {
    /// Returns the sum of all elements in the collection
    func sum() -> Element { return reduce(0, +) }
}

edit/update:

Xcode 10.2 • Swift 5 or later

We can simply constrain the sequence elements to the new AdditiveArithmetic protocol to return the sum of all elements in the collection

extension Sequence where Element: AdditiveArithmetic {
    func sum() -> Element {
        return reduce(.zero, +)
    }
}

Xcode 11 • Swift 5.1 or later

extension Sequence where Element: AdditiveArithmetic {
    func sum() -> Element { reduce(.zero, +) }
}

let numbers = [1,2,3]
numbers.sum()    // 6

let doubles = [1.5, 2.7, 3.0]
doubles.sum()    // 7.2

To sum a property of a custom object we can extend Sequence to take a predicate to return a value that conforms to AdditiveArithmetic:

extension Sequence  {
    func sum<T: AdditiveArithmetic>(_ predicate: (Element) -> T) -> T { reduce(.zero) { $0 + predicate($1) } }
}

Usage:

struct Product {
    let id: String
    let price: Decimal
}

let products: [Product] = [.init(id: "abc", price: 21.9),
                           .init(id: "xyz", price: 19.7),
                           .init(id: "jkl", price: 2.9)
]

products.sum(\.price)  // 44.5

How to manually set an authenticated user in Spring Security / SpringMVC

Turn on debug logging to get a better picture of what is going on.

You can tell if the session cookies are being set by using a browser-side debugger to look at the headers returned in HTTP responses. (There are other ways too.)

One possibility is that SpringSecurity is setting secure session cookies, and your next page requested has an "http" URL instead of an "https" URL. (The browser won't send a secure cookie for an "http" URL.)

Understanding `scale` in R

log simply takes the logarithm (base e, by default) of each element of the vector.
scale, with default settings, will calculate the mean and standard deviation of the entire vector, then "scale" each element by those values by subtracting the mean and dividing by the sd. (If you use scale(x, scale=FALSE), it will only subtract the mean but not divide by the std deviation.)

Note that this will give you the same values

   set.seed(1)
   x <- runif(7)

   # Manually scaling
   (x - mean(x)) / sd(x)

   scale(x)

How to convert a selection to lowercase or uppercase in Sublime Text

As a bonus for setting up a Title Case shortcut key Ctrl+kt (while holding Ctrl, press k and t), go to Preferences --> Keybindings-User

If you have a blank file open and close with the square brackets:

[  { "keys": ["ctrl+k", "ctrl+t"], "command": "title_case" } ]

Otherwise if you already have stuff in there, just make sure if it comes after another command to prepend a comma "," and add:

{ "keys": ["ctrl+k", "ctrl+t"], "command": "title_case" }

Is it possible to CONTINUE a loop from an exception?

In the construct you have provided, you don't need a CONTINUE. Once the exception is handled, the statement after the END is performed, assuming your EXCEPTION block doesn't terminate the procedure. In other words, it will continue on to the next iteration of the user_rec loop.

You also need to SELECT INTO a variable inside your BEGIN block:

SELECT attr INTO v_attr FROM attribute_table...

Obviously you must declare v_attr as well...

How to append rows to an R data frame

A more generic solution for might be the following.

    extendDf <- function (df, n) {
    withFactors <- sum(sapply (df, function(X) (is.factor(X)) )) > 0
    nr          <- nrow (df)
    colNames    <- names(df)
    for (c in 1:length(colNames)) {
        if (is.factor(df[,c])) {
            col         <- vector (mode='character', length = nr+n) 
            col[1:nr]   <- as.character(df[,c])
            col[(nr+1):(n+nr)]<- rep(col[1], n)  # to avoid extra levels
            col         <- as.factor(col)
        } else {
            col         <- vector (mode=mode(df[1,c]), length = nr+n)
            class(col)  <- class (df[1,c])
            col[1:nr]   <- df[,c] 
        }
        if (c==1) {
            newDf       <- data.frame (col ,stringsAsFactors=withFactors)
        } else {
            newDf[,c]   <- col 
        }
    }
    names(newDf) <- colNames
    newDf
}

The function extendDf() extends a data frame with n rows.

As an example:

aDf <- data.frame (l=TRUE, i=1L, n=1, c='a', t=Sys.time(), stringsAsFactors = TRUE)
extendDf (aDf, 2)
#      l i n c                   t
# 1  TRUE 1 1 a 2016-07-06 17:12:30
# 2 FALSE 0 0 a 1970-01-01 01:00:00
# 3 FALSE 0 0 a 1970-01-01 01:00:00

system.time (eDf <- extendDf (aDf, 100000))
#    user  system elapsed 
#   0.009   0.002   0.010
system.time (eDf <- extendDf (eDf, 100000))
#    user  system elapsed 
#   0.068   0.002   0.070

Can I change the height of an image in CSS :before/:after pseudo-elements?

You can change the height or width of the Before or After element like this:

.element:after {
  display: block;
  content: url('your-image.png');
  height: 50px; //add any value you need for height or width
  width: 50px;
}

How to know that a string starts/ends with a specific string in jQuery?

You can always extend String prototype like this:

//  Checks that string starts with the specific string
if (typeof String.prototype.startsWith != 'function') {
    String.prototype.startsWith = function (str) {
        return this.slice(0, str.length) == str;
    };
}

//  Checks that string ends with the specific string...
if (typeof String.prototype.endsWith != 'function') {
    String.prototype.endsWith = function (str) {
        return this.slice(-str.length) == str;
    };
}

And use it like this:

var str = 'Hello World';

if( str.startsWith('Hello') ) {
   // your string starts with 'Hello'
}

if( str.endsWith('World') ) {
   // your string ends with 'World'
}

How to setup Tomcat server in Netbeans?

If TomCat is install. Perhaps it is not installed Java EE. Services-> plug-ins-> additional plug-ins-> in the search dial tomcat. and install the module java ee. then in the services, servers, add the tomcat server.

Converting a generic list to a CSV string

The problem with String.Join is that you are not handling the case of a comma already existing in the value. When a comma exists then you surround the value in Quotes and replace all existing Quotes with double Quotes.

String.Join(",",{"this value has a , in it","This one doesn't", "This one , does"});

See CSV Module

Unable to run Java code with Intellij IDEA

-First Move Your Code Files in side the "src" Folder

-Make sure your Main method is declared like the following

   public class Main {
         public static void main(String []args){


       }
    }

then:

  • Go to Project configurations
  • select Java application,
  • check allow parallel run
  • and select your main class

and it should work

IIS: Idle Timeout vs Recycle

From here:

One way to conserve system resources is to configure idle time-out settings for the worker processes in an application pool. When these settings are configured, a worker process will shut down after a specified period of inactivity. The default value for idle time-out is 20 minutes.

Also check Why is the IIS default app pool recycle set to 1740 minutes?

If you have a just a few sites on your server and you want them to always load fast then set this to zero. Otherwise, when you have 20 minutes without any traffic then the app pool will terminate so that it can start up again on the next visit. The problem is that the first visit to an app pool needs to create a new w3wp.exe worker process which is slow because the app pool needs to be created, ASP.NET or another framework needs to be loaded, and then your application needs to be loaded. That can take a few seconds. Therefore I set that to 0 every chance I have, unless it’s for a server that hosts a lot of sites that don’t always need to be running.

How to map an array of objects in React

What you need is to map your array of objects and remember that every item will be an object, so that you will use for instance dot notation to take the values of the object.

In your component

 [
    {
        name: 'Sam',
        email: '[email protected]'
    },

    {
        name: 'Ash',
        email: '[email protected]'
    }
].map((anObjectMapped, index) => {
    return (
        <p key={`${anObjectMapped.name}_{anObjectMapped.email}`}>
            {anObjectMapped.name} - {anObjectMapped.email}
        </p>
    );
})

And remember when you put an array of jsx it has a different meaning and you can not just put object in your render method as you can put an array.

Take a look at my answer at mapping an array to jsx

CSS align one item right with flexbox

To align one flex child to the right set it withmargin-left: auto;

From the flex spec:

One use of auto margins in the main axis is to separate flex items into distinct "groups". The following example shows how to use this to reproduce a common UI pattern - a single bar of actions with some aligned on the left and others aligned on the right.

.wrap div:last-child {
  margin-left: auto;
}

Updated fiddle

_x000D_
_x000D_
.wrap {_x000D_
  display: flex;_x000D_
  background: #ccc;_x000D_
  width: 100%;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.wrap div:last-child {_x000D_
  margin-left: auto;_x000D_
}_x000D_
.result {_x000D_
  background: #ccc;_x000D_
  margin-top: 20px;_x000D_
}_x000D_
.result:after {_x000D_
  content: '';_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
.result div {_x000D_
  float: left;_x000D_
}_x000D_
.result div:last-child {_x000D_
  float: right;_x000D_
}
_x000D_
<div class="wrap">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<!-- DESIRED RESULT -->_x000D_
<div class="result">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note:

You could achieve a similar effect by setting flex-grow:1 on the middle flex item (or shorthand flex:1) which would push the last item all the way to the right. (Demo)

The obvious difference however is that the middle item becomes bigger than it may need to be. Add a border to the flex items to see the difference.

Demo

_x000D_
_x000D_
.wrap {_x000D_
  display: flex;_x000D_
  background: #ccc;_x000D_
  width: 100%;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.wrap div {_x000D_
  border: 3px solid tomato;_x000D_
}_x000D_
.margin div:last-child {_x000D_
  margin-left: auto;_x000D_
}_x000D_
.grow div:nth-child(2) {_x000D_
  flex: 1;_x000D_
}_x000D_
.result {_x000D_
  background: #ccc;_x000D_
  margin-top: 20px;_x000D_
}_x000D_
.result:after {_x000D_
  content: '';_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
.result div {_x000D_
  float: left;_x000D_
}_x000D_
.result div:last-child {_x000D_
  float: right;_x000D_
}
_x000D_
<div class="wrap margin">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<div class="wrap grow">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<!-- DESIRED RESULT -->_x000D_
<div class="result">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why does find -exec mv {} ./target/ + not work?

I encountered the same issue on Mac OSX, using a ZSH shell: in this case there is no -t option for mv, so I had to find another solution. However the following command succeeded:

find .* * -maxdepth 0 -not -path '.git' -not -path '.backup' -exec mv '{}' .backup \;

The secret was to quote the braces. No need for the braces to be at the end of the exec command.

I tested under Ubuntu 14.04 (with BASH and ZSH shells), it works the same.

However, when using the + sign, it seems indeed that it has to be at the end of the exec command.

How to bind RadioButtons to an enum?

I would use the RadioButtons in a ListBox, and then bind to the SelectedValue.

This is an older thread about this topic, but the base idea should be the same: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/323d067a-efef-4c9f-8d99-fecf45522395/

How to show uncommitted changes in Git and some Git diffs in detail

For me, the only thing which worked is

git diff HEAD

including the staged files, git diff --cached only shows staged files.

Can I use if (pointer) instead of if (pointer != NULL)?

Yes, you can. The ability to compare values to zeros implicitly has been inherited from C, and is there in all versions of C++. You can also use if (!pointer) to check pointers for NULL.

Is there any simple way to convert .xls file to .csv file? (Excel)

Install these 2 packages

<packages>
  <package id="ExcelDataReader" version="3.3.0" targetFramework="net451" />
  <package id="ExcelDataReader.DataSet" version="3.3.0" targetFramework="net451" />
</packages>

Helper function

using ExcelDataReader;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExcelToCsv
{
    public class ExcelFileHelper
    {
        public static bool SaveAsCsv(string excelFilePath, string destinationCsvFilePath)
        {

            using (var stream = new FileStream(excelFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                IExcelDataReader reader = null;
                if (excelFilePath.EndsWith(".xls"))
                {
                    reader = ExcelReaderFactory.CreateBinaryReader(stream);
                }
                else if (excelFilePath.EndsWith(".xlsx"))
                {
                    reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
                }

                if (reader == null)
                    return false;

                var ds = reader.AsDataSet(new ExcelDataSetConfiguration()
                {
                    ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
                    {
                        UseHeaderRow = false
                    }
                });

                var csvContent = string.Empty;
                int row_no = 0;
                while (row_no < ds.Tables[0].Rows.Count)
                {
                    var arr = new List<string>();
                    for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
                    {
                        arr.Add(ds.Tables[0].Rows[row_no][i].ToString());
                    }
                    row_no++;
                    csvContent += string.Join(",", arr) + "\n";
                }
                StreamWriter csv = new StreamWriter(destinationCsvFilePath, false);
                csv.Write(csvContent);
                csv.Close();
                return true;
            }
        }
    }
}

Usage :

var excelFilePath = Console.ReadLine();
string output = Path.ChangeExtension(excelFilePath, ".csv");
ExcelFileHelper.SaveAsCsv(excelFilePath, output);

How to create a scrollable Div Tag Vertically?

Well, your code worked for me (running Chrome 5.0.307.9 and Firefox 3.5.8 on Ubuntu 9.10), though I switched

overflow-y: scroll;

to

overflow-y: auto;

Demo page over at: http://davidrhysthomas.co.uk/so/tableDiv.html.

xhtml below:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
    <META http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <title>Div in table</title>
    <link rel="stylesheet" type="text/css" href="css/stylesheet.css" />

        <style type="text/css" media="all">

        th      {border-bottom: 2px solid #ccc; }

        th,td       {padding: 0.5em 1em; 
                margin: 0;
                border-collapse: collapse;
                }

        tr td:first-child
                {border-right: 2px solid #ccc; } 

        td > div    {width: 249px;
                height: 299px;
                background-color:Gray;
                overflow-y: auto;
                max-width:230px;
                max-height:100px;
                }
        </style>

    <script type="text/javascript" src="js/jquery.js"></script>

    <script type="text/javascript">

    </script>

</head>

<body>

<div>

    <table>

        <thead>
            <tr><th>This is column one</th><th>This is column two</th><th>This is column three</th>
        </thead>



        <tbody>
            <tr><td>This is row one</td><td>data point 2.1</td><td>data point 3.1</td>
            <tr><td>This is row two</td><td>data point 2.2</td><td>data point 3.2</td>
            <tr><td>This is row three</td><td>data point 2.3</td><td>data point 3.3</td>
            <tr><td>This is row four</td><td><div><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ultricies mattis dolor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum a accumsan purus. Vivamus semper tempus nisi et convallis. Aliquam pretium rutrum lacus sed auctor. Phasellus viverra elit vel neque lacinia ut dictum mauris aliquet. Etiam elementum iaculis lectus, laoreet tempor ligula aliquet non. Mauris ornare adipiscing feugiat. Vivamus condimentum luctus tortor venenatis fermentum. Maecenas eu risus nec leo vehicula mattis. In nisi nibh, fermentum vitae tincidunt non, mattis eu metus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nunc vel est purus. Ut accumsan, elit non lacinia porta, nibh magna pretium ligula, sed iaculis metus tortor aliquam urna. Duis commodo tincidunt aliquam. Maecenas in augue ut ligula sodales elementum quis vitae risus. Vivamus mollis blandit magna, eu fringilla velit auctor sed.</p></div></td><td>data point 3.4</td>
            <tr><td>This is row five</td><td>data point 2.5</td><td>data point 3.5</td>
            <tr><td>This is row six</td><td>data point 2.6</td><td>data point 3.6</td>
            <tr><td>This is row seven</td><td>data point 2.7</td><td>data point 3.7</td>
        </body>



    </table>

</div>

</body>

</html>

What are the dark corners of Vim your mom never told you about?

Try using perltidy for formatting by = normal-mode command

:set equalprg=perltidy

Convert date to another timezone in JavaScript

You can try this also for convert date timezone to India:

var indianTimeZoneVal = new Date().toLocaleString('en-US', {timeZone: 'Asia/Kolkata'});
var indainDateObj = new Date(indianTimeZoneVal);
indainDateObj.setHours(indainDateObj.getHours() + 5);
indainDateObj.setMinutes(indainDateObj.getMinutes() + 30);
console.log(indainDateObj);

How do I simulate a low bandwidth, high latency environment?

Try WANem

WANem is a Wide Area Network Emulator, meant to provide a real experience of a Wide Area Network/Internet, during application development / testing over a LAN environment.

How to see PL/SQL Stored Function body in Oracle

If is a package then you can get the source for that with:

    select text from all_source where name = 'PADCAMPAIGN' 
    and type = 'PACKAGE BODY'
    order by line;

Oracle doesn't store the source for a sub-program separately, so you need to look through the package source for it.

Note: I've assumed you didn't use double-quotes when creating that package, but if you did , then use

    select text from all_source where name = 'pAdCampaign' 
    and type = 'PACKAGE BODY'
    order by line;

How does System.out.print() work?

System.out is just an instance of PrintStream. You can check its JavaDoc. Its variability is based on method overloading (multiple methods with the same name, but with different parameters).

This print stream is sending its output to so called standard output.


In your question you mention a technique called variadic functions (or varargs). Unfortunately that is not supported by PrintStream#print, so you must be mistaking this with something else. However it is very easy to implement these in Java. Just check the documentation.


And if you are curious how Java knows how to concatenate non-string variables "foo" + 1 + true + myObj, it is mainly responsibility of a Java compiler.

When there is no variable involved in the concatenation, the compiler simply concatenates the string. When there is a variable involved, the concatenation is translated into StringBuilder#append chain. There is no concatenation instruction in the resulting byte code; i.e. the + operator (when talking about string concatenation) is resolved during the compilation.

All types in Java can be converted to string (int via methods in Integer class, boolean via methods in Boolean class, objects via their own #toString, ...). You can check StringBuilder's source code if you are interested.


UPDATE: I was curious myself and checked (using javap) what my example System.out.println("foo" + 1 + true + myObj) compiles into. The result:

System.out.println(new StringBuilder("foo1true").append(myObj).toString());

How do I update/upsert a document in Mongoose?

Here's the simplest way to create/update while also calling the middleware and validators.

Contact.findOne({ phone: request.phone }, (err, doc) => {
    const contact = (doc) ? doc.set(request) : new Contact(request);

    contact.save((saveErr, savedContact) => {
        if (saveErr) throw saveErr;
        console.log(savedContact);
    });
})

Using ls to list directories and their total sizes

To display current directory's files and subdirectories sizes recursively:

du -h .

To display the same size information but without printing their sub directories recursively (which can be a huge list), just use the --max-depth option:

du -h --max-depth=1 .

The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported

I forgot to select the column (or set/map the property to a column value):

IQueryable<SampleTable> queryable = from t in dbcontext.SampleTable
                                    where ...
                                    select new DataModel { Name = t.Name };

Calling queryable.OrderBy("Id") will throw exception, even though DataModel has property Id defined.

The correct query is:

IQueryable<SampleTable> queryable = from t in dbcontext.SampleTable
                                    where ...
                                    select new DataModel { Name = t.Name, Id = t.Id };

How can I generate a random number in a certain range?

To extend what Rahul Gupta said:

You can use Java function int random = Random.nextInt(n).
This returns a random int in the range [0, n-1].

I.e., to get the range [20, 80] use:

final int random = new Random().nextInt(61) + 20; // [0, 60] + 20 => [20, 80]

To generalize more:

final int min = 20;
final int max = 80;
final int random = new Random().nextInt((max - min) + 1) + min;

HTTP Basic Authentication - what's the expected web browser experience?

You might have old invalid username/password cached in your browser. Try clearing them and check again.

If you are using IE and somesite.com is in your Intranet security zone, IE may be sending your windows credentials automatically.

How to add double quotes to a string that is inside a variable?

If I understand your question properly, maybe you can try this:

string title = string.Format("<div>\"{0}\"</div>", "some text");

How to call a parent method from child class in javascript?

ES6 style allows you to use new features, such as super keyword. super keyword it's all about parent class context, when you are using ES6 classes syntax. As a very simple example, checkout:

class Foo {
    static classMethod() {
        return 'hello';
    }
}

class Bar extends Foo {
    static classMethod() {
        return super.classMethod() + ', too';
    }
}
Bar.classMethod(); // 'hello, too'

Also, you can use super to call parent constructor:

class Foo {}

class Bar extends Foo {
    constructor(num) {
        let tmp = num * 2; // OK
        this.num = num; // ReferenceError
        super();
        this.num = num; // OK
    }
}

And of course you can use it to access parent class properties super.prop. So, use ES6 and be happy.

ssh: Could not resolve hostname [hostname]: nodename nor servname provided, or not known

If you're on Mac, restarting the DNS responder fixed the issue for me.

sudo killall -HUP mDNSResponder

How to pass variables from one php page to another without form?

use the get method in the url. If you want to pass over a variable called 'phone' as 0001112222:

<a href='whatever.php?phone=0001112222'>click</a>

then on the next page (whatever.php) you can access this var via:

$_GET['phone']

What is the difference between Session.Abandon() and Session.Clear()

this code works and dont throw any exception:

Session.Abandon();  
Session["tempKey1"] = "tempValue1";

It's because when the Abandon method is called, the current Session object is queued for deletion but is not actually deleted until all of the script commands on the current page have been processed. This means that you can access variables stored in the Session object on the same page as the call to the Abandon method but not in any subsequent Web pages.

For example, in the following script, the third line prints the value Mary. This is because the Session object is not destroyed until the server has finished processing the script.

<% 
  Session.Abandon  
  Session("MyName") = "Mary" 
  Reponse.Write(Session("MyName")) 
%>

If you access the variable MyName on a subsequent Web page, it is empty. This is because MyName was destroyed with the previous Session object when the page containing the previous example finished processing.

from MSDN Session.Abandon

How to get a random number in Ruby

Maybe it help you. I use this in my app

https://github.com/rubyworks/facets
class String

  # Create a random String of given length, using given character set
  #
  # Character set is an Array which can contain Ranges, Arrays, Characters
  #
  # Examples
  #
  #     String.random
  #     => "D9DxFIaqR3dr8Ct1AfmFxHxqGsmA4Oz3"
  #
  #     String.random(10)
  #     => "t8BIna341S"
  #
  #     String.random(10, ['a'..'z'])
  #     => "nstpvixfri"
  #
  #     String.random(10, ['0'..'9'] )
  #     => "0982541042"
  #
  #     String.random(10, ['0'..'9','A'..'F'] )
  #     => "3EBF48AD3D"
  #
  #     BASE64_CHAR_SET =  ["A".."Z", "a".."z", "0".."9", '_', '-']
  #     String.random(10, BASE64_CHAR_SET)
  #     => "xM_1t3qcNn"
  #
  #     SPECIAL_CHARS = ["!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-", "_", "=", "+", "|", "/", "?", ".", ",", ";", ":", "~", "`", "[", "]", "{", "}", "<", ">"]
  #     BASE91_CHAR_SET =  ["A".."Z", "a".."z", "0".."9", SPECIAL_CHARS]
  #     String.random(10, BASE91_CHAR_SET)
  #      => "S(Z]z,J{v;"
  #
  # CREDIT: Tilo Sloboda
  #
  # SEE: https://gist.github.com/tilo/3ee8d94871d30416feba
  #
  # TODO: Move to random.rb in standard library?

  def self.random(len=32, character_set = ["A".."Z", "a".."z", "0".."9"])
    chars = character_set.map{|x| x.is_a?(Range) ? x.to_a : x }.flatten
    Array.new(len){ chars.sample }.join
  end

end

https://github.com/rubyworks/facets/blob/5569b03b4c6fd25897444a266ffe25872284be2b/lib/core/facets/string/random.rb

It works fine for me

how to download image from any web page in java

(throws IOException)

Image image = null;
try {
    URL url = new URL("http://www.yahoo.com/image_to_read.jpg");
    image = ImageIO.read(url);
} catch (IOException e) {
}

See javax.imageio package for more info. That's using the AWT image. Otherwise you could do:

 URL url = new URL("http://www.yahoo.com/image_to_read.jpg");
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
   out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();

And you may then want to save the image so do:

FileOutputStream fos = new FileOutputStream("C://borrowed_image.jpg");
fos.write(response);
fos.close();

Add or change a value of JSON key with jquery or javascript

Just like you would for any other variable, you just set it

alert(data.ID);
data.ID = "bar";  //dot notation 
alert(data.ID);    
data.userID = 123456;
data["address"] = "123 some street"; //bracket notation

Counting null and non-null values in a single query

for non nulls

select count(a)
from us

for nulls

select count(*)
from us

minus 

select count(a)
from us

Hence

SELECT COUNT(A) NOT_NULLS
FROM US

UNION

SELECT COUNT(*) - COUNT(A) NULLS
FROM US

ought to do the job

Better in that the column titles come out correct.

SELECT COUNT(A) NOT_NULL, COUNT(*) - COUNT(A) NULLS
FROM US

In some testing on my system, it costs a full table scan.

Best approach to real time http streaming to HTML5 video client

Take a look at this solution. As I know, Flashphoner allows to play Live audio+video stream in the pure HTML5 page.

They use MPEG1 and G.711 codecs for playback. The hack is rendering decoded video to HTML5 canvas element and playing decoded audio via HTML5 audio context.

Smart cast to 'Type' is impossible, because 'variable' is a mutable property that could have been changed by this time

For there to be a Smart Cast of the properties, the data type of the property must be the class that contains the method or behavior that you want to access and NOT that the property is of the type of the super class.


e.g on Android

Be:

class MyVM : ViewModel() {
    fun onClick() {}
}

Solution:

From: private lateinit var viewModel: ViewModel
To: private lateinit var viewModel: MyVM

Usage:

viewModel = ViewModelProvider(this)[MyVM::class.java]
viewModel.onClick {}

GL

Splitting applicationContext to multiple files

I find the following setup the easiest.

Use the default config file loading mechanism of DispatcherServlet:

The framework will, on initialization of a DispatcherServlet, look for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and create the beans defined there (overriding the definitions of any beans defined with the same name in the global scope).

In your case, simply create a file intrafest-servlet.xml in the WEB-INF dir and don't need to specify anything specific information in web.xml.

In intrafest-servlet.xml file you can use import to compose your XML configuration.

<beans>
  <bean id="bean1" class="..."/>
  <bean id="bean2" class="..."/>

  <import resource="foo-services.xml"/>
  <import resource="foo-persistence.xml"/>
</beans>

Note that the Spring team actually prefers to load multiple config files when creating the (Web)ApplicationContext. If you still want to do it this way, I think you don't need to specify both context parameters (context-param) and servlet initialization parameters (init-param). One of the two will do. You can also use commas to specify multiple config locations.

Using port number in Windows host file

What you want can be achieved by modifying the hosts file through Fiddler 2 application.

Follow these steps:

  1. Install Fiddler2

  2. Navigate to Fiddler2 menu:- Tools > HOSTS.. (Click to select)

  3. Add a line like this:-

    localhost:8080 www.mydomainname.com

  4. Save the file & then checkout www.mydomainname.com in browser.

use "netsh wlan set hostednetwork ..." to create a wifi hotspot and the authentication can't work correctly

For me, running the ad-hoc network on Windows 8.1, it was two things:

  • I had to set a static IP on my Android (under Advanced Options under where you type the Wifi password)
  • I had to use a password 8 characters long

Any IP will allow you to connect, but if you want internet access the static IP should match the subnet from the shared internet connection.

I'm not sure why I couldn't get a longer password to work, but it's worth a try. Maybe a more knowledgeable person could fill us in.

mappedBy reference an unknown target entity property

The mappedBy attribute is referencing customer while the property is mCustomer, hence the error message. So either change your mapping into:

/** The collection of stores. */
@OneToMany(mappedBy = "mCustomer", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Collection<Store> stores;

Or change the entity property into customer (which is what I would do).

The mappedBy reference indicates "Go look over on the bean property named 'customer' on the thing I have a collection of to find the configuration."

How do I POST XML data to a webservice with Postman?

Send XML requests with the raw data type, then set the Content-Type to text/xml.


  1. After creating a request, use the dropdown to change the request type to POST.

    Set request type to POST

  2. Open the Body tab and check the data type for raw.

    Setting data type to raw

  3. Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)

    Selecting content-type text/xml

  4. Enter your raw XML data into the input field below

    Example of XML request in Postman

  5. Click Send to submit your XML Request to the specified server.

    Clicking the Send button

How do I get just the date when using MSSQL GetDate()?

For SQL Server 2008, the best and index friendly way is

DELETE from Table WHERE Date > CAST(GETDATE() as DATE);

For prior SQL Server versions, date maths will work faster than a convert to varchar. Even converting to varchar can give you the wrong result, because of regional settings.

DELETE from Table WHERE Date > DATEDIFF(d, 0, GETDATE());

Note: it is unnecessary to wrap the DATEDIFF with another DATEADD

Git push requires username and password

This is what worked for me:

git remote set-url origin https://[email protected]/username/reponame.git

Example:

git remote set-url origin https://[email protected]/jsmith/master.git

How to embed PDF file with responsive width

I did that mistake once - embedding PDF files in HTML pages. I will suggest that you use a JavaScript library for displaying the content of the PDF. Like https://github.com/mozilla/pdf.js/

How to check if a JavaScript variable is NOT undefined?

var lastname = "Hi";

if(typeof lastname !== "undefined")
{
  alert("Hi. Variable is defined.");
} 

What is the proper declaration of main in C++?

The exact wording of the latest published standard (C++14) is:

An implementation shall allow both

  • a function of () returning int and

  • a function of (int, pointer to pointer to char) returning int

as the type of main.

This makes it clear that alternative spellings are permitted so long as the type of main is the type int() or int(int, char**). So the following are also permitted:

  • int main(void)
  • auto main() -> int
  • int main ( )
  • signed int main()
  • typedef char **a; typedef int b, e; e main(b d, a c)

Java executors: how to be notified, without blocking, when a task completes?

If you want to make sure that no tasks will run at the same time then use a SingleThreadedExecutor. The tasks will be processed in the order the are submitted. You don't even need to hold the tasks, just submit them to the exec.

What is the default scope of a method in Java?

Without an access modifier, a class member is accessible throughout the package in which it's declared. You can learn more from the Java Language Specification, §6.6.

Members of an interface are always publicly accessible, whether explicitly declared or not.

Broken references in Virtualenvs

What fixed it for me was just uninstalling python3 and pipenv then reinstalling them.

brew uninstall pipenv
brew uninstall python3
brew install python3 
brew install pipenv

Set up adb on Mac OS X

This Works Flawless....

In terminal Run both commands next to each other

export ANDROID_HOME=/Users/$USER/Library/Android/sdk

export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

C# catch a stack overflow exception

Yes from CLR 2.0 stack overflow is considered a non-recoverable situation. So the runtime still shut down the process.

For details please see the documentation http://msdn.microsoft.com/en-us/library/system.stackoverflowexception.aspx

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Since .NET 4.5 the Validators use data-attributes and bounded Javascript to do the validation work, so .NET expects you to add a script reference for jQuery.

There are two possible ways to solve the error:


Disable UnobtrusiveValidationMode:

Add this to web.config:

<configuration>
    <appSettings>
        <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
    </appSettings>
</configuration>

It will work as it worked in previous .NET versions and will just add the necessary Javascript to your page to make the validators work, instead of looking for the code in your jQuery file. This is the common solution actually.


Another solution is to register the script:

In Global.asax Application_Start add mapping to your jQuery file path:

void Application_Start(object sender, EventArgs e) 
{
    // Code that runs on application startup
    ScriptManager.ScriptResourceMapping.AddDefinition("jquery", 
    new ScriptResourceDefinition
    {
        Path = "~/scripts/jquery-1.7.2.min.js",
        DebugPath = "~/scripts/jquery-1.7.2.js",
        CdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.1.min.js",
        CdnDebugPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.1.js"
    });
}

Some details from MSDN:

ValidationSettings:UnobtrusiveValidationMode Specifies how ASP.NET globally enables the built-in validator controls to use unobtrusive JavaScript for client-side validation logic.

If this key value is set to "None" [default], the ASP.NET application will use the pre-4.5 behavior (JavaScript inline in the pages) for client-side validation logic.

If this key value is set to "WebForms", ASP.NET uses HTML5 data-attributes and late bound JavaScript from an added script reference for client-side validation logic.

C# declare empty string array

Arrays' constructors are different. Here are some ways to make an empty string array:

var arr = new string[0];
var arr = new string[]{};
var arr = Enumerable.Empty<string>().ToArray()

(sorry, on mobile)

How to sort a Pandas DataFrame by index?

Dataframes have a sort_index method which returns a copy by default. Pass inplace=True to operate in place.

import pandas as pd
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df.sort_index(inplace=True)
print(df.to_string())

Gives me:

     A
1    4
29   2
100  1
150  5
234  3

Loop over array dimension in plpgsql

Since PostgreSQL 9.1 there is the convenient FOREACH:

DO
$do$
DECLARE
   m   varchar[];
   arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
   FOREACH m SLICE 1 IN ARRAY arr
   LOOP
      RAISE NOTICE 'another_func(%,%)',m[1], m[2];
   END LOOP;
END
$do$

Solution for older versions:

DO
$do$
DECLARE
   arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
   FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
   LOOP
      RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
   END LOOP;
END
$do$

Also, there is no difference between varchar[] and varchar[][] for the PostgreSQL type system. I explain in more detail here.

The DO statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql is the default (so you can omit the declaration).

<select> HTML element with height

I've used a few CSS hacks and targeted Chrome/Safari/Firefox/IE individually, as each browser renders selects a bit differently. I've tested on all browsers except IE.

For Safari/Chrome, set the height and line-height you want for your <select />.

For Firefox, we're going to kill Firefox's default padding and border, then set our own. Set padding to whatever you like.

For IE 8+, just like Chrome, we've set the height and line-height properties. These two media queries can be combined. But I kept it separate for demo purposes. So you can see what I'm doing.

Please note, for the height/line-height property to work in Chrome/Safari OSX, you must set the background to a custom value. I changed the color in my example.

Here's a jsFiddle of the below: http://jsfiddle.net/URgCB/4/

For the non-hack route, why not use a custom select plug-in via jQuery? Check out this: http://codepen.io/wallaceerick/pen/ctsCz

HTML:

<select>
    <option>Here's one option</option>
    <option>here's another option</option>
</select>

CSS:

@media screen and (-webkit-min-device-pixel-ratio:0) {  /*safari and chrome*/
    select {
        height:30px;
        line-height:30px;
        background:#f4f4f4;
    } 
}
select::-moz-focus-inner { /*Remove button padding in FF*/ 
    border: 0;
    padding: 0;
}
@-moz-document url-prefix() { /* targets Firefox only */
    select {
        padding: 15px 0!important;
    }
}        
@media screen\0 { /* IE Hacks: targets IE 8, 9 and 10 */        
    select {
        height:30px;
        line-height:30px;
    }     
}

Manually adding a Userscript to Google Chrome

Share and install userscript with one-click

To make auto-install (but mannually confirm), You can make gist (gist.github.com) with <filename>.user.js filename to get on-click installation when you click on Raw and get this page:

Installation page

How to do this ?

  1. Name your gist <filename>.user.js, write your code and click on "Create".
    Make file on gist

  2. In the gist page, click on Raw to get installation page (first screen).
    Raw button

  3. Check the code and install it.

Connecting to SQL Server with Visual Studio Express Editions

My guess is that with VWD your solutions are more likely to be deployed to third party servers, many of which do not allow for a dynamically attached SQL Server database file. Thus the allowing of the other connection type.

This difference in IDE behavior is one of the key reasons for upgrading to a full version.

How to overlay one div over another div

I am not much of a coder nor an expert in CSS, but I am still using your idea in my web designs. I have tried different resolutions too:

_x000D_
_x000D_
#wrapper {_x000D_
  margin: 0 auto;_x000D_
  width: 901px;_x000D_
  height: 100%;_x000D_
  background-color: #f7f7f7;_x000D_
  background-image: url(images/wrapperback.gif);_x000D_
  color: #000;_x000D_
}_x000D_
#header {_x000D_
  float: left;_x000D_
  width: 100.00%;_x000D_
  height: 122px;_x000D_
  background-color: #00314e;_x000D_
  background-image: url(images/header.jpg);_x000D_
  color: #fff;_x000D_
}_x000D_
#menu {_x000D_
  float: left;_x000D_
  padding-top: 20px;_x000D_
  margin-left: 495px;_x000D_
  width: 390px;_x000D_
  color: #f1f1f1;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
  <div id="header">_x000D_
    <div id="menu">_x000D_
      menu will go here_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Of course there will be a wrapper around both of them. You can control the location of the menu div which will be displayed within the header div with left margins and top positions. You can also set the div menu to float right if you like.

pandas: merge (join) two data frames on multiple columns

Try this

new_df = pd.merge(A_df, B_df,  how='left', left_on=['A_c1','c2'], right_on = ['B_c1','c2'])

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html

left_on : label or list, or array-like Field names to join on in left DataFrame. Can be a vector or list of vectors of the length of the DataFrame to use a particular vector as the join key instead of columns

right_on : label or list, or array-like Field names to join on in right DataFrame or vector/list of vectors per left_on docs

What is the list of supported languages/locales on Android?

I think the best way is to run a sample code to find the supported locales. I've made a code snippet that does it:

final Locale[] availableLocales=Locale.getAvailableLocales();
for(final Locale locale : availableLocales)
  Log.d("Applog",":"+locale.getDisplayName()+":"+locale.getLanguage()+":"
    +locale.getCountry()+":values-"+locale.toString().replace("_","-r"));

the columns are : displayName (how it looks to the user), the locale, the variant, and the folder that the developer is supposed to put the strings into.

Here's a table I've made out of the 5.0.1 emulator: https://docs.google.com/spreadsheets/d/1Hx1CTPT82qFSbzuWiU1nyGROCNM6HKssKCPhxinvdww/

Weird thing is that for some cases, I got "#" which is something I've never seen before. It's probably quite new, and the rule I've chosen is probably incorrect for those cases (though it still compiles fine when I put such folders and files), but for the rest it should be fine.

If anyone knows about what the "#" is, and how to handle it, please let me know.

Is Python interpreted, or compiled, or both?

Python(the interpreter) is compiled.

Proof: It won't even compile your code if it contains syntax error.

Example 1:

print("This should print") 
a = 9/0 

Output:

This should print
Traceback (most recent call last):
  File "p.py", line 2, in <module>
    a = 9/0
ZeroDivisionError: integer division or modulo by zero

Code gets compiled successfully. First line gets executed (print) second line throws ZeroDivisionError (run time error) .

Example 2:

print("This should not print")
/0         

Output:

  File "p.py", line 2
    /0
    ^
SyntaxError: invalid syntax

Conclusion: If your code file contains SyntaxError nothing will execute as compilation fails.

Object cannot be cast from DBNull to other types

I'm thinking that your output parameter is coming back with a DBNull value. Add a check for that like this

var outputParam = dataAccCom.GetParameterValue(IDbCmd, "op_Id");
if(!(outputParam is DBNull))
     DataTO.Id = Convert.ToInt64(outputParam);

Delete files older than 10 days using shell script in Unix

If you can afford working via the file data, you can do

find -mmin +14400 -delete

Powershell equivalent of bash ampersand (&) for forking/running background processes

You can use PowerShell job cmdlets to achieve your goals.

There are 6 job related cmdlets available in PowerShell.

  • Get-Job
    • Gets Windows PowerShell background jobs that are running in the current session
  • Receive-Job
    • Gets the results of the Windows PowerShell background jobs in the current session
  • Remove-Job
    • Deletes a Windows PowerShell background job
  • Start-Job
    • Starts a Windows PowerShell background job
  • Stop-Job
    • Stops a Windows PowerShell background job
  • Wait-Job
    • Suppresses the command prompt until one or all of the Windows PowerShell background jobs running in the session are complete

If interesting about it, you can download the sample How to create background job in PowerShell

Collapsing Sidebar with Bootstrap

EDIT: I've added one more option for bootstrap sidebars.

There are actually three manners in which you can make a bootstrap 3 sidebar. I tried to keep the code as simple as possible.

Fixed sidebar

Here you can see a demo of a simple fixed sidebar I've developed with the same height as the page

Sidebar in a column

I've also developed a rather simple column sidebar that works in a two or three column page inside a container. It takes the length of the longest column. Here you can see a demo

Dashboard

If you google bootstrap dashboard, you can find multiple suitable dashboard, such as this one. However, most of them require a lot of coding. I've developed a dashboard that works without additional javascript (next to the bootstrap javascript). Here is a demo

For all three examples you off course have to include the jquery, bootstrap css, js and theme.css files.

Slidebar

If you want the sidebar to hide on pressing a button this is also possible with only a little javascript.Here is a demo

Disable a link in Bootstrap

You cant set links to "disabled" just system elements like input, textfield etc.

But you can disable links with jQuery/JavaScript

$('.disabled').click(function(e){
    e.preventDefault();
});

Just wrap the above code in whatever event you want to disable the links.

Find the most common element in a list

A one-liner:

def most_common (lst):
    return max(((item, lst.count(item)) for item in set(lst)), key=lambda a: a[1])[0]