Programs & Examples On #Xhtml transitional

0

Decode UTF-8 with Javascript

I searched for a simple solution and this works well for me:

//input data
view = new Uint8Array(data);

//output string
serialString = ua2text(view);

//convert UTF8 to string
function ua2text(ua) {
    s = "";
    for (var i = 0; i < ua.length; i++) {
        s += String.fromCharCode(ua[i]);
    }
    return s;               
}

Only issue I have is sometimes I get one character at a time. This might be by design with my source of the arraybuffer. I'm using https://github.com/xseignard/cordovarduino to read serial data on an android device.

What are Runtime.getRuntime().totalMemory() and freeMemory()?

JVM heap size can be growable and shrinkable by the Garbage-Collection mechanism. But, it can't allocate over maximum memory size: Runtime.maxMemory. This is the meaning of maximum memory. Total memory means the allocated heap size. And free memory means the available size in total memory.

example) java -Xms20M -Xmn10M -Xmx50M ~~~. This means that jvm should allocate heap 20M on start(ms). In this case, total memory is 20M. free memory is 20M-used size. If more heap is needed, JVM allocate more but can't over 50M(mx). In the case of maximum, total memory is 50M, and free size is 50M-used size. As for minumum size(mn), if heap is not used much, jvm can shrink heap size to 10M.

This mechanism is for efficiency of memory. If small java program run on huge fixed size heap memory, so much memory may be wasteful.

ResultSet exception - before start of result set

You have to do a result.next() before you can access the result. It's a very common idiom to do

ResultSet rs = stmt.executeQuery();
while (rs.next())
{
   int foo = rs.getInt(1);
   ...
}

How can I initialize an ArrayList with all zeroes in Java?

The integer passed to the constructor represents its initial capacity, i.e., the number of elements it can hold before it needs to resize its internal array (and has nothing to do with the initial number of elements in the list).

To initialize an list with 60 zeros you do:

List<Integer> list = new ArrayList<Integer>(Collections.nCopies(60, 0));

If you want to create a list with 60 different objects, you could use the Stream API with a Supplier as follows:

List<Person> persons = Stream.generate(Person::new)
                             .limit(60)
                             .collect(Collectors.toList());

How to get the last N rows of a pandas DataFrame?

Don't forget DataFrame.tail! e.g. df1.tail(10)

Convert InputStream to BufferedReader

BufferedReader can't wrap an InputStream directly. It wraps another Reader. In this case you'd want to do something like:

BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

Get combobox value in Java swing

If the string is empty, comboBox.getSelectedItem().toString() will give a NullPointerException. So better to typecast by (String).

How can I convert a dictionary into a list of tuples?

By keys() and values() methods of dictionary and zip.

zip will return a list of tuples which acts like an ordered dictionary.

Demo:

>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> zip(d.keys(), d.values())
[('a', 1), ('c', 3), ('b', 2)]
>>> zip(d.values(), d.keys())
[(1, 'a'), (3, 'c'), (2, 'b')]

Get protocol, domain, and port from URL

first get the current address

var url = window.location.href

Then just parse that string

var arr = url.split("/");

your url is:

var result = arr[0] + "//" + arr[2]

Hope this helps

How to get a div to resize its height to fit container?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
#top, #bottom {
    height: 100px;
    width: 100%;
    position: relative;
}
#container {
    overflow: hidden;
    position: relative;
    width: 100%;
}
#container .left {
    height: 550px;
    width: 55%;
    position: relative;
    float: left;
    background-color: #3399FF;
}
#container .right {
    height: 100%;
    position: absolute;
    right: 0;
    left: 55%;
    bottom: 0px;
    top: 0px;
    background-color: #3366CC;
}
</style>
</head>

<body>
<div id="top"></div>
<div id="container">
  <div class="left"></div>
  <div class="right"></div>
</div>
<div id="bottom"></div>
</body>
</html>

How to initialize an array of custom objects

Maybe you mean like this? I like to make an object and use Format-Table:

> $array = @()
> $object = New-Object -TypeName PSObject
> $object | Add-Member -Name 'Name' -MemberType Noteproperty -Value 'Joe'
> $object | Add-Member -Name 'Age' -MemberType Noteproperty -Value 32
> $object | Add-Member -Name 'Info' -MemberType Noteproperty -Value 'something about him'
> $array += $object
> $array | Format-Table

Name                                                                        Age Info
----                                                                        --- ----
Joe                                                                          32  something about him

This will put all objects you have in the array in columns according to their properties.

Tip: Using -auto sizes the table better

> $array | Format-Table -Auto

Name Age Info
---- --- ----
Joe   32 something about him

You can also specify which properties you want in the table. Just separate each property name with a comma:

> $array | Format-Table Name, Age -Auto

Name Age
---- ---
Joe   32

How to align a div to the top of its parent but keeping its inline-block behaviour?

Use vertical-align:top; for the element you want at the top, as I have demonstrated on your jsfiddle.

http://www.brunildo.org/test/inline-block.html

Sort a list of Class Instances Python

import operator
sorted_x = sorted(x, key=operator.attrgetter('score'))

if you want to sort x in-place, you can also:

x.sort(key=operator.attrgetter('score'))

Javascript - How to detect if document has loaded (IE 7/Firefox 3)

I have other solution, my application need to be started when new object of MyApp is created, so it looks like:

function MyApp(objId){
     this.init=function(){
        //.........
     }
     this.run=function(){
          if(!document || !document.body || !window[objId]){
              window.setTimeout(objId+".run();",100);
              return;
          }
          this.init();
     };
     this.run();
}
//and i am starting it 
var app=new MyApp('app');

it is working on all browsers, that i know.

Pandas get the most frequent values of a column

You can use this to get a perfect count, it calculates the mode a particular column

df['name'].value_counts()

Default values for Vue component props & how to check if a user did not set the prop?

Also something important to add here, in order to set default values for arrays and objects we must use the default function for props:

propE: {
      type: Object,
      // Object or array defaults must be returned from
      // a factory function
      default: function () {
        return { message: 'hello' }
      }
    },

How can I write data attributes using Angular?

Use attribute binding syntax instead

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    [attr.data-sectionvalue]="section.value">{{ section.text }}</li>  
</ol>

or

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    attr.data-sectionvalue="{{section.value}}">{{ section.text }}</li>  
</ol>

See also :

Android - Get value from HashMap

for (Object key : meMap.keySet()) {
        String value=(String)meMap.get(key);
        Toast.makeText(ctx, "Key: "+key+" Value: "+value, Toast.LENGTH_LONG).show();
    }

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

Android Studio (Preview) sometimes recommends updating to a Gradle Plugin that is not available yet (did Google forget to publish it?). Such as today with

'com.android.tools.build:gradle:3.1.0-beta1'

I found I can see current versions of com.android.tools.build:gradle here, and then I just pick the newest:

https://dl.google.com/dl/android/maven2/index.html

I just found this beta1 gradle bug in the Android Bug Tracker. I also just learned Android Studio > Help Menu > Submit Feedback brought me to the bug tracker.

Found temporary solution at androiddev reddit for the 3.1.0-beta1 problem: Either roll back to Preview Canary 8, or switch to gradle plugin 3.0.1 until Canary 10 is released shortly.

How to Round to the nearest whole number in C#

there's this manual, and kinda cute way too:

double d1 = 1.1;
double d2 = 1.5;
double d3 = 1.9;

int i1 = (int)(d1 + 0.5);
int i2 = (int)(d2 + 0.5);
int i3 = (int)(d3 + 0.5);

simply add 0.5 to any number, and cast it to int (or floor it) and it will be mathematically correctly rounded :D

Which is better, return value or out parameter?

Return values are almost always the right choice when the method doesn't have anything else to return. (In fact, I can't think of any cases where I'd ever want a void method with an out parameter, if I had the choice. C# 7's Deconstruct methods for language-supported deconstruction acts as a very, very rare exception to this rule.)

Aside from anything else, it stops the caller from having to declare the variable separately:

int foo;
GetValue(out foo);

vs

int foo = GetValue();

Out values also prevent method chaining like this:

Console.WriteLine(GetValue().ToString("g"));

(Indeed, that's one of the problems with property setters as well, and it's why the builder pattern uses methods which return the builder, e.g. myStringBuilder.Append(xxx).Append(yyy).)

Additionally, out parameters are slightly harder to use with reflection and usually make testing harder too. (More effort is usually put into making it easy to mock return values than out parameters). Basically there's nothing I can think of that they make easier...

Return values FTW.

EDIT: In terms of what's going on...

Basically when you pass in an argument for an "out" parameter, you have to pass in a variable. (Array elements are classified as variables too.) The method you call doesn't have a "new" variable on its stack for the parameter - it uses your variable for storage. Any changes in the variable are immediately visible. Here's an example showing the difference:

using System;

class Test
{
    static int value;

    static void ShowValue(string description)
    {
        Console.WriteLine(description + value);
    }

    static void Main()
    {
        Console.WriteLine("Return value test...");
        value = 5;
        value = ReturnValue();
        ShowValue("Value after ReturnValue(): ");

        value = 5;
        Console.WriteLine("Out parameter test...");
        OutParameter(out value);
        ShowValue("Value after OutParameter(): ");
    }

    static int ReturnValue()
    {
        ShowValue("ReturnValue (pre): ");
        int tmp = 10;
        ShowValue("ReturnValue (post): ");
        return tmp;
    }

    static void OutParameter(out int tmp)
    {
        ShowValue("OutParameter (pre): ");
        tmp = 10;
        ShowValue("OutParameter (post): ");
    }
}

Results:

Return value test...
ReturnValue (pre): 5
ReturnValue (post): 5
Value after ReturnValue(): 10
Out parameter test...
OutParameter (pre): 5
OutParameter (post): 10
Value after OutParameter(): 10

The difference is at the "post" step - i.e. after the local variable or parameter has been changed. In the ReturnValue test, this makes no difference to the static value variable. In the OutParameter test, the value variable is changed by the line tmp = 10;

Dealing with "Xerces hell" in Java/Maven?

Frankly, pretty much everything that we've encountered works just fine w/ the JAXP version, so we always exclude xml-apis and xercesImpl.

Links in <select> dropdown options

You can use this code:

<select id="menu" name="links" size="1" onchange="window.location.href=this.value;">
    <option value="URL">Book</option>
    <option value="URL">Pen</option>
    <option value="URL">Read</option>
    <option value="URL">Apple</option>
</select>

Using PHP to upload file and add the path to MySQL database

mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("altabotanikk") or die(mysql_error()) ;

These are deprecated use the following..

 // Connects to your Database
            $link = mysqli_connect("localhost", "root", "", "");

and to insert data use the following

 $sql = "INSERT INTO  Table-Name (Column-Name)
VALUES ('$filename')" ;

Disable all dialog boxes in Excel while running VB script?

In Access VBA I've used this to turn off all the dialogs when running a bunch of updates:

DoCmd.SetWarnings False

After running all the updates, the last step in my VBA script is:

DoCmd.SetWarnings True

Hope this helps.

String concatenation with Groovy

def my_string = "some string"
println "here: " + my_string 

Not quite sure why the answer above needs to go into benchmarks, string buffers, tests, etc.

how to remove "," from a string in javascript

If U want to delete more than one characters, say comma and dots you can write

<script type="text/javascript">
  var mystring = "It,is,a,test.string,of.mine" 
  mystring = mystring.replace(/[,.]/g , ''); 
  alert( mystring);
</script>

ImportError: no module named win32api

According to pywin32 github you must run

    pip install pywin32

and after that, you must run

    python Scripts/pywin32_postinstall.py -install

I know I'm reviving an old thread, but I just had this problem and this was the only way to solve it.

Android : Check whether the phone is dual SIM

Tips:

You can try to use

ctx.getSystemService("phone_msim")

instead of

ctx.getSystemService(Context.TELEPHONY_SERVICE)

If you have already tried Vaibhav's answer and telephony.getClass().getMethod() fails, above is what works for my Qualcomm mobile.

Converting SVG to PNG using C#

I'm using Batik for this. The complete Delphi code:

procedure ExecNewProcess(ProgramName : String; Wait: Boolean);
var
  StartInfo : TStartupInfo;
  ProcInfo : TProcessInformation;
  CreateOK : Boolean;
begin
  FillChar(StartInfo, SizeOf(TStartupInfo), #0);
  FillChar(ProcInfo, SizeOf(TProcessInformation), #0);
  StartInfo.cb := SizeOf(TStartupInfo);
  CreateOK := CreateProcess(nil, PChar(ProgramName), nil, nil, False,
              CREATE_NEW_PROCESS_GROUP + NORMAL_PRIORITY_CLASS,
              nil, nil, StartInfo, ProcInfo);
  if CreateOK then begin
    //may or may not be needed. Usually wait for child processes
    if Wait then
      WaitForSingleObject(ProcInfo.hProcess, INFINITE);
  end else
    ShowMessage('Unable to run ' + ProgramName);

  CloseHandle(ProcInfo.hProcess);
  CloseHandle(ProcInfo.hThread);
end;

procedure ConvertSVGtoPNG(aFilename: String);
const
  ExecLine = 'c:\windows\system32\java.exe -jar C:\Apps\batik-1.7\batik-rasterizer.jar ';
begin
  ExecNewProcess(ExecLine + aFilename, True);
end;

How to access the elements of a function's return array?

here is the best way in a similar function

 function cart_stats($cart_id){

$sql = "select sum(price) sum_bids, count(*) total_bids from carts_bids where cart_id = '$cart_id'";
$rs = mysql_query($sql);
$row = mysql_fetch_object($rs);
$total_bids = $row->total_bids;
$sum_bids = $row->sum_bids;
$avarage = $sum_bids/$total_bids;

 $array["total_bids"] = "$total_bids";
 $array["avarage"] = " $avarage";

 return $array;
}  

and you get the array data like this

$data = cart_stats($_GET['id']); 
<?=$data['total_bids']?>

How do operator.itemgetter() and sort() work?

You are asking a lot of questions that you could answer yourself by reading the documentation, so I'll give you a general advice: read it and experiment in the python shell. You'll see that itemgetter returns a callable:

>>> func = operator.itemgetter(1)
>>> func(a)
['Paul', 22, 'Car Dealer']
>>> func(a[0])
8

To do it in a different way, you can use lambda:

a.sort(key=lambda x: x[1])

And reverse it:

a.sort(key=operator.itemgetter(1), reverse=True)

Sort by more than one column:

a.sort(key=operator.itemgetter(1,2))

See the sorting How To.

Inserting the same value multiple times when formatting a string

You can use the dictionary type of formatting:

s='arbit'
string='%(key)s hello world %(key)s hello world %(key)s' % {'key': s,}

Division of integers in Java

As your output results a double you should cast either completed variable or total variable or both to double while dividing.

So, the correct implmentation will be:

System.out.println((double)completed/total);

error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)' -- Missing /var/run/mysqld/mysqld.sock

my situation is that the mysql in the /etc/ directory is renamed mysql_bk, just copy mysql_bk

sudo cp -r /etc/mysql_bk/ /etc/mysql/

then

service mysql restart

How to tell which commit a tag points to in Git?

This doesn't show the filenames, but at least you get a feel of the repository.

cat .git/refs/tags/*

Each file in that directory contains a commit SHA pointing to a commit.

Structure padding and packing

Padding aligns structure members to "natural" address boundaries - say, int members would have offsets, which are mod(4) == 0 on 32-bit platform. Padding is on by default. It inserts the following "gaps" into your first structure:

struct mystruct_A {
    char a;
    char gap_0[3]; /* inserted by compiler: for alignment of b */
    int b;
    char c;
    char gap_1[3]; /* -"-: for alignment of the whole struct in an array */
} x;

Packing, on the other hand prevents compiler from doing padding - this has to be explicitly requested - under GCC it's __attribute__((__packed__)), so the following:

struct __attribute__((__packed__)) mystruct_A {
    char a;
    int b;
    char c;
};

would produce structure of size 6 on a 32-bit architecture.

A note though - unaligned memory access is slower on architectures that allow it (like x86 and amd64), and is explicitly prohibited on strict alignment architectures like SPARC.

How do I iterate over a range of numbers defined by variables in Bash?

for i in $(seq 1 $END); do echo $i; done

edit: I prefer seq over the other methods because I can actually remember it ;)

Change R default library path using .libPaths in Rprofile.site fails to work

On Ubuntu, the recommended way of changing the default library path for a user, is to set the R_LIBS_USER variable in the ~/.Renviron file.

touch ~/.Renviron
echo "R_LIBS_USER=/custom/path/in/absolute/form" >> ~/.Renviron

Correct way to quit a Qt program?

You can call qApp.exit();. I always use that and never had a problem with it.

If you application is a command line application, you might indeed want to return an exit code. It's completely up to you what the code is.

How to change Visual Studio 2012,2013 or 2015 License Key?

I had the same problem and wanted to change the product key to another. Unfortunate it's not as easy as it was on VS2010.

The following steps work:

  • Remove the registry key containing the license information: HKEY_CLASSES_ROOT\Licenses\77550D6B-6352-4E77-9DA3-537419DF564B

  • If you can't find the key, use sysinternals ProcessMonitor to check the registry access of VS2012 to locate the correct key which is always in HKEY_CLASSES_ROOT\Licenses

  • After you remove this key, VS2012 will tell you that it's license information is incorrect. Go to "Programs and features" and repair VS2012.

  • After the repair, VS2012 is reverted to a 30 day trial and you can enter a new product key. This could also be used to stay in a trial version loop and never enter a producy key.

python pandas dataframe to dictionary

Simplest solution:

df.set_index('id').T.to_dict('records')

Example:

df= pd.DataFrame([['a',1],['a',2],['b',3]], columns=['id','value'])
df.set_index('id').T.to_dict('records')

If you have multiple values, like val1, val2, val3,etc and u want them as lists, then use the below code:

df.set_index('id').T.to_dict('list')

How do you find what version of libstdc++ library is installed on your linux machine?

To find which library is being used you could run

 $ /sbin/ldconfig -p | grep stdc++
    libstdc++.so.6 (libc6) => /usr/lib/libstdc++.so.6

The list of compatible versions for libstdc++ version 3.4.0 and above is provided by

 $ strings /usr/lib/libstdc++.so.6 | grep LIBCXX
 GLIBCXX_3.4
 GLIBCXX_3.4.1
 GLIBCXX_3.4.2
 ...

For earlier versions the symbol GLIBCPP is defined.

The date stamp of the library is defined in a macro __GLIBCXX__ or __GLIBCPP__ depending on the version:

// libdatestamp.cxx
#include <cstdio>

int main(int argc, char* argv[]){
#ifdef __GLIBCPP__
    std::printf("GLIBCPP: %d\n",__GLIBCPP__);
#endif
#ifdef __GLIBCXX__
    std::printf("GLIBCXX: %d\n",__GLIBCXX__);
#endif
   return 0;
}

$ g++ libdatestamp.cxx -o libdatestamp
$ ./libdatestamp
GLIBCXX: 20101208

The table of datestamps of libstdc++ versions is listed in the documentation:

jQuery get an element by its data-id

Yes, you can find out element by data attribute.

element = $('a[data-item-id="stand-out"]');

C++ equivalent of Java's toString?

In C++ you can overload operator<< for ostream and your custom class:

class A {
public:
  int i;
};

std::ostream& operator<<(std::ostream &strm, const A &a) {
  return strm << "A(" << a.i << ")";
}

This way you can output instances of your class on streams:

A x = ...;
std::cout << x << std::endl;

In case your operator<< wants to print out internals of class A and really needs access to its private and protected members you could also declare it as a friend function:

class A {
private:
  friend std::ostream& operator<<(std::ostream&, const A&);
  int j;
};

std::ostream& operator<<(std::ostream &strm, const A &a) {
  return strm << "A(" << a.j << ")";
}

Generate getters and setters in NetBeans

Position the cursor inside the class, then press ALT + Ins and select Getters and Setters from the contextual menu.

Cancel a UIView animation?

Use:

#import <QuartzCore/QuartzCore.h>

.......

[myView.layer removeAllAnimations];

How to rename a file using Python

Use os.rename. But you have to pass full path of both files to the function. If I have a file a.txt on my desktop so I will do and also I have to give full of renamed file too.

os.rename('C:\\Users\\Desktop\\a.txt', 'C:\\Users\\Desktop\\b.kml')

Getting HTML elements by their attribute names

Yes, the function is querySelectorAll (or querySelector for a single element), which allows you to use CSS selectors to find elements.

document.querySelectorAll('[property]'); // All with attribute named "property"
document.querySelectorAll('[property="value"]'); // All with "property" set to "value" exactly.

(Complete list of attribute selectors on MDN.)

This finds all elements with the attribute property. It would be better to specify a tag name if possible:

document.querySelectorAll('span[property]');

You can work around this if necessary by looping through all the elements on the page to see whether they have the attribute set:

var withProperty = [],
    els = document.getElementsByTagName('span'), // or '*' for all types of element
    i = 0;

for (i = 0; i < els.length; i++) {
    if (els[i].hasAttribute('property')) {
        withProperty.push(els[i]);
    }
}

Libraries such as jQuery handle this for you; it's probably a good idea to let them do the heavy lifting.

For anyone dealing with ancient browsers, note that querySelectorAll was introduced to Internet Explorer in v8 (2009) and fully supported in IE9. All modern browsers support it.

How to parse unix timestamp to time.Time

The time.Parse function does not do Unix timestamps. Instead you can use strconv.ParseInt to parse the string to int64 and create the timestamp with time.Unix:

package main

import (
    "fmt"
    "time"
    "strconv"
)

func main() {
    i, err := strconv.ParseInt("1405544146", 10, 64)
    if err != nil {
        panic(err)
    }
    tm := time.Unix(i, 0)
    fmt.Println(tm)
}

Output:

2014-07-16 20:55:46 +0000 UTC

Playground: http://play.golang.org/p/v_j6UIro7a

Edit:

Changed from strconv.Atoi to strconv.ParseInt to avoid int overflows on 32 bit systems.

Can CSS detect the number of children an element has?

No, there is nothing like this in CSS. You can, however, use JavaScript to calculate the number of children and apply styles.

CSS to make table 100% of max-width

I have a very well working solution for tables of max-width: 100%. Just use word-break: break-all; for the table cells (except heading cells) to break all long text into several lines:

<!DOCTYPE html>
<html>
<head>
<style>

table {
  max-width: 100%; 
}
table td {
  word-break: break-all;
}

</style>
</head>
<body>

<table border="1">
  <tr>
    <th><strong>Input</strong></th>
    <th><strong>Output</strong></th>
  </tr>
  <tr>
    <td>some text</td>
    <td>12b6459fc6b4cabb4b1990be1a78e4dc5fa79c3a0fe9aa9f0386d673cfb762171a4aaa363b8dac4c33e0ad23e4830888</td>
  </tr>
</table>

</body>
</html>

This will render like this (when the screen width is limited):

Force IE compatibility mode off using tags

If you have access to the server, the most reliable way of doing this is to do it on the server itself, in IIS. Go in to IIS HTTP Response Headers. Add Name: X-UA-Compatible
Value: IE=edge This will override your browser and your code.

Checking whether a String contains a number value in Java

if(str.matches(".*\\d.*")){
   // contains a number
} else{
   // does not contain a number
}

Previous suggested solution, which does not work, but brought back because of @Eng.Fouad's request/suggestion.

Not working suggested solution

String strWithNumber = "This string has a 1 number";
String strWithoutNumber = "This string does not have a number";

System.out.println(strWithNumber.contains("\d"));
System.out.println(strWithoutNumber.contains("\d"));

Working solution

String strWithNumber = "This string has a 1 number";
if(strWithNumber.matches(".*\\d.*")){
    System.out.println("'"+strWithNumber+"' contains digit");
} else{
    System.out.println("'"+strWithNumber+"' does not contain a digit");
}

String strWithoutNumber = "This string does not have a number";
if(strWithoutNumber.matches(".*\\d.*")){
    System.out.println("'"+strWithoutNumber+"' contains digit");
} else{
    System.out.println("'"+strWithoutNumber+"' does not contain a digit");
}

Output

'This string has a 1 number' contains digit
'This string does not have a number' does not contain a digit

Write Base64-encoded image to file

Assuming the image data is already in the format you want, you don't need image ImageIO at all - you just need to write the data to the file:

// Note preferred way of declaring an array variable
byte[] data = Base64.decodeBase64(crntImage);
try (OutputStream stream = new FileOutputStream("c:/decode/abc.bmp")) {
    stream.write(data);
}

(I'm assuming you're using Java 7 here - if not, you'll need to write a manual try/finally statement to close the stream.)

If the image data isn't in the format you want, you'll need to give more details.

How to empty a list?

lst *= 0

has the same effect as

lst[:] = []

It's a little simpler and maybe easier to remember. Other than that there's not much to say

The efficiency seems to be about the same

How to make <div> fill <td> height

This questions is already answered here. Just put height: 100% in both the div and the container td.

How to use Visual Studio Code as Default Editor for Git

Im not sure you can do this, however you can try these additions in your gitconfig file.

Try to replace the kdiff3 from these values to point to visual studio code executable.

[merge] tool = kdiff3 [mergetool "kdiff3"] path = C:/Program Files/KDiff3/kdiff3.exe keepBackup = false trustExitCode = false

Javascript getElementsByName.value not working

You have mentioned Wrong id

alert(document.getElementById("name").value);

if you want to use name attribute then

alert(document.getElementsByName("username")[0].value);

Updates:

input type="text" id="name" name="username"  

id is different from name

How to style dt and dd so they are on the same line?

Because I have yet to see an example that works for my use case, here is the most full-proof solution that I was able to realize.

_x000D_
_x000D_
dd {_x000D_
    margin: 0;_x000D_
}_x000D_
dd::after {_x000D_
    content: '\A';_x000D_
    white-space: pre-line;_x000D_
}_x000D_
dd:last-of-type::after {_x000D_
    content: '';_x000D_
}_x000D_
dd, dt {_x000D_
    display: inline;_x000D_
}_x000D_
dd, dt, .address {_x000D_
    vertical-align: middle;_x000D_
}_x000D_
dt {_x000D_
    font-weight: bolder;_x000D_
}_x000D_
dt::after {_x000D_
    content: ': ';_x000D_
}_x000D_
.address {_x000D_
    display: inline-block;_x000D_
    white-space: pre;_x000D_
}
_x000D_
Surrounding_x000D_
_x000D_
<dl>_x000D_
  <dt>Phone Number</dt>_x000D_
  <dd>+1 (800) 555-1234</dd>_x000D_
  <dt>Email Address</dt>_x000D_
  <dd><a href="#">[email protected]</a></dd>_x000D_
  <dt>Postal Address</dt>_x000D_
  <dd><div class="address">123 FAKE ST<br />EXAMPLE EX  00000</div></dd>_x000D_
</dl>_x000D_
_x000D_
Text
_x000D_
_x000D_
_x000D_

Strangely enough, it doesn't work with display: inline-block. I suppose that if you need to set the size of any of the dt elements or dd elements, you could set the dl's display as display: flexbox; display: -webkit-flex; display: flex; and the flex shorthand of the dd elements and the dt elements as something like flex: 1 1 50% and display as display: inline-block. But I haven't tested that, so approach with caution.

ImportError: No module named model_selection

Your sklearn version is too low, model_selection is imported by 0.18.1, so please update the sklearn version.

What is the best way to compare floats for almost-equality in Python?

Is something as simple as the following not good enough?

return abs(f1 - f2) <= allowed_error

Standard way to embed version into python package?

For what it's worth, if you're using NumPy distutils, numpy.distutils.misc_util.Configuration has a make_svn_version_py() method that embeds the revision number inside package.__svn_version__ in the variable version .

How do I completely rename an Xcode project (i.e. inclusive of folders)?

Step 1 - Rename the project

  1. Click on the project you want to rename in the "Project navigator" in the left panel of the Xcode window.
  2. In the right panel, select the "File inspector", and the name of your project should be found under "Identity and Type". Change it to your new name.
  3. When the dialog asks whether to rename or not rename the project's content items, click "Rename". Say yes to any warning about uncommitted changes.

Step 2 - Rename the scheme

  1. At the top of the window, next to the "Stop" button, there is a scheme for your product under its old name; click on it, then choose "Manage Schemes…".
  2. Click on the old name in the scheme and it will become editable; change the name and click "Close".

Step 3 - Rename the folder with your assets

  1. Quit Xcode. Rename the master folder that contains all your project files.
  2. In the correctly-named master folder, beside your newly-named .xcodeproj file, there is probably a wrongly-named OLD folder containing your source files. Rename the OLD folder to your new name (if you use Git, you could run git mv oldname newname so that Git recognizes this is a move, rather than deleting/adding new files).
  3. Re-open the project in Xcode. If you see a warning "The folder OLD does not exist", dismiss the warning. The source files in the renamed folder will be grayed out because the path has broken.
  4. In the "Project navigator" in the left-hand panel, click on the top-level folder representing the OLD folder you renamed.
  5. In the right-hand panel, under "Identity and Type", change the "Name" field from the OLD name to the new name.
  6. Just below that field is a "Location" menu. If the full path has not corrected itself, click on the nearby folder icon and choose the renamed folder.

Step 4 - Rename the Build plist data

  1. Click on the project in the "Project navigator" on the left, and in the main panel select "Build Settings".
  2. Search for "plist" in the settings.
  3. In the Packaging section, you will see Info.plist and Product Bundle Identifier.
  4. If there is a name entered in Info.plist, update it.
  5. Do the same for Product Bundle Identifier, unless it is utilizing the ${PRODUCT_NAME} variable. In that case, search for "product" in the settings and update Product Name. If Product Name is based on ${TARGET_NAME}, click on the actual target item in the TARGETS list on the left of the settings pane and edit it, and all related settings will update immediately.
  6. Search the settings for "prefix" and ensure that Prefix Header's path is also updated to the new name.
  7. If you use SwiftUI, search for "Development Assets" and update the path.

Step 5 - Repeat step 3 for tests (if you have them)

Step 6 - Repeat step 3 for core data if its name matches project name (if you have it)

Step 7 - Clean and rebuild your project

  1. Command + Shift + K to clean
  2. Command + B to build

MySQL query String contains

Use:

SELECT *
  FROM `table`
 WHERE INSTR(`column`, '{$needle}') > 0

Reference:

Removing packages installed with go get

It's safe to just delete the source directory and compiled package file. Find the source directory under $GOPATH/src and the package file under $GOPATH/pkg/<architecture>, for example: $GOPATH/pkg/windows_amd64.

Select arrow style change

I have referred this post, it worked like charm , except it did not hide the arrow in IE browser.

However adding following hides the arrow in IE:

_x000D_
_x000D_
&::-ms-expand {_x000D_
      display: none;_x000D_
    }
_x000D_
_x000D_
_x000D_

Complete solution ( sass )

_x000D_
_x000D_
$select-border-color: #ccc;_x000D_
$select-focus-color: green;_x000D_
_x000D_
select {_x000D_
_x000D_
    cursor: pointer;_x000D_
    /* styling */_x000D_
    background-color: white;_x000D_
    border: 1px solid $select-border-color;_x000D_
    border-radius: 4px;_x000D_
    display: inline-block;_x000D_
    font: inherit;_x000D_
    line-height: 1.5em;_x000D_
    padding: 0.5em 3.5em 0.5em 1em;_x000D_
_x000D_
    /* reset */_x000D_
    margin: 0;_x000D_
    -webkit-box-sizing: border-box;_x000D_
    -moz-box-sizing: border-box;_x000D_
    box-sizing: border-box;_x000D_
    -webkit-appearance: none;_x000D_
    -moz-appearance: none;_x000D_
_x000D_
    background-image: linear-gradient(45deg, transparent 50%, $select-border-color 50%),_x000D_
    linear-gradient(135deg, $select-border-color 50%, transparent 50%),_x000D_
    linear-gradient(to right, $select-border-color, $select-border-color);_x000D_
    background-position: calc(100% - 20px) calc(1em + 2px),_x000D_
    calc(100% - 15px) calc(1em + 2px), calc(100% - 2.5em) 0.5em;_x000D_
    background-size: 5px 5px, 5px 5px, 1px 1.5em;_x000D_
    background-repeat: no-repeat;_x000D_
_x000D_
    /* Very imp: hide arrow in IE */_x000D_
    &::-ms-expand {_x000D_
      display: none;_x000D_
    }_x000D_
_x000D_
    &:-moz-focusring {_x000D_
      color: transparent;_x000D_
      text-shadow: none;_x000D_
    }_x000D_
_x000D_
    &:focus {_x000D_
      background-image: linear-gradient(45deg, $select-focus-color 50%, transparent 50%),_x000D_
      linear-gradient(135deg, transparent 50%, $select-focus-color 50%), linear-gradient(to right, $select-focus-color, $select-focus-color);_x000D_
      background-position: calc(100% - 15px) 1em, calc(100% - 20px) 1em, calc(100% - 2.5em) 0.5em;_x000D_
      background-size: 5px 5px, 5px 5px, 1px 1.5em;_x000D_
      background-repeat: no-repeat;_x000D_
      border-color: $select-focus-color;_x000D_
      outline: 0;_x000D_
    }_x000D_
  }
_x000D_
_x000D_
_x000D_

val() vs. text() for textarea

.val() always works with textarea elements.

.text() works sometimes and fails other times! It's not reliable (tested in Chrome 33)

What's best is that .val() works seamlessly with other form elements too (like input) whereas .text() fails.

System.Net.Http: missing from namespace? (using .net 4.5)

NuGet > Microsoft.AspNet.WebApi.Client package

How to convert SSH keypairs generated using PuTTYgen (Windows) into key-pairs used by ssh-agent and Keychain (Linux)

I recently had this problem as I was moving from Putty for Linux to Remmina for Linux. So I have a lot of PPK files for Putty in my .putty directory as I've been using it's for 8 years. For this I used a simple for command for bash shell to do all files:

cd ~/.putty
for X in *.ppk; do puttygen $X -L > ~/.ssh/$(echo $X | sed 's,./,,' | sed 's/.ppk//g').pub; puttygen $X -O private-openssh -o ~/.ssh/$(echo $X | sed 's,./,,' | sed 's/.ppk//g').pvk; done;

Very quick and to the point, got the job done for all files that putty had. If it finds a key with a password it will stop and ask for the password for that key first and then continue.

SpringMVC RequestMapping for GET parameters

If you are willing to change your uri, you could also use PathVariable.

@RequestMapping(value="/mapping/foo/{foo}/{bar}", method=RequestMethod.GET)
public String process(@PathVariable String foo,@PathVariable String bar) {
    //Perform logic with foo and bar
}

NB: The first foo is part of the path, the second one is the PathVariable

Difference between RUN and CMD in a Dockerfile

RUN - command triggers while we build the docker image.

CMD - command triggers while we launch the created docker image.

SQL: How To Select Earliest Row

SELECT company
   , workflow
   , MIN(date)
FROM workflowTable
GROUP BY company
       , workflow

OpenCV resize fails on large image with "error: (-215) ssize.area() > 0 in function cv::resize"

Also pay attention to the object type of your numpy array, converting it using .astype('uint8') resolved the issue for me.

Get day of week in SQL Server 2005/2008

this is a working copy of my code check it, how to retrive day name from date in sql

CREATE Procedure [dbo].[proc_GetProjectDeploymentTimeSheetData] 
@FromDate date,
@ToDate date

As 
Begin
select p.ProjectName + ' ( ' + st.Time +' '+'-'+' '+et.Time +' )' as ProjectDeatils,
datename(dw,pts.StartDate) as 'Day'
from 
ProjectTimeSheet pts 
join Projects p on pts.ProjectID=p.ID 
join Timing st on pts.StartTimingId=st.Id
join Timing et on pts.EndTimingId=et.Id
where pts.StartDate >= @FromDate
and pts.StartDate <= @ToDate
END

Count unique values with pandas per groups

Generally to count distinct values in single column, you can use Series.value_counts:

df.domain.value_counts()

#'vk.com'          5
#'twitter.com'     2
#'facebook.com'    1
#'google.com'      1
#Name: domain, dtype: int64

To see how many unique values in a column, use Series.nunique:

df.domain.nunique()
# 4

To get all these distinct values, you can use unique or drop_duplicates, the slight difference between the two functions is that unique return a numpy.array while drop_duplicates returns a pandas.Series:

df.domain.unique()
# array(["'vk.com'", "'twitter.com'", "'facebook.com'", "'google.com'"], dtype=object)

df.domain.drop_duplicates()
#0          'vk.com'
#2     'twitter.com'
#4    'facebook.com'
#6      'google.com'
#Name: domain, dtype: object

As for this specific problem, since you'd like to count distinct value with respect to another variable, besides groupby method provided by other answers here, you can also simply drop duplicates firstly and then do value_counts():

import pandas as pd
df.drop_duplicates().domain.value_counts()

# 'vk.com'          3
# 'twitter.com'     2
# 'facebook.com'    1
# 'google.com'      1
# Name: domain, dtype: int64

Could not find method compile() for arguments Gradle

In my case I had to remove some files that were created by gradle at some point in my study to make things work. So, cleaning up after messing up and then it ran fine ...

If you experienced this issue in a git project, do git status and remove the unrevisioned files. (For me elasticsearch had a problem with plugins/analysis-icu).

Gradle Version : 5.1.1

downcast and upcast

Answer 1 : Yes it called upcasting but the way you do it is not modern way. Upcasting can be performed implicitly you don't need any conversion. So just writing Employee emp = mgr; is enough for upcasting.

Answer 2 : If you create object of Manager class we can say that manager is an employee. Because class Manager : Employee depicts Is-A relationship between Employee Class and Manager Class. So we can say that every manager is an employee.

But if we create object of Employee class we can not say that this employee is manager because class Employee is a class which is not inheriting any other class. So you can not directly downcast that Employee Class object to Manager Class object.

So answer is, if you want to downcast from Employee Class object to Manager Class object, first you must have object of Manager Class first then you can upcast it and then you can downcast it.

Using the HTML5 "required" attribute for a group of checkboxes?

Inspired by the answers from @thegauraw and @Brian Woodward, here's a bit I pulled together for JQuery users, including a custom validation error message:

$cbx_group = $("input:checkbox[name^='group']");
$cbx_group.on("click", function() {
    if ($cbx_group.is(":checked")) {
        // checkboxes become unrequired as long as one is checked
        $cbx_group.prop("required", false).each(function() {
            this.setCustomValidity("");
        });
    } else {
        // require checkboxes and set custom validation error message
        $cbx_group.prop("required", true).each(function() {
            this.setCustomValidity("Please select at least one checkbox.");
        });
    }
});

Note that my form has some checkboxes checked by default.

Maybe some of you JavaScript/JQuery wizards could tighten that up even more?

Extract filename and extension in Bash

pax> echo a.b.js | sed 's/\.[^.]*$//'
a.b
pax> echo a.b.js | sed 's/^.*\.//'
js

works fine, so you can just use:

pax> FILE=a.b.js
pax> NAME=$(echo "$FILE" | sed 's/\.[^.]*$//')
pax> EXTENSION=$(echo "$FILE" | sed 's/^.*\.//')
pax> echo $NAME
a.b
pax> echo $EXTENSION
js

The commands, by the way, work as follows.

The command for NAME substitutes a "." character followed by any number of non-"." characters up to the end of the line, with nothing (i.e., it removes everything from the final "." to the end of the line, inclusive). This is basically a non-greedy substitution using regex trickery.

The command for EXTENSION substitutes a any number of characters followed by a "." character at the start of the line, with nothing (i.e., it removes everything from the start of the line to the final dot, inclusive). This is a greedy substitution which is the default action.

Jquery find nearest matching element

var otherInput = $(this).closest('.row').find('.inputQty');

That goes up to a row level, then back down to .inputQty.

Moment.js - How to convert date string into date?

If you are getting a JS based date String then first use the new Date(String) constructor and then pass the Date object to the moment method. Like:

var dateString = 'Thu Jul 15 2016 19:31:44 GMT+0200 (CEST)';
var dateObj = new Date(dateString);
var momentObj = moment(dateObj);
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15

In case dateString is 15-07-2016, then you should use the moment(date:String, format:String) method

var dateString = '07-15-2016';
var momentObj = moment(dateString, 'MM-DD-YYYY');
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15

Simple prime number generator in Python

Just studied the topic, look for the examples in the thread and try to make my version:

from collections import defaultdict
# from pprint import pprint

import re


def gen_primes(limit=None):
    """Sieve of Eratosthenes"""
    not_prime = defaultdict(list)
    num = 2
    while limit is None or num <= limit:
        if num in not_prime:
            for prime in not_prime[num]:
                not_prime[prime + num].append(prime)
            del not_prime[num]
        else:  # Prime number
            yield num
            not_prime[num * num] = [num]
        # It's amazing to debug it this way:
        # pprint([num, dict(not_prime)], width=1)
        # input()
        num += 1


def is_prime(num):
    """Check if number is prime based on Sieve of Eratosthenes"""
    return num > 1 and list(gen_primes(limit=num)).pop() == num


def oneliner_is_prime(num):
    """Simple check if number is prime"""
    return num > 1 and not any([num % x == 0 for x in range(2, num)])


def regex_is_prime(num):
    return re.compile(r'^1?$|^(11+)\1+$').match('1' * num) is None


def simple_is_prime(num):
    """Simple check if number is prime
    More efficient than oneliner_is_prime as it breaks the loop
    """
    for x in range(2, num):
        if num % x == 0:
            return False
    return num > 1


def simple_gen_primes(limit=None):
    """Prime number generator based on simple gen"""
    num = 2
    while limit is None or num <= limit:
        if simple_is_prime(num):
            yield num
        num += 1


if __name__ == "__main__":
    less1000primes = list(gen_primes(limit=1000))
    assert less1000primes == list(simple_gen_primes(limit=1000))
    for num in range(1000):
        assert (
            (num in less1000primes)
            == is_prime(num)
            == oneliner_is_prime(num)
            == regex_is_prime(num)
            == simple_is_prime(num)
        )
    print("Primes less than 1000:")
    print(less1000primes)

    from timeit import timeit

    print("\nTimeit:")
    print(
        "gen_primes:",
        timeit(
            "list(gen_primes(limit=1000))",
            setup="from __main__ import gen_primes",
            number=1000,
        ),
    )
    print(
        "simple_gen_primes:",
        timeit(
            "list(simple_gen_primes(limit=1000))",
            setup="from __main__ import simple_gen_primes",
            number=1000,
        ),
    )
    print(
        "is_prime:",
        timeit(
            "[is_prime(num) for num in range(2, 1000)]",
            setup="from __main__ import is_prime",
            number=100,
        ),
    )
    print(
        "oneliner_is_prime:",
        timeit(
            "[oneliner_is_prime(num) for num in range(2, 1000)]",
            setup="from __main__ import oneliner_is_prime",
            number=100,
        ),
    )
    print(
        "regex_is_prime:",
        timeit(
            "[regex_is_prime(num) for num in range(2, 1000)]",
            setup="from __main__ import regex_is_prime",
            number=100,
        ),
    )
    print(
        "simple_is_prime:",
        timeit(
            "[simple_is_prime(num) for num in range(2, 1000)]",
            setup="from __main__ import simple_is_prime",
            number=100,
        ),
    )

The result of running this code show interesting results:

$ python prime_time.py
Primes less than 1000:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]

Timeit:
gen_primes: 0.6738066330144648
simple_gen_primes: 4.738092333020177
is_prime: 31.83770858097705
oneliner_is_prime: 3.3708438930043485
regex_is_prime: 8.692703998007346
simple_is_prime: 0.4686249239894096

So I can see that we have right answers for different questions here; for a prime number generator gen_primes looks like the right answer; but for a prime number check, the simple_is_prime function is better suited.

This works, but I am always open to better ways to make is_prime function.

Autoresize View When SubViews are Added

Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.

You should read Working with Auto Layout Programmatically and Visual Format Language.

You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.

Ruby: kind_of? vs. instance_of? vs. is_a?

What is the difference?

From the documentation:

- (Boolean) instance_of?(class)
Returns true if obj is an instance of the given class.

and:

- (Boolean) is_a?(class)
- (Boolean) kind_of?(class)
Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.

If that is unclear, it would be nice to know what exactly is unclear, so that the documentation can be improved.

When should I use which?

Never. Use polymorphism instead.

Why are there so many of them?

I wouldn't call two "many". There are two of them, because they do two different things.

How to declare an ArrayList with values?

Use:

List<String> x = new ArrayList<>(Arrays.asList("xyz", "abc"));

If you don't want to add new elements to the list later, you can also use (Arrays.asList returns a fixed-size list):

List<String> x = Arrays.asList("xyz", "abc");

Note: you can also use a static import if you like, then it looks like this:

import static java.util.Arrays.asList;

...

List<String> x = new ArrayList<>(asList("xyz", "abc"));

or

List<String> x = asList("xyz", "abc");

What is the maximum length of a valid email address?

According to the below article:

http://tools.ietf.org/html/rfc3696 (Page 6, Section 3)

It's mentioned that:

"There is a length limit on email addresses. That limit is a maximum of 64 characters (octets) in the "local part" (before the "@") and a maximum of 255 characters (octets) in the domain part (after the "@") for a total length of 320 characters. Systems that handle email should be prepared to process addresses which are that long, even though they are rarely encountered."

So, the maximum total length for an email address is 320 characters ("local part": 64 + "@": 1 + "domain part": 255 which sums to 320)

How to split a delimited string into an array in awk?

echo "12|23|11" | awk '{split($0,a,"|"); print a[3] a[2] a[1]}'

Google drive limit number of download

Sorry, you can't view or download this file at this time is an error message that you may get when you try to download files on Google Drive.

Bandwidth limits

Limit                          Per hour            Per day
Download via web client        750 MB              1250 MB
Upload via web client          300 MB              500 MB

The explanation for the error message is simple: while users are free to share files publicly, or with a large number of users, quotas are in effect that limit availability.

If too many users view or download a file, it may be locked for a 24 hour period before the quota is reset. The period that a file is locked may be shorter according to Google.

If a file is particularly popular, it may take days or even longer before you manage to download it to your computer or place it on your Drive storage.

It could be a solution:

  1. Locate the "uc" part of the address, and replace it with "open", so that the beginning of the URL reads * https:// drive.google.com/open?*

  2. Load the address again once you have replaced uc with open in the address.

  3. This loads a new screen with controls at the top.

  4. Click on the "add to my drive" icon at the top right.

  5. Click on "add to my drive" again to open your Google Drive storage in a new tab in the browser.

  6. You should see the locked file on your drive now.

  7. Select it with a right-click, and then the "make a copy" option from the menu.

    8.Select the copy of the file with a right-click, and there download to download the file to your local system.

Basically, what this does is create a copy of the file on your own Drive account. Since you are the owner of the copied file, you may download it to your local system this way.

Please note that this works only if you are signed in to a Google Account. Also note that you are the owner of the copied file and will be held responsible for policy violations or other issues linked to the file.

Another option is: Any public folder in Drive can host files and provide direct links to the files.

How to create the hosting URL: https:// googledrive.com/host/FolderID (your id file)

This will provide a folder that will give direct links to files inside the folder. Note: hosting view will not display files created in Google Docs.

My solution:

I had the same problem, so I made a JSON file in Google Drive but the URL file (.mp3) is in Dropbox. It is working fantastic even though I have 40,000 active user. I used this solution because I did not have time to search too much! I wrote you the Dropbox Limits anyway but I did not get problems with it

Traffic limits DROPBOX

Links and file requests are automatically banned if they generate unusually large amounts of traffic.

Dropbox Basic (free) accounts:

20 GB per day: The total amount of traffic that all of your links and file requests combined can generate without getting banned 100,000 downloads per day: The total number of downloads that all of your links combined can generate

Dropbox Plus and Business accounts: About 200 GB per day: The total amount of traffic that all of your links and file requests combined can generate without getting banned There's no daily limit to the number of downloads that your links can generate If your account hits our limit, we'll send a message to the email address registered to your account. Your links will be temporarily disabled, and anyone who tries to access them will see an error page instead of your files.

P.S. If you need more information about my files and how did it and How to make the URL File from Dropbox, I hope help to the people is reading this! (I posted it before but Someone deleted my last post)!

How to convert a byte array to a hex string in Java?

I would use something like this for fixed length, like hashes:

md5sum = String.format("%032x", new BigInteger(1, md.digest()));

I am not able launch JNLP applications using "Java Web Start"?

This can also be due to environment variable CATALINA_HOME in your system. In our organization there were several cases where JNLP applications just refused to start without logging anything and emptying CATALINA_HOME solved the issue.

I had the environment variable set in the command prompt and it didn't appear in GUI. I'm not sure if setx command or register removal commands did the trick. Restart seems to be necessary after removing the variable.

Why does CSS not support negative padding?

Because the designers of CSS didn't have the foresight to imagine the flexibility this would bring. There are plenty of reasons to expand the content area of a box without affecting its relationship to neighbouring elements. If you think it's not possible, put some long nowrap'd text in a box, set a width on the box, and watch how the overflowed content does nothing to the layout.

Yes, this is still relevant with CSS3 in 2019; case in point: flexbox layouts. Flexbox items' margins do not collapse, so in order to space them evenly and align them with the visual edge of the container, one must subtract the items' margins from their container's padding. If any result is < 0, you must use a negative margin on the container, or sum that negative with the existing margin. I.e. the content of the element effects how one defines the margins for it, which is backwards. Summing doesn't work cleanly when flex elements' content have margins defined in different units or are affected by a different font-size, etc.

The example below should, ideally have aligned and evenly spaced grey boxes but, sadly they aren't.

_x000D_
_x000D_
body {_x000D_
  font-family: sans-serif;_x000D_
  margin: 2rem;_x000D_
}_x000D_
body > * {_x000D_
  margin: 2rem 0 0;_x000D_
}_x000D_
body > :first-child {_x000D_
  margin-top: 0;_x000D_
}_x000D_
h1,_x000D_
li,_x000D_
p {_x000D_
  padding: 10px;_x000D_
  background: lightgray;_x000D_
}_x000D_
ul {_x000D_
  list-style: none;_x000D_
  display: flex;_x000D_
  flex-wrap: wrap;_x000D_
  padding: 0;/* just to reset */_x000D_
  padding: -5px;/* would allow correct alignment */_x000D_
}_x000D_
li {_x000D_
  flex: 1 1 auto;_x000D_
  margin: 5px;_x000D_
}
_x000D_
<h1>Cras facilisis orci ligula</h1>_x000D_
_x000D_
<ul>_x000D_
  <li>a lacinia purus porttitor eget</li>_x000D_
  <li>donec ut nunc lorem</li>_x000D_
  <li>duis in est dictum</li>_x000D_
  <li>tempor metus non</li>_x000D_
  <li>dapibus sapien</li>_x000D_
  <li>phasellus bibendum tincidunt</li>_x000D_
  <li>quam vitae accumsan</li>_x000D_
  <li>ut interdum eget nisl in eleifend</li>_x000D_
  <li>maecenas sodales interdum quam sed accumsan</li>_x000D_
</ul>_x000D_
_x000D_
<p>Fusce convallis, arcu vel elementum pulvinar, diam arcu tempus dolor, nec venenatis sapien diam non dui. Nulla mollis velit dapibus magna pellentesque, at tempor sapien blandit. Sed consectetur nec orci ac lobortis.</p>_x000D_
_x000D_
<p>Integer nibh purus, convallis eget tincidunt id, eleifend id lectus. Vivamus tristique orci finibus, feugiat eros id, semper augue.</p>
_x000D_
_x000D_
_x000D_

I have encountered enough of these little issues over the years where a little negative padding would have gone a long way, but instead I'm forced to add non-semantic markup, use calc(), or CSS preprocessors which only work when the units are the same, etc.

What is the best way to implement nested dictionaries?

As for "obnoxious try/catch blocks":

d = {}
d.setdefault('key',{}).setdefault('inner key',{})['inner inner key'] = 'value'
print d

yields

{'key': {'inner key': {'inner inner key': 'value'}}}

You can use this to convert from your flat dictionary format to structured format:

fd = {('new jersey', 'mercer county', 'plumbers'): 3,
 ('new jersey', 'mercer county', 'programmers'): 81,
 ('new jersey', 'middlesex county', 'programmers'): 81,
 ('new jersey', 'middlesex county', 'salesmen'): 62,
 ('new york', 'queens county', 'plumbers'): 9,
 ('new york', 'queens county', 'salesmen'): 36}

for (k1,k2,k3), v in fd.iteritems():
    d.setdefault(k1, {}).setdefault(k2, {})[k3] = v

SQL Server - transactions roll back on error?

From MDSN article, Controlling Transactions (Database Engine).

If a run-time statement error (such as a constraint violation) occurs in a batch, the default behavior in the Database Engine is to roll back only the statement that generated the error. You can change this behavior using the SET XACT_ABORT statement. After SET XACT_ABORT ON is executed, any run-time statement error causes an automatic rollback of the current transaction. Compile errors, such as syntax errors, are not affected by SET XACT_ABORT. For more information, see SET XACT_ABORT (Transact-SQL).

In your case it will rollback the complete transaction when any of inserts fail.

Can't Autowire @Repository annotated interface in Spring Boot

There is another cause for this type of problem what I would like to share, because I struggle in this problem for some time and I could't find any answer on SO.

In a repository like:

@Repository
public interface UserEntityDao extends CrudRepository<UserEntity, Long>{

}

If your entity UserEntity does not have the @Entity annotation on the class, you will have the same error.

This error is confusing for this case, because you focus on trying to resolve the problem about Spring not found the Repository but the problem is the entity. And if you came to this answer trying to test your Repository, this answer may help you.

How to effectively work with multiple files in Vim

My way to effectively work with multiple files is to use tmux.

It allows you to split windows vertically and horizontally, as in:

enter image description here

I have it working this way on both my mac and linux machines and I find it better than the native window pane switching mechanism that's provided (on Macs). I find the switching easier and only with tmux have I been able to get the 'new page at the same current directory' working on my mac (despite the fact that there seems to be options to open new panes in the same directory) which is a surprisingly critical piece. An instant new pane at the current location is amazingly useful. A method that does new panes with the same key combos for both OS's is critical for me and a bonus for all for future personal compatibility. Aside from multiple tmux panes, I've also tried using multiple tabs, e.g. enter image description here and multiple new windows, e.g. enter image description here and ultimately I've found that multiple tmux panes to be the most useful for me. I am very 'visual' and like to keep my various contexts right in front of me, connected together as panes.

tmux also support horizontal and vertical panes which the older screen didn't (though mac's iterm2 seems to support it, but again, the current directory setting didn't work for me). tmux 1.8

How to output something in PowerShell

You simply cannot get PowerShell to ommit those pesky newlines. There is no script or cmdlet that does this.

Of course Write-Host is absolute nonsense because you can't redirect/pipe from it! You simply have to write your own:

using System;

namespace WriteToStdout
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args != null)
            {
                Console.Write(string.Join(" ", args));
            }
        }
    }
}

E.g.

PS C:\> writetostdout finally I can write to stdout like echo -n
finally I can write to stdout like echo -nPS C:\>

changing permission for files and folder recursively using shell command in mac

I do not have a Mac OSx machine to test this on but in bash on Linux I use something like the following to chmod only directories:

find . -type d -exec chmod 755 {} \+

but this also does the same thing:

chmod 755 `find . -type d`

and so does this:

chmod 755 $(find . -type d)

The last two are using different forms of subcommands. The first is using backticks (older and depreciated) and the other the $() subcommand syntax.

So I think in your case that the following will do what you want.

chmod 777 $(find "/Users/Test/Desktop/PATH")

How to loop in excel without VBA or macros?

I was just searching for something similar:

I want to sum every odd row column.

SUMIF has TWO possible ranges, the range to sum from, and a range to consider criteria in.

SUMIF(B1:B1000,1,A1:A1000)

This function will consider if a cell in the B range is "=1", it will sum the corresponding A cell only if it is.

To get "=1" to return in the B range I put this in B:

=MOD(ROWNUM(B1),2)

Then auto fill down to get the modulus to fill, you could put and calculatable criteria here to get the SUMIF or SUMIFS conditions you need to loop through each cell.

Easier than ARRAY stuff and hides the back-end of loops!

How do I calculate square root in Python?

If you want to do it the way the calculator actually does it, use the Babylonian technique. It is explained here and here.

Suppose you want to calculate the square root of 2:

a=2

a1 = (a/2)+1
b1 = a/a1
aminus1 = a1
bminus1 = b1


while (aminus1-bminus1 > 0):
    an = 0.5 * (aminus1 + bminus1)
    bn = a / an
    aminus1 = an
    bminus1 = bn
    print(an,bn,an-bn)

How to check iOS version?

a bit late to the party but in light of iOS 8.0 out there this might be relevant:

if you can avoid using

[[UIDevice currentDevice] systemVersion]

Instead check for existence of of a method/class/whatever else.

if ([self.yourClassInstance respondsToSelector:@selector(<yourMethod>)]) 
{ 
    //do stuff 
}

I found it to be useful for location manager where I have to call requestWhenInUseAuthorization for iOS 8.0 but the method is not available for iOS < 8

What are all the possible values for HTTP "Content-Type" header?

You can find every content type here: http://www.iana.org/assignments/media-types/media-types.xhtml

The most common type are:

  1. Type application

    application/java-archive
    application/EDI-X12   
    application/EDIFACT   
    application/javascript   
    application/octet-stream   
    application/ogg   
    application/pdf  
    application/xhtml+xml   
    application/x-shockwave-flash    
    application/json  
    application/ld+json  
    application/xml   
    application/zip  
    application/x-www-form-urlencoded  
    
  2. Type audio

    audio/mpeg   
    audio/x-ms-wma   
    audio/vnd.rn-realaudio   
    audio/x-wav   
    
  3. Type image

    image/gif   
    image/jpeg   
    image/png   
    image/tiff    
    image/vnd.microsoft.icon    
    image/x-icon   
    image/vnd.djvu   
    image/svg+xml    
    
  4. Type multipart

    multipart/mixed    
    multipart/alternative   
    multipart/related (using by MHTML (HTML mail).)  
    multipart/form-data  
    
  5. Type text

    text/css    
    text/csv    
    text/html    
    text/javascript (obsolete)    
    text/plain    
    text/xml    
    
  6. Type video

    video/mpeg    
    video/mp4    
    video/quicktime    
    video/x-ms-wmv    
    video/x-msvideo    
    video/x-flv   
    video/webm   
    
  7. Type vnd :

    application/vnd.android.package-archive
    application/vnd.oasis.opendocument.text    
    application/vnd.oasis.opendocument.spreadsheet  
    application/vnd.oasis.opendocument.presentation   
    application/vnd.oasis.opendocument.graphics   
    application/vnd.ms-excel    
    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet   
    application/vnd.ms-powerpoint    
    application/vnd.openxmlformats-officedocument.presentationml.presentation    
    application/msword   
    application/vnd.openxmlformats-officedocument.wordprocessingml.document   
    application/vnd.mozilla.xul+xml   
    

Is there a way to remove the separator line from a UITableView?

In interface Builder set table view separator "None"

enter image description here and those separator lines which are shown after the last cell can be remove by following approach. Best approach is to assign Empty View to tableView FooterView in viewDidLoad

self.tableView.tableFooterView = UIView()

Write a mode method in Java to find the most frequently occurring element in an array

I know that this question is from a while ago, but I wanted to add an answer that I believe expands upon the original question. The addendum to this question was to write the mode method without relying upon a preset range (in this case, 0 through 100). I have written a version for mode that uses the range of values in the original array to generate the count array.

public static int mode(int[] list) {

    //Initialize max and min value variable as first value of list
    int maxValue = list[0]; 
    int minValue = list[0];

    //Finds maximum and minimum values in list
    for (int i = 1; i < list.length; i++) {
        if (list[i] > maxValue) {
            maxValue = list[i];
        }

        if (list[i] < minValue) {
            minValue = list[i];
        }
    }

    //Initialize count array with (maxValue - minValue + 1) elements  
    int[] count = new int[maxValue - minValue + 1];

    //Tally counts of values from list, store in array count
    for (int i = 0; i < list.length; i++) {
        count[list[i] - minValue]++; //Increment counter index for current value of list[i] - minValue
    }

    //Find max value in count array
    int max = count[0]; //Initialize max variable as first value of count

    for (int i = 1; i < count.length; i++) {
        if (count[i] > max) {
            max = count[i];
        }
    }

    //Find first instance where max occurs in count array
    for (int i = 0; i < count.length; i++) {
        if (count[i] == max) {
            return i + minValue; //Returns index of count adjusted for min/max list values - this is the mode value in list
        }
    }
    return -1; //Only here to force compilation, never actually used
}

Create Excel file in Java

I've created an API to create an Excel file more easier.

Create Excel - Creating Excel from Template

Just set the required values upon instantiation then invoke execute(), it will be created based on your desired output directory.

But before you use this, you must have an Excel Template which will be use as a template of the newly created Excel file.

Also, you need Apache POI in your project's class path.

Check last modified date of file in C#

Be aware that the function File.GetLastWriteTime does not always work as expected, the values are sometimes not instantaneously updated by the OS. You may get an old Timestamp, even if the file has been modified right before.

The behaviour may vary between OS versions. For example, this unit test worked well every time on my developer machine, but it always fails on our build server.

  [TestMethod]
  public void TestLastModifiedTimeStamps()
  {
     var tempFile = Path.GetTempFileName();
     var lastModified = File.GetLastWriteTime(tempFile);
     using (new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.None))
     {

     }
     Assert.AreNotEqual(lastModified, File.GetLastWriteTime(tempFile));
  }

See File.GetLastWriteTime seems to be returning 'out of date' value

Your options:

a) live with the occasional omissions.

b) Build up an active component realising the observer pattern (eg. a tcp server client structure), communicating the changes directly instead of writing / reading files. Fast and flexible, but another dependency and a possible point of failure (and some work, of course).

c) Ensure the signalling process by replacing the content of a dedicated signal file that other processes regularly read. It´s not that smart as it´s a polling procedure and has a greater overhead than calling File.GetLastWriteTime, but if not checking the content from too many places too often, it will do the work.

/// <summary>
/// type to set signals or check for them using a central file 
/// </summary>
public class FileSignal
{
    /// <summary>
    /// path to the central file for signal control
    /// </summary>
    public string FilePath { get; private set; }

    /// <summary>
    /// numbers of retries when not able to retrieve (exclusive) file access
    /// </summary>
    public int MaxCollisions { get; private set; }

    /// <summary>
    /// timespan to wait until next try
    /// </summary>
    public TimeSpan SleepOnCollisionInterval { get; private set; }

    /// <summary>
    /// Timestamp of the last signal
    /// </summary>
    public DateTime LastSignal { get; private set; }

    /// <summary>
    /// constructor
    /// </summary>
    /// <param name="filePath">path to the central file for signal control</param>
    /// <param name="maxCollisions">numbers of retries when not able to retrieve (exclusive) file access</param>
    /// <param name="sleepOnCollisionInterval">timespan to wait until next try </param>
    public FileSignal(string filePath, int maxCollisions, TimeSpan sleepOnCollisionInterval)
    {
        FilePath = filePath;
        MaxCollisions = maxCollisions;
        SleepOnCollisionInterval = sleepOnCollisionInterval;
        LastSignal = GetSignalTimeStamp();
    }

    /// <summary>
    /// constructor using a default value of 50 ms for sleepOnCollisionInterval
    /// </summary>
    /// <param name="filePath">path to the central file for signal control</param>
    /// <param name="maxCollisions">numbers of retries when not able to retrieve (exclusive) file access</param>        
    public FileSignal(string filePath, int maxCollisions): this (filePath, maxCollisions, TimeSpan.FromMilliseconds(50))
    {
    }

    /// <summary>
    /// constructor using a default value of 50 ms for sleepOnCollisionInterval and a default value of 10 for maxCollisions
    /// </summary>
    /// <param name="filePath">path to the central file for signal control</param>        
    public FileSignal(string filePath) : this(filePath, 10)
    {
    }

    private Stream GetFileStream(FileAccess fileAccess)
    {
        var i = 0;
        while (true)
        {
            try
            {
                return new FileStream(FilePath, FileMode.Create, fileAccess, FileShare.None);
            }
            catch (Exception e)
            {
                i++;
                if (i >= MaxCollisions)
                {
                    throw e;
                }
                Thread.Sleep(SleepOnCollisionInterval);
            };
        };
    }

    private DateTime GetSignalTimeStamp()
    {
        if (!File.Exists(FilePath))
        {
            return DateTime.MinValue;
        }
        using (var stream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.None))
        {
            if(stream.Length == 0)
            {
                return DateTime.MinValue;
            }
            using (var reader = new BinaryReader(stream))
            {
                return DateTime.FromBinary(reader.ReadInt64());
            };                
        }
    }

    /// <summary>
    /// overwrites the existing central file and writes the current time into it.
    /// </summary>
    public void Signal()
    {
        LastSignal = DateTime.Now;
        using (var stream = new FileStream(FilePath, FileMode.Create, FileAccess.Write, FileShare.None))
        {
            using (var writer = new BinaryWriter(stream))
            {
                writer.Write(LastSignal.ToBinary());
            }
        }
    }

    /// <summary>
    /// returns true if the file signal has changed, otherwise false.
    /// </summary>        
    public bool CheckIfSignalled()
    {
        var signal = GetSignalTimeStamp();
        var signalTimestampChanged = LastSignal != signal;
        LastSignal = signal;
        return signalTimestampChanged;
    }
}

Some tests for it:

    [TestMethod]
    public void TestSignal()
    {
        var fileSignal = new FileSignal(Path.GetTempFileName());
        var fileSignal2 = new FileSignal(fileSignal.FilePath);
        Assert.IsFalse(fileSignal.CheckIfSignalled());
        Assert.IsFalse(fileSignal2.CheckIfSignalled());
        Assert.AreEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
        fileSignal.Signal();
        Assert.IsFalse(fileSignal.CheckIfSignalled());
        Assert.AreNotEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
        Assert.IsTrue(fileSignal2.CheckIfSignalled());
        Assert.AreEqual(fileSignal.LastSignal, fileSignal2.LastSignal);
        Assert.IsFalse(fileSignal2.CheckIfSignalled());
    }

Does Arduino use C or C++?

Arduino sketches are written in C++.

Here is a typical construct you'll encounter:

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
...
lcd.begin(16, 2);
lcd.print("Hello, World!");

That's C++, not C.

Hence do yourself a favor and learn C++. There are plenty of books and online resources available.

Tomcat: LifecycleException when deploying

Remove the servlet-api.jar from build path and just add it on web-inf lib folder and then export the WAR file..it'll work...cheers..!!!

show validation error messages on submit in angularjs

I like the solution from realcrowd the best.

HTML:

<form role="form" id="form" name="form" autocomplete="off" novalidate rc-submit="signup()">
<div class="form-group" ng-class="{'has-error':  rc.form.hasError(form.firstName)}">
    <label for="firstName">Your First Name</label>
    <input type="text" id="firstName" name="firstName" class="form-control input-sm" placeholder="First Name" ng-maxlength="40" required="required" ng-model="owner.name.first"/>
    <div class="help-block" ng-show="rc.form.hasError(form.firstName)">{{rc.form.getErrMsg(form.firstName)}}</div>
</div>
</form>

javascript:

//define custom submit directive
var rcSubmitDirective = {
'rcSubmit': ['$parse', function ($parse) {
    return {
        restrict: 'A',
        require: ['rcSubmit', '?form'],
        controller: ['$scope', function ($scope) {
            this.attempted = false;

            var formController = null;

            this.setAttempted = function() {
                this.attempted = true;
            };

            this.setFormController = function(controller) {
              formController = controller;
            };

            this.hasError = function (fieldModelController) {
                if (!formController) return false;

                if (fieldModelController) {
                    return fieldModelController.$invalid && this.attempted;
                } else {
                    return formController && formController.$invalid && this.attempted;
                }
            };
            this.getErrMsg=function(ctrl){
                var e=ctrl.$error;
                var errMsg;
                if (e.required){
                    errMsg='Please enter a value';
                }
                return errMsg;
            }
        }],
        compile: function(cElement, cAttributes, transclude) {
            return {
                pre: function(scope, formElement, attributes, controllers) {

                    var submitController = controllers[0];
                    var formController = (controllers.length > 1) ? controllers[1] : null;

                    submitController.setFormController(formController);

                    scope.rc = scope.rc || {};
                    scope.rc[attributes.name] = submitController;
                },
                post: function(scope, formElement, attributes, controllers) {

                    var submitController = controllers[0];
                    var formController = (controllers.length > 1) ? controllers[1] : null;
                    var fn = $parse(attributes.rcSubmit);

                    formElement.bind('submit', function (event) {
                        submitController.setAttempted();
                        if (!scope.$$phase) scope.$apply();

                        if (!formController.$valid) return false;

                        scope.$apply(function() {
                            fn(scope, {$event:event});
                        });
                    });
                }
          };
        }
    };
}]
};
app.directive(rcSubmitDirective);

Query to list all stored procedures

Unfortunately INFORMATION_SCHEMA doesn't contain info about the system procs.

SELECT *
  FROM sys.objects
 WHERE objectproperty(object_id, N'IsMSShipped') = 0
   AND objectproperty(object_id, N'IsProcedure') = 1

does linux shell support list data structure?

It supports lists, but not as a separate data structure (ignoring arrays for the moment).

The for loop iterates over a list (in the generic sense) of white-space separated values, regardless of how that list is created, whether literally:

for i in 1 2 3; do
    echo "$i"
done

or via parameter expansion:

listVar="1 2 3"
for i in $listVar; do
    echo "$i"
done

or command substitution:

for i in $(echo 1; echo 2; echo 3); do
    echo "$i"
done

An array is just a special parameter which can contain a more structured list of value, where each element can itself contain whitespace. Compare the difference:

array=("item 1" "item 2" "item 3")
for i in "${array[@]}"; do   # The quotes are necessary here
    echo "$i"
done

list='"item 1" "item 2" "item 3"'
for i in $list; do
    echo $i
done
for i in "$list"; do
    echo $i
done
for i in ${array[@]}; do
    echo $i
done

Refresh an asp.net page on button click

  • Create a class for maintain hit counters

    public static class Counter
    {
           private static long hit;
    
           public static void HitCounter()
           {
              hit++;
           }
    
           public static long GetCounter()
           {
              return hit;
           }
    }
    
  • Increment the value of counter at page load event

    protected void Page_Load(object sender, EventArgs e)
    {
        Counter.HitCounter(); // call static function of static class Counter to increment the counter value
    }
    
  • Redirect the page on itself and display the counter value on button click

    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Write(Request.RawUrl.ToString()); // redirect on itself
        Response.Write("<br /> Counter =" + Counter.GetCounter() ); // display counter value
    }
    

Compiling an application for use in highly radioactive environments

What you ask is quite complex topic - not easily answerable. Other answers are ok, but they covered just a small part of all the things you need to do.

As seen in comments, it is not possible to fix hardware problems 100%, however it is possible with high probabily to reduce or catch them using various techniques.

If I was you, I would create the software of the highest Safety integrity level level (SIL-4). Get the IEC 61513 document (for the nuclear industry) and follow it.

How to implement my very own URI scheme on Android

This is very possible; you define the URI scheme in your AndroidManifest.xml, using the <data> element. You setup an intent filter with the <data> element filled out, and you'll be able to create your own scheme. (More on intent filters and intent resolution here.)

Here's a short example:

<activity android:name=".MyUriActivity">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="myapp" android:host="path" />
    </intent-filter>
</activity>

As per how implicit intents work, you need to define at least one action and one category as well; here I picked VIEW as the action (though it could be anything), and made sure to add the DEFAULT category (as this is required for all implicit intents). Also notice how I added the category BROWSABLE - this is not necessary, but it will allow your URIs to be openable from the browser (a nifty feature).

'names' attribute must be the same length as the vector

In the spirit of @Chris W, just try to replicate the exact error you are getting. An example would have helped but maybe you're doing:

  x <- c(1,2)
  y <- c("a","b","c")
  names(x) <- y

Error in names(x) <- y : 
  'names' attribute [3] must be the same length as the vector [2]

I suspect you're trying to give names to a vector (x) that is shorter than your vector of names (y).

Adding a directory to the PATH environment variable in Windows

Use pathed from gtools.

It does things in an intuitive way. For example:

pathed /REMOVE "c:\my\folder"
pathed /APPEND "c:\my\folder"

It shows results without the need to spawn a new cmd!

AngularJS - How to use $routeParams in generating the templateUrl?

This very helpful feature is now available starting at version 1.1.2 of AngularJS. It's considered unstable but I have used it (1.1.3) and it works fine.

Basically you can use a function to generate a templateUrl string. The function is passed the route parameters that you can use to build and return the templateUrl string.

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

app.config(
    function($routeProvider) {
        $routeProvider.
            when('/', {templateUrl:'/home'}).
            when('/users/:user_id', 
                {   
                    controller:UserView, 
                    templateUrl: function(params){ return '/users/view/' + params.user_id; }
                }
            ).
            otherwise({redirectTo:'/'});
    }
);

Many thanks to https://github.com/lrlopez for the pull request.

https://github.com/angular/angular.js/pull/1524

I want to remove double quotes from a String

To restate your problem in a way that's easier to express as a regular expression:

Get the substring of characters that is contained between zero or one leading double-quotes and zero or one trailing double-quotes.

Here's the regexp that does that:

  var regexp = /^"?(.+?)"?$/;
  var newStr = str.replace(/^"?(.+?)"?$/,'$1');

Breaking down the regexp:

  • ^"? a greedy match for zero or one leading double-quotes
  • "?$ a greedy match for zero or one trailing double-quotes
  • those two bookend a non-greedy capture of all other characters, (.+?), which will contain the target as $1.

This will return delimited "string" here for:

str = "delimited "string" here"  // ...
str = '"delimited "string" here"' // ...
str = 'delimited "string" here"' // ... and
str = '"delimited "string" here'

JSON date to Java date?

Note that SimpleDateFormat format pattern Z is for RFC 822 time zone and pattern X is for ISO 8601 (this standard supports single letter time zone names like Z for Zulu).

So new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX") produces a format that can parse both "2013-03-11T01:38:18.309Z" and "2013-03-11T01:38:18.309+0000" and will give you the same result.

Unfortunately, as far as I can tell, you can't get this format to generate the Z for Zulu version, which is annoying.

I actually have more trouble on the JavaScript side to deal with both formats.

Why is my JQuery selector returning a n.fn.init[0], and what is it?

I just want to add something to these great answers. If your DOM element ins't loading in time. You can still set the value.

let Ctrl = $('#mySelectElement'); ... Ctrl.attr('value', myValue);

after that most DOM elements that accept a value attribute should populate correctly.

How to read HDF5 files in Python

To read the content of .hdf5 file as an array, you can do something as follow

> import numpy as np 
> myarray = np.fromfile('file.hdf5', dtype=float)
> print(myarray)

Save PHP array to MySQL?

Yup, serialize/unserialize is what I've seen the most in many open source projects.

How to find cube root using Python?

The best way is to use simple math

>>> a = 8
>>> a**(1./3.)
2.0

EDIT

For Negative numbers

>>> a = -8
>>> -(-a)**(1./3.)
-2.0

Complete Program for all the requirements as specified

x = int(input("Enter an integer: "))
if x>0:
    ans = x**(1./3.)
    if ans ** 3 != abs(x):
        print x, 'is not a perfect cube!'
else:
    ans = -((-x)**(1./3.))
    if ans ** 3 != -abs(x):
        print x, 'is not a perfect cube!'

print 'Cube root of ' + str(x) + ' is ' + str(ans)

getOutputStream() has already been called for this response

Here is what worked for me in similar case.

After you finish writing into the Servlet OutputStream just call response.sendRedirect("yourPage.jsp");. That would cause initiation of a new request from the browser, therefore avoid writing into the same output stream.

how to read a text file using scanner in Java?

If you are working in some IDE like Eclipse or NetBeans, you should have that a.txt file in the root directory of your project. (and not in the folder where your .class files are built or anywhere else)

If not, you should specify the absolute path to that file.


Edit:
You would put the .txt file in the same place with the .class(usually also the .java file because you compile in the same folder) compiled files if you compile it by hand with javac. This is because it uses the relative path and the path tells the JVM the path where the executable file is located.

If you use some IDE, it will generate the compiled files for you using a Makefile or something similar for Windows and will consider it's default file structure, so he knows that the relative path begins from the root folder of the project.

Multi-line bash commands in makefile

The ONESHELL directive allows to write multiple line recipes to be executed in the same shell invocation.

all: foo

SOURCE_FILES = $(shell find . -name '*.c')

.ONESHELL:
foo: ${SOURCE_FILES}
    FILES=()
    for F in $^; do
        FILES+=($${F})
    done
    gcc "$${FILES[@]}" -o $@

There is a drawback though : special prefix characters (‘@’, ‘-’, and ‘+’) are interpreted differently.

https://www.gnu.org/software/make/manual/html_node/One-Shell.html

Convert date from 'Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)' to 'YYYY-MM-DD' in javascript

Above solutions will work only if its a string. Input type date, gives you output in javascript date object in some cases like if you use angular or so. That's why some people are getting error like "TypeError: str.split is not a function". It's a date object, so you should use functions of Date object in javascript to manipulate it. Example here:

var date = $scope.dateObj ; 
//dateObj is data bind to the ng-modal of input type dat.
console.log(date.getFullYear()); //this will give you full year eg : 1990
console.log(date.getDate()); //gives you the date from 1 to 31
console.log(date.getMonth() + 1); //getMonth will give month from 0 to 11 

Check the following link for reference:

Difference between Dictionary and Hashtable

Want to add a difference:

Trying to acess a inexistent key gives runtime error in Dictionary but no problem in hashtable as it returns null instead of error.

e.g.

       //No strict type declaration
        Hashtable hash = new Hashtable();
        hash.Add(1, "One");
        hash.Add(2, "Two");
        hash.Add(3, "Three");
        hash.Add(4, "Four");
        hash.Add(5, "Five"); 
        hash.Add(6, "Six");
        hash.Add(7, "Seven");
        hash.Add(8, "Eight");
        hash.Add(9, "Nine");
        hash.Add("Ten", 10);// No error as no strict type

        for(int i=0;i<=hash.Count;i++)//=>No error for index 0
        {
            //Can be accessed through indexers
            Console.WriteLine(hash[i]);
        }
        Console.WriteLine(hash["Ten"]);//=> No error in Has Table

here no error for key 0 & also for key "ten"(note: t is small)

//Strict type declaration
        Dictionary<int,string> dictionary= new Dictionary<int, string>();
        dictionary.Add(1, "One");
        dictionary.Add(2, "Two");
        dictionary.Add(3, "Three");
        dictionary.Add(4, "Four");
        dictionary.Add(5, "Five");
        dictionary.Add(6, "Six");
        dictionary.Add(7, "Seven");
        dictionary.Add(8, "Eight");
        dictionary.Add(9, "Nine");
        //dictionary.Add("Ten", 10);// error as only key, value pair of type int, string can be added

        //for i=0, key doesn't  exist error
        for (int i = 1; i <= dictionary.Count; i++)
        {
            //Can be accessed through indexers
            Console.WriteLine(dictionary[i]);
        }
        //Error : The given key was not present in the dictionary.
        //Console.WriteLine(dictionary[10]);

here error for key 0 & also for key 10 as both are inexistent in dictionary, runtime error, while try to acess.

isPrime Function for Python Language

int(n**0.5) is the floor value of sqrt(n) which you confused with power 2 of n (n**2). If n is not prime, there must be two numbers 1 < i <= j < n such that: i * j = n.

Now, since sqrt(n) * sqrt(n) = n assuming one of i,j is bigger than (or equals to) sqrt(n) - it means that the other one has to be smaller than (or equals to) sqrt(n).

Since that is the case, it's good enough to iterate the integer numbers in the range [2, sqrt(n)]. And that's exactly what the code that was posted is doing.

If you want to come out as a real smartass, use the following one-liner function:

import re
def is_prime(n):    
    return not re.match(r'^1?$|^(11+?)\1+$',n*'1')

An explanation for the "magic regex" can be found here

git returns http error 407 from proxy after CONNECT

Your password seems to be incorrect. Recheck your credentials.

jQuery - trapping tab select event

Simply use the on click event for tab shown.

$(document).on('shown.bs.tab', 'a[href="#tab"]', function (){
});

Any way to write a Windows .bat file to kill processes?

As TASKKILL might be unavailable on some Home/basic editions of windows here some alternatives:

TSKILL processName

or

TSKILL PID

Have on mind that processName should not have the .exe suffix and is limited to 18 characters.

Another option is WMIC :

wmic Path win32_process Where "Caption Like 'MyProcess%.exe'" Call Terminate

wmic offer even more flexibility than taskkill with its SQL-like matchers .With wmic Path win32_process get you can see the available fileds you can filter (and % can be used as a wildcard).

Running Facebook application on localhost

In my case the issue revealed to be chrome blocking the CORS request from localhost:4200 to facebook api website. Running Chrome with this setting: "YOUR_PATH_TO_CHROME\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="c:/chrome worked like a charm while developing. Even with no localhost added to facebook app's settings.

Random shuffling of an array

Here is a complete solution using the Collections.shuffle approach:

public static void shuffleArray(int[] array) {
  List<Integer> list = new ArrayList<>();
  for (int i : array) {
    list.add(i);
  }

  Collections.shuffle(list);

  for (int i = 0; i < list.size(); i++) {
    array[i] = list.get(i);
  }    
}

Note that it suffers due to Java's inability to smoothly translate between int[] and Integer[] (and thus int[] and List<Integer>).

Right mime type for SVG images with fonts embedded

There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml mediatype.

Remove non-ASCII characters from CSV

This worked for me:

sed -i 's/[^[:print:]]//g'

How do I mock an autowired @Value field in Spring with Mockito?

You can use the magic of Spring's ReflectionTestUtils.setField in order to avoid making any modifications whatsoever to your code.

The comment from Michal Stochmal provides an example:

use ReflectionTestUtils.setField(bean, "fieldName", "value"); before invoking your bean method during test.

Check out this tutorial for even more information, although you probably won't need it since the method is very easy to use

UPDATE

Since the introduction of Spring 4.2.RC1 it is now possible to set a static field without having to supply an instance of the class. See this part of the documentation and this commit.

Overlaying a DIV On Top Of HTML 5 Video

<div id="video_box">
  <div id="video_overlays"></div>
  <div>
    <video id="player" src="http://video.webmfiles.org/big-buck-bunny_trailer.webm" type="video/webm" onclick="this.play();">Your browser does not support this streaming content.</video>
  </div>
</div>

for this you need to just add css like this:

#video_overlays {
  position: absolute;
  background-color: rgba(0, 0, 0, 0.46);
  z-index: 2;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}
#video_box{position: relative;}

How to check if $_GET is empty?

i guess the simplest way which doesn't require any operators is

if($_GET){
//do something if $_GET is set 
} 
if(!$_GET){
//do something if $_GET is NOT set 
} 

How do I profile memory usage in Python?

A simple example to calculate the memory usage of a block of codes / function using memory_profile, while returning result of the function:

import memory_profiler as mp

def fun(n):
    tmp = []
    for i in range(n):
        tmp.extend(list(range(i*i)))
    return "XXXXX"

calculate memory usage before running the code then calculate max usage during the code:

start_mem = mp.memory_usage(max_usage=True)
res = mp.memory_usage(proc=(fun, [100]), max_usage=True, retval=True) 
print('start mem', start_mem)
print('max mem', res[0][0])
print('used mem', res[0][0]-start_mem)
print('fun output', res[1])

calculate usage in sampling points while running function:

res = mp.memory_usage((fun, [100]), interval=.001, retval=True)
print('min mem', min(res[0]))
print('max mem', max(res[0]))
print('used mem', max(res[0])-min(res[0]))
print('fun output', res[1])

Credits: @skeept

How to downgrade or install an older version of Cocoapods

Actually, you don't need to downgrade – if you need to use older version in some projects, just specify the version that you need to use after pod command.

pod _0.37.2_ setup

Call a PHP function after onClick HTML event

 cell1.innerHTML="<?php echo $customerDESC; ?>";
 cell2.innerHTML="<?php echo $comm; ?>";
 cell3.innerHTML="<?php echo $expressFEE; ?>";
 cell4.innerHTML="<?php echo $totao_unit_price; ?>";

it is working like a charm, the javascript is inside a php while loop

MySQL dump by query

If you want to export your last n amount of records into a file, you can run the following:

mysqldump -u user -p -h localhost --where "1=1 ORDER BY id DESC LIMIT 100" database table > export_file.sql

The above will save the last 100 records into export_file.sql, assuming the table you're exporting from has an auto-incremented id column.

You will need to alter the user, localhost, database and table values. You may optionally alter the id column and export file name.

Python, compute list difference

In case of a list of dictionaries, the full list comprehension solution works while the set solution raises

TypeError: unhashable type: 'dict'

Test Case

def diff(a, b):
    return [aa for aa in a if aa not in b]

d1 = {"a":1, "b":1}
d2 = {"a":2, "b":2}
d3 = {"a":3, "b":3}

>>> diff([d1, d2, d3], [d2, d3])
[{'a': 1, 'b': 1}]
>>> diff([d1, d2, d3], [d1])
[{'a': 2, 'b': 2}, {'a': 3, 'b': 3}]

jQuery: using a variable as a selector

You're thinking too complicated. It's actually just $('#'+openaddress).

Count the number occurrences of a character in a string

I know the ask is to count a particular letter. I am writing here generic code without using any method.

sentence1 =" Mary had a little lamb"
count = {}
for i in sentence1:
    if i in count:
        count[i.lower()] = count[i.lower()] + 1
    else:
        count[i.lower()] = 1
print(count)

output

{' ': 5, 'm': 2, 'a': 4, 'r': 1, 'y': 1, 'h': 1, 'd': 1, 'l': 3, 'i': 1, 't': 2, 'e': 1, 'b': 1}

Now if you want any particular letter frequency, you can print like below.

print(count['m'])
2

Laravel 5 Application Key

Just as another option if you want to print only the key (doesn't write the .env file) you can use:

php artisan key:generate --show

Delete all lines starting with # or ; in Notepad++

Maybe you should try

^[#;].*$

^ matches the beggining, $ the end.

With android studio no jvm found, JAVA_HOME has been set

It says that it should be a 64-bit JDK. I have a feeling that you installed (at a previous time) a 32-bit version of Java. The path for all 32-bit applications in Windows 7 and Vista is:

C:\Program Files (x86)\

You were setting the JAVA_HOME variable to the 32-bit version of Java. Set your JAVA_HOME variable to the following:

C:\Program Files\Java\jdk1.7.0_45

If that does not work, check that the JDK version is 1.7.0_45. If not, change the JAVA_HOME variable to (with JAVAVERSION as the Java version number:

C:\Program Files\Java\jdkJAVAVERSION

An established connection was aborted by the software in your host machine

follow this two step 1) adb kill-server 2) adb start-server

this is work for me

How do you pass a function as a parameter in C?

Declaration

A prototype for a function which takes a function parameter looks like the following:

void func ( void (*f)(int) );

This states that the parameter f will be a pointer to a function which has a void return type and which takes a single int parameter. The following function (print) is an example of a function which could be passed to func as a parameter because it is the proper type:

void print ( int x ) {
  printf("%d\n", x);
}

Function Call

When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this:

func(print);

would call func, passing the print function to it.

Function Body

As with any parameter, func can now use the parameter's name in the function body to access the value of the parameter. Let's say that func will apply the function it is passed to the numbers 0-4. Consider, first, what the loop would look like to call print directly:

for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
  print(ctr);
}

Since func's parameter declaration says that f is the name for a pointer to the desired function, we recall first that if f is a pointer then *f is the thing that f points to (i.e. the function print in this case). As a result, just replace every occurrence of print in the loop above with *f:

void func ( void (*f)(int) ) {
  for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
    (*f)(ctr);
  }
}

Source

Compare dates in MySQL

this is what it worked for me:

select * from table
where column
BETWEEN STR_TO_DATE('29/01/15', '%d/%m/%Y')
 AND STR_TO_DATE('07/10/15', '%d/%m/%Y')

Please, note that I had to change STR_TO_DATE(column, '%d/%m/%Y') from previous solutions, as it was taking ages to load

Convert String to java.util.Date

You should set a TimeZone in your DateFormat, otherwise it will use the default one (depending on the settings of the computer).

Entity Framework Provider type could not be loaded?

I sorted it out with [DeploymentItem] on my assembly initializing class

namespace MyTests
{
    /// <summary>
    /// Summary description for AssemblyTestInit
    /// </summary>
    [TestClass]
    [DeploymentItem("EntityFramework.SqlServer.dll")]
    public class AssemblyTestInit
    {
        public AssemblyTestInit()
        {
        }

        private TestContext testContextInstance;

        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        [AssemblyInitialize()]
        public static void DbContextInitialize(TestContext testContext)
        {
            Database.SetInitializer<TestContext>(new TestContextInitializer());
        }
    }
}

Application not picking up .css file (flask/python)

If any of the above method is not working and you code is perfect then try hard refreshing by pressing Ctrl + F5. It will clear all the chaces and then reload file. It worked for me.

Converting integer to string in Python

With the introduction of f-strings in Python 3.6, this will also work:

f'{10}' == '10'

It is actually faster than calling str(), at the cost of readability.

In fact, it's faster than %x string formatting and .format()!

Use basic authentication with jQuery and Ajax

The examples above are a bit confusing, and this is probably the best way:

$.ajaxSetup({
  headers: {
    'Authorization': "Basic " + btoa(USERNAME + ":" + PASSWORD)
  }
});

I took the above from a combination of Rico and Yossi's answer.

The btoa function Base64 encodes a string.

How to implement if-else statement in XSLT?

If statement is used for checking just one condition quickly. When you have multiple options, use <xsl:choose> as illustrated below:

   <xsl:choose>
     <xsl:when test="$CreatedDate > $IDAppendedDate">
       <h2>mooooooooooooo</h2>
     </xsl:when>
     <xsl:otherwise>
      <h2>dooooooooooooo</h2>
     </xsl:otherwise>
   </xsl:choose>

Also, you can use multiple <xsl:when> tags to express If .. Else If or Switch patterns as illustrated below:

   <xsl:choose>
     <xsl:when test="$CreatedDate > $IDAppendedDate">
       <h2>mooooooooooooo</h2>
     </xsl:when>
     <xsl:when test="$CreatedDate = $IDAppendedDate">
       <h2>booooooooooooo</h2>
     </xsl:when>
     <xsl:otherwise>
      <h2>dooooooooooooo</h2>
     </xsl:otherwise>
   </xsl:choose>

The previous example would be equivalent to the pseudocode below:

   if ($CreatedDate > $IDAppendedDate)
   {
       output: <h2>mooooooooooooo</h2>
   }
   else if ($CreatedDate = $IDAppendedDate)
   {
       output: <h2>booooooooooooo</h2>
   }
   else
   {
       output: <h2>dooooooooooooo</h2>
   }

calling server side event from html button control

On your aspx page define the HTML Button element with the usual suspects: runat, class, title, etc.

If this element is part of a data bound control (i.e.: grid view, etc.) you may want to use CommandName and possibly CommandArgument as attributes. Add your button's content and closing tag.

<button id="cmdAction" 
    runat="server" onserverclick="cmdAction_Click()" 
    class="Button Styles" 
    title="Does something on the server" 
    <!-- for databound controls -->
    CommandName="cmdname"> 
    CommandArgument="args..."
    >
    <!-- content -->
    <span class="ui-icon ..."></span>
    <span class="push">Click Me</span>
</button>

On the code behind page the element would call the handler that would be defined as the element's ID_Click event function.

protected void cmdAction_Click(object sender, EventArgs e)
{
: do something.
}

There are other solutions as in using custom controls, etc. Also note that I am using this live on projects in VS2K8.

Hoping this helps. Enjoy!

Qt - reading from a text file

You have to replace string line

QString line = in.readLine();

into while:

QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
    QMessageBox::information(0, "error", file.errorString());
}

QTextStream in(&file);

while(!in.atEnd()) {
    QString line = in.readLine();    
    QStringList fields = line.split(",");    
    model->appendRow(fields);    
}

file.close();

How to save a plot as image on the disk?

dev.copy(png,'path/pngFile.png')
plot(YData ~ XData, data = mydata)
dev.off()

How to get attribute of element from Selenium?

As the recent developed Web Applications are using JavaScript, jQuery, AngularJS, ReactJS etc there is a possibility that to retrieve an attribute of an element through Selenium you have to induce WebDriverWait to synchronize the WebDriver instance with the lagging Web Client i.e. the Web Browser before trying to retrieve any of the attributes.

Some examples:

  • Python:

    • To retrieve any attribute form a visible element (e.g. <h1> tag) you need to use the expected_conditions as visibility_of_element_located(locator) as follows:

      attribute_value = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.ID, "org"))).get_attribute("attribute_name")
      
    • To retrieve any attribute form an interactive element (e.g. <input> tag) you need to use the expected_conditions as element_to_be_clickable(locator) as follows:

      attribute_value = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "org"))).get_attribute("attribute_name")
      

HTML Attributes

Below is a list of some attributes often used in HTML

HTML Attributes

Note: A complete list of all attributes for each HTML element, is listed in: HTML Attribute Reference

Sql Server string to date conversion

If you want SQL Server to try and figure it out, just use CAST CAST('whatever' AS datetime) However that is a bad idea in general. There are issues with international dates that would come up. So as you've found, to avoid those issues, you want to use the ODBC canonical format of the date. That is format number 120, 20 is the format for just two digit years. I don't think SQL Server has a built-in function that allows you to provide a user given format. You can write your own and might even find one if you search online.

Display rows with one or more NaN values in pandas dataframe

Suppose gamma1 and gamma2 are two such columns for which df.isnull().any() gives True value , the following code can be used to print the rows.

bool1 = pd.isnull(df['gamma1'])
bool2 = pd.isnull(df['gamma2'])
df[bool1]
df[bool2]

How to create a String with carriage returns?

Try \r\n where \r is carriage return. Also ensure that your output do not have new line, because debugger can show you special characters in form of \n, \r, \t etc.

Get the real width and height of an image with JavaScript? (in Safari/Chrome)

Webkit browsers set the height and width property after the image is loaded. Instead of using timeouts, I'd recommend using an image's onload event. Here's a quick example:

var img = $("img")[0]; // Get my img elem
var pic_real_width, pic_real_height;
$("<img/>") // Make in memory copy of image to avoid css issues
    .attr("src", $(img).attr("src"))
    .load(function() {
        pic_real_width = this.width;   // Note: $(this).width() will not
        pic_real_height = this.height; // work for in memory images.
    });

To avoid any of the effects CSS might have on the image's dimensions, the code above makes an in memory copy of the image. This is a very clever solution suggested by FDisk.

You can also use the naturalHeight and naturalWidth HTML5 attributes.

Split pandas dataframe in two if it has more than 10 rows

The method based on list comprehension and groupby, which stores all the split dataframes in a list variable and can be accessed using the index.

Example:

ans = [pd.DataFrame(y) for x, y in DF.groupby('column_name', as_index=False)]***
ans[0]
ans[0].column_name

_csv.Error: field larger than field limit (131072)

The csv file might contain very huge fields, therefore increase the field_size_limit:

import sys
import csv

csv.field_size_limit(sys.maxsize)

sys.maxsize works for Python 2.x and 3.x. sys.maxint would only work with Python 2.x (SO: what-is-sys-maxint-in-python-3)

Update

As Geoff pointed out, the code above might result in the following error: OverflowError: Python int too large to convert to C long. To circumvent this, you could use the following quick and dirty code (which should work on every system with Python 2 and Python 3):

import sys
import csv
maxInt = sys.maxsize

while True:
    # decrease the maxInt value by factor 10 
    # as long as the OverflowError occurs.

    try:
        csv.field_size_limit(maxInt)
        break
    except OverflowError:
        maxInt = int(maxInt/10)

How to make the background image to fit into the whole page without repeating using plain css?

You can either use JavaScript or CSS3.

JavaScript solution: Use an absolute positioned <img> tag and resize it on the page load and whenever the page resizes. Be careful of possible bugs when trying to get the page/window size.

CSS3 solution: Use the CSS3 background-size property. You might use either 100% 100% or contain or cover, depending on how you want the image to resize. Of course, this only works on modern browsers.

Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

If none of the solutions work for you, the handling the post-autoload-dump event returned with error code 1 error can also be caused by using Composer 2 instead of Composer 1. That can happen when you run the install command manually in something like a Dockerfile, and it installs newest. Just modify your command to install the last 1.x.x stable version with the --1 option:

curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer --1

Or, specify a certain version with --version=x.x.x:

curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer --version=1.10.17

It might be good to also delete your vendor directory and composer.lock file so that nothing stale interferes with the version downgrade, before calling composer install as usual.

Find Item in ObservableCollection without using a loop

Here comes Linq:

var listItem = list.Single(i => i.Title == title);

It throws an exception if there's no item matching the predicate. Alternatively, there's SingleOrDefault.

If you want a collection of items matching the title, there's:

var listItems = list.Where(i => i.Title ==  title);

Repeat rows of a data.frame

Another way to do this would to first get row indices, append extra copies of the df, and then order by the indices:

df$index = 1:nrow(df)
df = rbind(df,df)
df = df[order(df$index),][,-ncol(df)]

Although the other solutions may be shorter, this method may be more advantageous in certain situations.

What characters can be used for up/down triangle (arrow without stem) for display in HTML?

"Not ASCII (neither's ?/?)" needs qualification.

While these characters are not defined in the American Standard Code for Information Interchange as glyphs, their codes WERE commonly used to give a graphical presentation for ASCII codes 24 and 25 (hex 18 and 19, CANcel and EM:End of Medium). Code page 437 (called Extended ASCII by IBM, includes the numeric codes 128 to 255) defined the use of these glyphs as ASCII codes and the ubiquity of these conventions permeated the industry as seen by their deployment as standards by leading companies such as HP, particularly for printers, and IBM, particularly for microcomputers starting with the original PC.

Just as the use of the ASCII codes for CAN and EM was relatively obsolete at the time, justifying their use as glyphs, so has the passage of time made the use of the codes as glyphs obsolete by the current use of UNICODE conventions.


It should be emphasized that the extensions to ASCII made by IBM in Extended ASCII, included not only a larger numeric set for numeric codes 128 to 255, but also extended the use of some numeric control codes, in the ASCII range 0 to 32, from just media transmission control protocols to include glyphs. It is often assumed, incorrectly, that the first 0 to 128 were not "extended" and that IBM was using the glyphs of conventional ASCII for this range. This error is also perpetrated in one of the previous references. This error became so pervasive that it colloquially redefined ASCII subliminally.

How to solve this java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream?

You will have to download file from here https://commons.apache.org/proper/commons-io/download_io.cgi and select https://prnt.sc/tk5ewt

Now, Next add this downloaded files into your project:

Right click to your project ->Build path->Configure BuidPath -> https://prnt.sc/tk5d93

How to extract a string between two delimiters

If you have just a pair of brackets ( [] ) in your string, you can use indexOf():

String str = "ABC[ This is the text to be extracted ]";    
String result = str.substring(str.indexOf("[") + 1, str.indexOf("]"));

Swift presentViewController

For those getting blank/black screens this code worked for me.

    let vc = self.storyboard?.instantiateViewController(withIdentifier: myVCID) as! myVCName
    self.present(vc, animated: true, completion: nil)

To set the "Identifier" to your VC just go to identity inspector for the VC in the storyboard. Set the 'Storyboard ID' to what ever you want to identifier to be. Look at the image below for reference.

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

I experienced this today. The value in Config was the updated one but the application would return the older value, stop and starting the solution did nothing.

So I cleared the .Net Temp folder.

C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files

It shouldn't create bugs but to be safe close your solution down first. Clear the Temporary ASP.NET Files then load up your solution.

My issue was sorted.

Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?

Other type of format :

$headers[] = 'Accept: application/json';
$headers[] = 'Content-Type: application/json';
$headers[] = 'Content-length: 0';

curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);

Java equivalent to C# extension methods

Technically C# Extension have no equivalent in Java. But if you do want to implement such functions for a cleaner code and maintainability, you have to use Manifold framework.

package extensions.java.lang.String;

import manifold.ext.api.*;

@Extension
public class MyStringExtension {

  public static void print(@This String thiz) {
    System.out.println(thiz);
  }

  @Extension
  public static String lineSeparator() {
    return System.lineSeparator();
  }
}

Document Root PHP

The Easiest way to do it is to have good site structure and write it as a constant.

DEFINE("BACK_ROOT","/var/www/");

PHP FPM - check if running

in case it helps someone, on amilinux, with php5.6 and php-fpm installed, it's:

sudo /etc/init.d/php-fpm-5.6 status

notifyDataSetChanged not working on RecyclerView

I had same problem. I just solved it with declaring adapter public before onCreate of class.

PostAdapter postAdapter;

after that

postAdapter = new PostAdapter(getActivity(), posts);
recList.setAdapter(postAdapter);

at last I have called:

@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
    // Display the size of your ArrayList
    Log.i("TAG", "Size : " + posts.size());
    progressBar.setVisibility(View.GONE);
    postAdapter.notifyDataSetChanged();
}

May this will helps you.

Multiple inputs on one line

Yes, you can.

From cplusplus.com:

Because these functions are operator overloading functions, the usual way in which they are called is:

   strm >> variable;

Where strm is the identifier of a istream object and variable is an object of any type supported as right parameter. It is also possible to call a succession of extraction operations as:

   strm >> variable1 >> variable2 >> variable3; //...

which is the same as performing successive extractions from the same object strm.

Just replace strm with cin.

How to find the number of days between two dates

To find the number of days between two dates, you use:

DATEDIFF ( d, startdate , enddate )

How to create an XML document using XmlDocument?

Working with a dictionary ->level2 above comes from a dictionary in my case (just in case anybody will find it useful) Trying the first example I stumbled over this error: "This document already has a 'DocumentElement' node." I was inspired by the answer here

and edited my code: (xmlDoc.DocumentElement.AppendChild(body))

//a dictionary:
Dictionary<string, string> Level2Data 
{
    {"level2", "text"},
    {"level2", "other text"},
    {"same_level2", "more text"}
}
//xml Decalration:
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = xmlDoc.DocumentElement;
xmlDoc.InsertBefore(xmlDeclaration, root);
// add body
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.AppendChild(body);
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.DocumentElement.AppendChild(body); //without DocumentElement ->ERR



foreach (KeyValuePair<string, string> entry in Level2Data)
{
    //write to xml: - it works version 1.
    XmlNode keyNode = xmlDoc.CreateElement(entry.Key); //open TAB
    keyNode.InnerText = entry.Value;
    body.AppendChild(keyNode); //close TAB

    //Write to xmml verdion 2: (uncomment the next 4 lines and comment the above 3 - version 1
    //XmlElement key = xmlDoc.CreateElement(string.Empty, entry.Key, string.Empty);
    //XmlText value = xmlDoc.CreateTextNode(entry.Value);
    //key.AppendChild(value);
    //body.AppendChild(key);
}

Both versions (1 and 2 inside foreach loop) give the output:

<?xml version="1.0" encoding="UTF-8"?>
<body>
    <level1>
        <level2>text</level2>
        <level2>ther text</level2>
         <same_level2>more text</same_level2>
    </level1>
</body>

(Note: third line "same level2" in dictionary can be also level2 as the others but I wanted to ilustrate the advantage of the dictionary - in my case I needed level2 with different names.

Getting attribute using XPath

You can also get it by

string(//bookstore/book[1]/title/@lang)    
string(//bookstore/book[2]/title/@lang)

although if you are using XMLDOM with JavaScript you can code something like

var n1 = uXmlDoc.selectSingleNode("//bookstore/book[1]/title/@lang");

and n1.text will give you the value "eng"

Where to find the complete definition of off_t type?

If you are having trouble tracing the definitions, you can use the preprocessed output of the compiler which will tell you all you need to know. E.g.

$ cat test.c
#include <stdio.h>
$ cc -E test.c | grep off_t
typedef long int __off_t;
typedef __off64_t __loff_t;
  __off_t __pos;
  __off_t _old_offset;
typedef __off_t off_t;
extern int fseeko (FILE *__stream, __off_t __off, int __whence);
extern __off_t ftello (FILE *__stream) ;

If you look at the complete output you can even see the exact header file location and line number where it was defined:

# 132 "/usr/include/bits/types.h" 2 3 4


typedef unsigned long int __dev_t;
typedef unsigned int __uid_t;
typedef unsigned int __gid_t;
typedef unsigned long int __ino_t;
typedef unsigned long int __ino64_t;
typedef unsigned int __mode_t;
typedef unsigned long int __nlink_t;
typedef long int __off_t;
typedef long int __off64_t;

...

# 91 "/usr/include/stdio.h" 3 4
typedef __off_t off_t;

NSOperation vs Grand Central Dispatch

Both NSQueueOperations and GCD allow executing heavy computation task in the background on separate threads by freeing the UI Application Main Tread.

Well, based previous post we see NSOperations has addDependency so that you can queue your operation one after another sequentially.

But I also read about GCD serial Queues you can create run your operations in the queue using dispatch_queue_create. This will allow running a set of operations one after another in a sequential manner.

NSQueueOperation Advantages over GCD:

  1. It allows to add dependency and allows you to remove dependency so for one transaction you can run sequential using dependency and for other transaction run concurrently while GCD doesn't allow to run this way.

  2. It is easy to cancel an operation if it is in the queue it can be stopped if it is running.

  3. You can define the maximum number of concurrent operations.

  4. You can suspend operation which they are in Queue

  5. You can find how many pending operations are there in queue.

Need to perform Wildcard (*,?, etc) search on a string using Regex

d* means that it should match zero or more "d" characters. So any string is a valid match. Try d+ instead!

In order to have support for wildcard patterns I would replace the wildcards with the RegEx equivalents. Like * becomes .* and ? becomes .?. Then your expression above becomes d.*

How to position two divs horizontally within another div

When you float sub-left and sub-right they no longer take up any space within sub-title. You need to add another div with style = "clear: both" beneath them to expand the containing div or they appear below it.

HTML:

<div id="sub-title">
   <div id="sub-left">
      sub-left
   </div>
   <div id="sub-right">
      sub-right
   </div>
   <div class="clear-both"></div>
</div>

CSS:

#sub-left {
   float: left;
}
#sub-right {
   float: right;
}
.clear-both {
   clear: both;
}

PHP to search within txt file and echo the whole line

Do it like this. This approach lets you search a file of any size (big size won't crash the script) and will return ALL lines that match the string you want.

<?php
$searchthis = "mystring";
$matches = array();

$handle = @fopen("path/to/inputfile.txt", "r");
if ($handle)
{
    while (!feof($handle))
    {
        $buffer = fgets($handle);
        if(strpos($buffer, $searchthis) !== FALSE)
            $matches[] = $buffer;
    }
    fclose($handle);
}

//show results:
print_r($matches);
?>

Note the way strpos is used with !== operator.

What are the correct version numbers for C#?

C# 1.0 - Visual Studio .NET 2002

Classes
Structs
Interfaces
Events
Properties
Delegates
Expressions
Statements
Attributes
Literals

C# 1.2 - Visual Studio .NET 2003

Dispose in foreach
foreach over string specialization
C# 2 - Visual Studio 2005
Generics
Partial types
Anonymous methods
Iterators
Nullable types
Getter/setter separate accessibility
Method group conversions (delegates)
Static classes
Delegate inference

C# 3 - Visual Studio 2008

Implicitly typed local variables
Object and collection initializers
Auto-Implemented properties
Anonymous types
Extension methods
Query expressions
Lambda expression
Expression trees
Partial methods

C# 4 - Visual Studio 2010

Dynamic binding
Named and optional arguments
Co- and Contra-variance for generic delegates and interfaces
Embedded interop types ("NoPIA")

C# 5 - Visual Studio 2012

    Asynchronous methods
    Caller info attributes

C# 6 - Visual Studio 2015

Draft Specification online
Compiler-as-a-service (Roslyn)
Import of static type members into namespace
Exception filters
Await in catch/finally blocks
Auto property initializers
Default values for getter-only properties
Expression-bodied members
Null propagator (null-conditional operator, succinct null checking)
String interpolation
nameof operator
Dictionary initializer

C# 7.0 - Visual Studio 2017

Out variables
Pattern matching
Tuples
Deconstruction
Discards
Local Functions
Binary Literals
Digit Separators
Ref returns and locals
Generalized async return types
More expression-bodied members
Throw expressions

C# 7.1 - Visual Studio 2017 version 15.3

Async main
Default expressions
Reference assemblies
Inferred tuple element names
Pattern-matching with generics

C# 7.2 - Visual Studio 2017 version 15.5

Span and ref-like types
In parameters and readonly references
Ref conditional
Non-trailing named arguments
Private protected accessibility
Digit separator after base specifier

C# 7.3 - Visual Studio 2017 version 15.7

System.Enum, System.Delegate and unmanaged constraints.
Ref local re-assignment: Ref locals and ref parameters can now be reassigned with the ref assignment operator (= ref).
Stackalloc initializers: Stack-allocated arrays can now be initialized, e.g. Span<int> x = stackalloc[] { 1, 2, 3 };.
Indexing movable fixed buffers: Fixed buffers can be indexed into without first being pinned.
Custom fixed statement: Types that implement a suitable GetPinnableReference can be used in a fixed statement.
Improved overload candidates: Some overload resolution candidates can be ruled out early, thus reducing ambiguities.
Expression variables in initializers and queries: Expression variables like out var and pattern variables are allowed in field initializers, constructor initializers and LINQ queries.
Tuple comparison: Tuples can now be compared with == and !=.
Attributes on backing fields: Allows [field: …] attributes on an auto-implemented property to target its backing field.

C# 8.0 - .NET Core 3.0 and Visual Studio 2019 version 16.3

Nullable reference types: express nullability intent on reference types with ?, notnull constraint and annotations attributes in APIs, the compiler will use those to try and detect possible null values being dereferenced or passed to unsuitable APIs.
Default interface members: interfaces can now have members with default implementations, as well as static/private/protected/internal members except for state (ie. no fields).
Recursive patterns: positional and property patterns allow testing deeper into an object, and switch expressions allow for testing multiple patterns and producing corresponding results in a compact fashion.
Async streams: await foreach and await using allow for asynchronous enumeration and disposal of IAsyncEnumerable<T> collections and IAsyncDisposable resources, and async-iterator methods allow convenient implementation of such asynchronous streams.
Enhanced using: a using declaration is added with an implicit scope and using statements and declarations allow disposal of ref structs using a pattern.
Ranges and indexes: the i..j syntax allows constructing System.Range instances, the ^k syntax allows constructing System.Index instances, and those can be used to index/slice collections.
Null-coalescing assignment: ??= allows conditionally assigning when the value is null.
Static local functions: local functions modified with static cannot capture this or local variables, and local function parameters now shadow locals in parent scopes.
Unmanaged generic structs: generic struct types that only have unmanaged fields are now considered unmanaged (ie. they satisfy the unmanaged constraint).
Readonly members: individual members can now be marked as readonly to indicate and enforce that they do not modify instance state.
Stackalloc in nested contexts: stackalloc expressions are now allowed in more expression contexts.
Alternative interpolated verbatim strings: @$"..." strings are recognized as interpolated verbatim strings just like $@"...".
Obsolete on property accessors: property accessors can now be individually marked as obsolete.
Permit t is null on unconstrained type parameter

[source] : https://github.com/dotnet/csharplang/blob/master/Language-Version-History.md

get current date with 'yyyy-MM-dd' format in Angular 4

app.component.html

<div>
     <h5 style="color:#ffffff;">{{myDate | date:'fullDate'}}</h5>
</div>

app.component.ts

export class AppComponent implements OnInit {
myDate = Date.now();    //date 

Send Mail to multiple Recipients in java

If you want to send as Cc using MimeMessageHelper

List<String> emails= new ArrayList();
email.add("email1");
email.add("email2");
for (String string : emails) {
message.addCc(string);
}

Same you can use to add multiple recipient.

"&" meaning after variable type

The & means that the function accepts the address (or reference) to a variable, instead of the value of the variable.

For example, note the difference between this:

void af(int& g)
{
    g++;
    cout<<g;
}

int main()
{
    int g = 123;
    cout << g;
    af(g);
    cout << g;
    return 0;
}

And this (without the &):

void af(int g)
{
    g++;
    cout<<g;
}

int main()
{
    int g = 123;
    cout << g;
    af(g);
    cout << g;
    return 0;
}

What does "#pragma comment" mean?

The answers and the documentation provided by MSDN is the best, but I would like to add one typical case that I use a lot which requires the use of #pragma comment to send a command to the linker at link time for example

#pragma comment(linker,"/ENTRY:Entry")

tell the linker to change the entry point form WinMain() to Entry() after that the CRTStartup going to transfer controll to Entry()

How to use Class<T> in Java?

It is confusing in the beginning. But it helps in the situations below :

class SomeAction implements Action {
}

// Later in the code.
Class<Action> actionClass = Class.forName("SomeAction"); 
Action action = actionClass.newInstance();
// Notice you get an Action instance, there was no need to cast.

How to stop a JavaScript for loop?

I know this is a bit old, but instead of looping through the array with a for loop, it would be much easier to use the method <array>.indexOf(<element>[, fromIndex])

It loops through an array, finding and returning the first index of a value. If the value is not contained in the array, it returns -1.

<array> is the array to look through, <element> is the value you are looking for, and [fromIndex] is the index to start from (defaults to 0).

I hope this helps reduce the size of your code!