Programs & Examples On #Isinrole

IsInRole is a method of the WindowsPrincipal class found in the System.Security.Principal namespace of Microsoft's .NET framework. It has several overloads and returns a boolean value that indicates if the principal object is member of a particular group.

How can prevent a PowerShell window from closing so I can see the error?

The simplest and easiest way is to execute your particular script with -NoExit param.

1.Open run box by pressing:

Win + R

2.Then type into input prompt:

PowerShell -NoExit "C:\folder\script.ps1"

and execute.

Powershell script does not run via Scheduled Tasks

Good morning,

I know this is an old thread but I just ran across it while looking for a similar problem - script was running successfully but not doing its work. I can't find the post that helped me but my issue was that I was running the script as the domain admin. When I followed the suggestion of the post and added the domain admin to the local administrator's group it worked. I hope this helps others with the same issue I had.

Joe

SQLite with encryption/password protection

You can get sqlite3.dll file with encryption support from http://system.data.sqlite.org/.

1 - Go to http://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki and download one of the packages. .NET version is irrelevant here.

2 - Extract SQLite.Interop.dll from package and rename it to sqlite3.dll. This DLL supports encryption via plaintext passwords or encryption keys.

The mentioned file is native and does NOT require .NET framework. It might need Visual C++ Runtime depending on the package you have downloaded.

UPDATE

This is the package that I've downloaded for 32-bit development: http://system.data.sqlite.org/blobs/1.0.94.0/sqlite-netFx40-static-binary-Win32-2010-1.0.94.0.zip

How to resolve Error : Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation

You 100% can do this on the server side...

     Protected Sub Button3_Click(sender As Object, e As System.EventArgs)
    MesgBox("Test")
End Sub

Private Sub MesgBox(ByVal sMessage As String)
    Dim msg As String
    msg = "<script language='javascript'>"
    msg += "alert('" & sMessage & "');"
    msg += "</script>"
    Response.Write(msg)
End Sub

here is actually a whole slew of ways to go about this http://www.sislands.com/coin70/week1/dialogbox.htm

How to get current SIM card number in Android?

Getting the Phone Number, IMEI, and SIM Card ID

TelephonyManager tm = (TelephonyManager) 
            getSystemService(Context.TELEPHONY_SERVICE);        

For SIM card, use the getSimSerialNumber()

    //---get the SIM card ID---
    String simID = tm.getSimSerialNumber();
    if (simID != null)
        Toast.makeText(this, "SIM card ID: " + simID, 
        Toast.LENGTH_LONG).show();

Phone number of your phone, use the getLine1Number() (some device's dont return the phone number)

    //---get the phone number---
    String telNumber = tm.getLine1Number();
    if (telNumber != null)        
        Toast.makeText(this, "Phone number: " + telNumber, 
        Toast.LENGTH_LONG).show();

IMEI number of the phone, use the getDeviceId()

    //---get the IMEI number---
    String IMEI = tm.getDeviceId();
    if (IMEI != null)        
        Toast.makeText(this, "IMEI number: " + IMEI, 
        Toast.LENGTH_LONG).show();

Permissions needed

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Creating a file only if it doesn't exist in Node.js

As your intuition correctly guessed, the naive solution with a pair of exists / writeFile calls is wrong. Asynchronous code runs in unpredictable ways. And in given case it is

  • Is there a file a.txt? — No.
  • (File a.txt gets created by another program)
  • Write to a.txt if it's possible. — Okay.

But yes, we can do that in a single call. We're working with file system so it's a good idea to read developer manual on fs. And hey, here's an interesting part.

'w' - Open file for writing. The file is created (if it does not exist) or truncated (if it exists).

'wx' - Like 'w' but fails if path exists.

So all we have to do is just add wx to the fs.open call. But hey, we don't like fopen-like IO. Let's read on fs.writeFile a bit more.

fs.readFile(filename[, options], callback)#

filename String

options Object

encoding String | Null default = null

flag String default = 'r'

callback Function

That options.flag looks promising. So we try

fs.writeFile(path, data, { flag: 'wx' }, function (err) {
    if (err) throw err;
    console.log("It's saved!");
});

And it works perfectly for a single write. I guess this code will fail in some more bizarre ways yet if you try to solve your task with it. You have an atomary "check for a_#.jpg existence, and write there if it's empty" operation, but all the other fs state is not locked, and a_1.jpg file may spontaneously disappear while you're already checking a_5.jpg. Most* file systems are no ACID databases, and the fact that you're able to do at least some atomic operations is miraculous. It's very likely that wx code won't work on some platform. So for the sake of your sanity, use database, finally.

Some more info for the suffering

Imagine we're writing something like memoize-fs that caches results of function calls to the file system to save us some network/cpu time. Could we open the file for reading if it exists, and for writing if it doesn't, all in the single call? Let's take a funny look on those flags. After a while of mental exercises we can see that a+ does what we want: if the file doesn't exist, it creates one and opens it both for reading and writing, and if the file exists it does so without clearing the file (as w+ would). But now we cannot use it neither in (smth)File, nor in create(Smth)Stream functions. And that seems like a missing feature.

So feel free to file it as a feature request (or even a bug) to Node.js github, as lack of atomic asynchronous file system API is a drawback of Node. Though don't expect changes any time soon.

Edit. I would like to link to articles by Linus and by Dan Luu on why exactly you don't want to do anything smart with your fs calls, because the claim was left mostly not based on anything.

Check if the file exists using VBA

Correction to fileExists from @UberNubIsTrue :

Function fileExists(s_directory As String, s_fileName As String) As Boolean

  Dim obj_fso As Object, obj_dir As Object, obj_file As Object
  Dim ret As Boolean
   Set obj_fso = CreateObject("Scripting.FileSystemObject")
   Set obj_dir = obj_fso.GetFolder(s_directory)
   ret = False
   For Each obj_file In obj_dir.Files
     If obj_fso.fileExists(s_directory & "\" & s_fileName) = True Then
        ret = True
        Exit For
      End If
   Next

   Set obj_fso = Nothing
   Set obj_dir = Nothing
   fileExists = ret

 End Function

EDIT: shortened version

' Check if a file exists
Function fileExists(s_directory As String, s_fileName As String) As Boolean

    Dim obj_fso As Object

    Set obj_fso = CreateObject("Scripting.FileSystemObject")
    fileExists = obj_fso.fileExists(s_directory & "\" & s_fileName)

End Function

"Object doesn't support property or method 'find'" in IE

I solved same issue by adding polyfill following:

<script src="https://cdn.polyfill.io/v3/polyfill.min.js?features=default,Array.prototype.includes,Array.prototype.find"></script>

A polyfill is a piece of code (usually JavaScript on the Web) used to provide modern functionality on older browsers that do not natively support it.

Hope someone find this helpful.

How to display pandas DataFrame of floats using a format string for columns?

You can also set locale to your region and set float_format to use a currency format. This will automatically set $ sign for currency in USA.

import locale

locale.setlocale(locale.LC_ALL, "en_US.UTF-8")

pd.set_option("float_format", locale.currency)

df = pd.DataFrame(
    [123.4567, 234.5678, 345.6789, 456.7890],
    index=["foo", "bar", "baz", "quux"],
    columns=["cost"],
)
print(df)

        cost
foo  $123.46
bar  $234.57
baz  $345.68
quux $456.79

Programmatically check Play Store for app updates

enter image description here

Google has introduced in-app updates API

The API currently supports two flows:

  • The “immediate” flow is a full-screen user experience that guides the user from download to update before they can use your app.
  • The “flexible flow” allows users to download the update while continuing to use your app.

variable or field declared void

It for example happens in this case here:

void initializeJSP(unknownType Experiment);

Try using std::string instead of just string (and include the <string> header). C++ Standard library classes are within the namespace std::.

what is the use of $this->uri->segment(3) in codeigniter pagination

This provides you to retrieve information from your URI strings

$this->uri->segment(n); // n=1 for controller, n=2 for method, etc

Consider this example:

http://example.com/index.php/controller/action/1stsegment/2ndsegment

it will return

$this->uri->segment(1); // controller
$this->uri->segment(2); // action
$this->uri->segment(3); // 1stsegment
$this->uri->segment(4); // 2ndsegment

Modify tick label text

One can also do this with pylab and xticks

import matplotlib
import matplotlib.pyplot as plt
x = [0,1,2]
y = [90,40,65]
labels = ['high', 'low', 37337]
plt.plot(x,y, 'r')
plt.xticks(x, labels, rotation='vertical')
plt.show()

http://matplotlib.org/examples/ticks_and_spines/ticklabels_demo_rotation.html

How to write data to a JSON file using Javascript

You have to be clear on what you mean by "JSON".

Some people use the term JSON incorrectly to refer to a plain old JavaScript object, such as [{a: 1}]. This one happens to be an array. If you want to add a new element to the array, just push it, as in

var arr = [{a: 1}];
arr.push({b: 2});

< [{a: 1}, {b: 2}]

The word JSON may also be used to refer to a string which is encoded in JSON format:

var json = '[{"a": 1}]';

Note the (single) quotation marks indicating that this is a string. If you have such a string that you obtained from somewhere, you need to first parse it into a JavaScript object, using JSON.parse:

var obj = JSON.parse(json);

Now you can manipulate the object any way you want, including push as shown above. If you then want to put it back into a JSON string, then you use JSON.stringify:

var new_json = JSON.stringify(obj.push({b: 2}));
'[{"a": 1}, {"b": 1}]'

JSON is also used as a common way to format data for transmission of data to and from a server, where it can be saved (persisted). This is where ajax comes in. Ajax is used both to obtain data, often in JSON format, from a server, and/or to send data in JSON format up to to the server. If you received a response from an ajax request which is JSON format, you may need to JSON.parse it as described above. Then you can manipulate the object, put it back into JSON format with JSON.stringify, and use another ajax call to send the data to the server for storage or other manipulation.

You use the term "JSON file". Normally, the word "file" is used to refer to a physical file on some device (not a string you are dealing with in your code, or a JavaScript object). The browser has no access to physical files on your machine. It cannot read or write them. Actually, the browser does not even really have the notion of a "file". Thus, you cannot just read or write some JSON file on your local machine. If you are sending JSON to and from a server, then of course, the server might be storing the JSON as a file, but more likely the server would be constructing the JSON based on some ajax request, based on data it retrieves from a database, or decoding the JSON in some ajax request, and then storing the relevant data back into its database.

Do you really have a "JSON file", and if so, where does it exist and where did you get it from? Do you have a JSON-format string, that you need to parse, mainpulate, and turn back into a new JSON-format string? Do you need to get JSON from the server, and modify it and then send it back to the server? Or is your "JSON file" actually just a JavaScript object, that you simply need to manipulate with normal JavaScript logic?

Printing Lists as Tabular Data

Python actually makes this quite easy.

Something like

for i in range(10):
    print '%-12i%-12i' % (10 ** i, 20 ** i)

will have the output

1           1           
10          20          
100         400         
1000        8000        
10000       160000      
100000      3200000     
1000000     64000000    
10000000    1280000000  
100000000   25600000000
1000000000  512000000000

The % within the string is essentially an escape character and the characters following it tell python what kind of format the data should have. The % outside and after the string is telling python that you intend to use the previous string as the format string and that the following data should be put into the format specified.

In this case I used "%-12i" twice. To break down each part:

'-' (left align)
'12' (how much space to be given to this part of the output)
'i' (we are printing an integer)

From the docs: https://docs.python.org/2/library/stdtypes.html#string-formatting

Convert string in base64 to image and save on filesystem in Python

You can use Pillow.

pip install Pillow



image = base64.b64decode(str(base64String))       
fileName = 'test.jpeg'

imagePath = FILE_UPLOAD_DIR + fileName

img = Image.open(io.BytesIO(image))
img.save(imagePath, 'jpeg')
return fileName

reference for complete source code: https://abhisheksharma.online/convert-base64-blob-to-image-file-in-python/

Prevent flex items from stretching

You don't want to stretch the span in height?
You have the possiblity to affect one or more flex-items to don't stretch the full height of the container.

To affect all flex-items of the container, choose this:
You have to set align-items: flex-start; to div and all flex-items of this container get the height of their content.

_x000D_
_x000D_
div {_x000D_
  align-items: flex-start;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}
_x000D_
<div>_x000D_
  <span>This is some text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

To affect only a single flex-item, choose this:
If you want to unstretch a single flex-item on the container, you have to set align-self: flex-start; to this flex-item. All other flex-items of the container aren't affected.

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
  background: tan;_x000D_
}_x000D_
span.only {_x000D_
  background: red;_x000D_
  align-self:flex-start;_x000D_
}_x000D_
span {_x000D_
    background:green;_x000D_
}
_x000D_
<div>_x000D_
  <span class="only">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why is this happening to the span?
The default value of the property align-items is stretch. This is the reason why the span fill the height of the div.

Difference between baseline and flex-start?
If you have some text on the flex-items, with different font-sizes, you can use the baseline of the first line to place the flex-item vertically. A flex-item with a smaller font-size have some space between the container and itself at top. With flex-start the flex-item will be set to the top of the container (without space).

_x000D_
_x000D_
div {_x000D_
  align-items: baseline;_x000D_
  background: tan;_x000D_
  display: flex;_x000D_
  height: 200px;_x000D_
}_x000D_
span {_x000D_
  background: red;_x000D_
}_x000D_
span.fontsize {_x000D_
  font-size:2em;_x000D_
}
_x000D_
<div>_x000D_
  <span class="fontsize">This is some text.</span>_x000D_
  <span>This is more text.</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can find more information about the difference between baseline and flex-start here:
What's the difference between flex-start and baseline?

Integer.valueOf() vs. Integer.parseInt()

First Question: Difference between parseInt and valueOf in java?

Second Question:

NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse("1,234");
double d = number.doubleValue();

Third Question:

DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
symbols.setGroupingSeparator(',');
df.setDecimalFormatSymbols(symbols);
df.parse(p);

Subtract minute from DateTime in SQL Server 2005

Use DATEPART to pull apart your interval, and DATEADD to subtract the parts:

select dateadd(
     hh,
    -1 * datepart(hh, cast('1:15' as datetime)),
    dateadd(
        mi,
        -1 * datepart(mi, cast('1:15' as datetime)),
        '2000-01-01 08:30:00'))

or, we can convert to minutes first (though OP would prefer not to):

declare @mins int
select @mins = datepart(mi, cast('1:15' as datetime)) + 60 * datepart(hh, cast('1:15' as datetime)) 
select dateadd(mi, -1 * @mins, '2000-01-01 08:30:00')

The difference between the Runnable and Callable interfaces in Java

As it was already mentioned here Callable is relatively new interface and it was introduced as a part of concurrency package. Both Callable and Runnable can be used with executors. Class Thread (that implements Runnable itself) supports Runnable only.

You can still use Runnable with executors. The advantage of Callable that you can send it to executor and immediately get back Future result that will be updated when the execution is finished. The same may be implemented with Runnable, but in this case you have to manage the results yourself. For example you can create results queue that will hold all results. Other thread can wait on this queue and deal with results that arrive.

How do you set the EditText keyboard to only consist of numbers on Android?

For the EditText if we specify,

android:inputType="number"

only numbers can be got. But if you use,

android:inputType="phone"

along with the numbers it can accept special characters like ;,/". etc.

Python Error: unsupported operand type(s) for +: 'int' and 'NoneType'

In your giant elif chain, you skipped 13. You might want to throw an error if you hit the end of the chain without returning anything, to catch numbers you missed and incorrect calls of the function:

...
elif x == 90:
    return 6
else:
    raise ValueError(x)

Why doesn't CSS ellipsis work in table cell?

Apparently, adding:

td {
  display: block; /* or inline-block */
}

solves the problem as well.


Another possible solution is to set table-layout: fixed; for the table, and also set it's width. For example: http://jsfiddle.net/fd3Zx/5/

Submit a form in a popup, and then close the popup

Here's how I ended up doing this:

        <div id="divform">
            <form action="/system/wpacert" method="post" enctype="multipart/form-data" name="certform">
                <div>Certificate 1: <input type="file" name="cert1"/></div>
                <div>Certificate 2: <input type="file" name="cert2"/></div>

                <div><input type="button" value="Upload" onclick="closeSelf();"/></div>
            </form>
        </div>
        <div  id="closelink" style="display:none">
            <a href="javascript:window.close()">Click Here to Close this Page</a>
        </div>

function closeSelf(){
    document.forms['certform'].submit();
    hide(document.getElementById('divform'));
    unHide(document.getElementById('closelink'));

}

Where hide() and unhide() set the style.display to 'none' and 'block' respectively.

Not exactly what I had in mind, but this will have to do for the time being. Works on IE, Safari, FF and Chrome.

Perl: function to trim string leading and trailing whitespace

One option is Text::Trim:

use Text::Trim;
print trim("  example  ");

SyntaxError: import declarations may only appear at top level of a module

I got this on Firefox (FF58). I fixed this with:

  1. It is still experimental on Firefox (from v54): You have to set to true the variable dom.moduleScripts.enabled in about:config

Source: Import page on mozilla (See Browser compatibility)

  1. Add type="module" to your script tag where you import the js file

<script type="module" src="appthatimports.js"></script>

  1. Import files have to be prefixed (./, /, ../ or http:// before)

import * from "./mylib.js"

For more examples, this blog post is good.

How to create loading dialogs in Android?

It's a ProgressDialog, with setIndeterminate(true).

From http://developer.android.com/guide/topics/ui/dialogs.html#ProgressDialog

ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "", 
                    "Loading. Please wait...", true);

An indeterminate progress bar doesn't actually show a bar, it shows a spinning activity circle thing. I'm sure you know what I mean :)

Is there a Subversion command to reset the working copy?

To revert tracked files

svn revert . -R

To clean untracked files

svn status | rm -rf $(awk '/^?/{$1 = ""; print $0}')

The -rf may/should look scary at first, but once understood it will not be for these reasons:

  1. Only wholly-untracked directories will match the pattern passed to rm
  2. The -rf is required, else these directories will not be removed

To revert then clean (the OP question)

svn revert . -R && svn status | rm -rf $(awk '/^?/{$1 = ""; print $0}')

For consistent ease of use

Add permanent alias to your .bash_aliases

alias svn.HardReset='read -p "destroy all local changes?[y/N]" && [[ $REPLY =~ ^[yY] ]] && svn revert . -R && rm -rf $(awk -f <(echo "/^?/{print \$2}") <(svn status) ;)'

Purpose of a constructor in Java?

Constructor will be helpful to prevent instances getting unreal values. For an example set a Person class with height , weight. There can't be a Person with 0m and 0kg

How do you sort an array on multiple columns?

I suggest to use a built in comparer and chain the wanted sort order with logical or ||.

function customSort(a, b) {
    return a[3].localeCompare(b[3]) || a[1].localeCompare(b[1]);
}

Working example:

_x000D_
_x000D_
var array = [_x000D_
    [0, 'Aluminium', 0, 'Francis'],_x000D_
    [1, 'Argon', 1, 'Ada'],_x000D_
    [2, 'Brom', 2, 'John'],_x000D_
    [3, 'Cadmium', 3, 'Marie'],_x000D_
    [4, 'Fluor', 3, 'Marie'],_x000D_
    [5, 'Gold', 1, 'Ada'],_x000D_
    [6, 'Kupfer', 4, 'Ines'],_x000D_
    [7, 'Krypton', 4, 'Joe'],_x000D_
    [8, 'Sauerstoff', 3, 'Marie'],_x000D_
    [9, 'Zink', 5, 'Max']_x000D_
];_x000D_
_x000D_
array.sort(function (a, b) {_x000D_
    return a[3].localeCompare(b[3]) || a[1].localeCompare(b[1]);_x000D_
});_x000D_
_x000D_
document.write('<pre>');_x000D_
array.forEach(function (a) {_x000D_
    document.write(JSON.stringify(a) + '<br>');_x000D_
});
_x000D_
_x000D_
_x000D_

Search and replace a line in a file in Python

If you're wanting a generic function that replaces any text with some other text, this is likely the best way to go, particularly if you're a fan of regex's:

import re
def replace( filePath, text, subs, flags=0 ):
    with open( filePath, "r+" ) as file:
        fileContents = file.read()
        textPattern = re.compile( re.escape( text ), flags )
        fileContents = textPattern.sub( subs, fileContents )
        file.seek( 0 )
        file.truncate()
        file.write( fileContents )

PHP: If internet explorer 6, 7, 8 , or 9

You can as well look into PHP's get_browser(); http://php.net/manual/en/function.get-browser.php

Maybe you'll find it useful for more features.

Checking for a null object in C++

A C++ reference is not a pointer nor a Java/C# style reference and cannot be NULL. They behave as if they were an alias to another existing object.

In some cases, if there are bugs in your code, you might get a reference into an already dead or non-existent object, but the best thing you can do is hope that the program dies soon enough to be able to debug what happened and why your program got corrupted.

That is, I have seen code checking for 'null references' doing something like: if ( &reference == 0 ), but the standard is clear that there cannot be null references in a well-formed program. If a reference is bound to a null object the program is ill-formed and should be corrected. If you need optional values, use pointers (or some higher level construct like boost::optional), not references.

How to use sed/grep to extract text between two words?

Problem. My stored Claws Mail messages are wrapped as follows, and I am trying to extract the Subject lines:

Subject: [SLC38A9 lysosomal arginine sensor; mTORC1 pathway] Key molecular
 link in major cell growth pathway: Findings point to new potential
 therapeutic target in pancreatic cancer [mTORC1 Activator SLC38A9 Is
 Required to Efflux Essential Amino Acids from Lysosomes and Use Protein as
 a Nutrient] [Re: Nutrient sensor in key growth-regulating metabolic pathway
 identified [Lysosomal amino acid transporter SLC38A9 signals arginine
 sufficiency to mTORC1]]
Message-ID: <[email protected]>

Per A2 in this thread, How to use sed/grep to extract text between two words? the first expression, below, "works" as long as the matched text does not contain a newline:

grep -o -P '(?<=Subject: ).*(?=molecular)' corpus/01

[SLC38A9 lysosomal arginine sensor; mTORC1 pathway] Key

However, despite trying numerous variants (.+?; /s; ...), I could not get these to work:

grep -o -P '(?<=Subject: ).*(?=link)' corpus/01
grep -o -P '(?<=Subject: ).*(?=therapeutic)' corpus/01
etc.

Solution 1.

Per Extract text between two strings on different lines

sed -n '/Subject: /{:a;N;/Message-ID:/!ba; s/\n/ /g; s/\s\s*/ /g; s/.*Subject: \|Message-ID:.*//g;p}' corpus/01

which gives

[SLC38A9 lysosomal arginine sensor; mTORC1 pathway] Key molecular link in major cell growth pathway: Findings point to new potential therapeutic target in pancreatic cancer [mTORC1 Activator SLC38A9 Is Required to Efflux Essential Amino Acids from Lysosomes and Use Protein as a Nutrient] [Re: Nutrient sensor in key growth-regulating metabolic pathway identified [Lysosomal amino acid transporter SLC38A9 signals arginine sufficiency to mTORC1]]                              

Solution 2.*

Per How can I replace a newline (\n) using sed?

sed ':a;N;$!ba;s/\n/ /g' corpus/01

will replace newlines with a space.

Chaining that with A2 in How to use sed/grep to extract text between two words?, we get:

sed ':a;N;$!ba;s/\n/ /g' corpus/01 | grep -o -P '(?<=Subject: ).*(?=Message-ID:)'

which gives

[SLC38A9 lysosomal arginine sensor; mTORC1 pathway] Key molecular  link in major cell growth pathway: Findings point to new potential  therapeutic target in pancreatic cancer [mTORC1 Activator SLC38A9 Is  Required to Efflux Essential Amino Acids from Lysosomes and Use Protein as  a Nutrient] [Re: Nutrient sensor in key growth-regulating metabolic pathway  identified [Lysosomal amino acid transporter SLC38A9 signals arginine  sufficiency to mTORC1]] 

This variant removes double spaces:

sed ':a;N;$!ba;s/\n/ /g; s/\s\s*/ /g' corpus/01 | grep -o -P '(?<=Subject: ).*(?=Message-ID:)'

giving

[SLC38A9 lysosomal arginine sensor; mTORC1 pathway] Key molecular link in major cell growth pathway: Findings point to new potential therapeutic target in pancreatic cancer [mTORC1 Activator SLC38A9 Is Required to Efflux Essential Amino Acids from Lysosomes and Use Protein as a Nutrient] [Re: Nutrient sensor in key growth-regulating metabolic pathway identified [Lysosomal amino acid transporter SLC38A9 signals arginine sufficiency to mTORC1]]

How to hide a TemplateField column in a GridView

Am I missing something ?

If you can't set visibility on TemplateField then set it on its content

<asp:TemplateField>
  <ItemTemplate>
    <asp:LinkButton Visible='<%# MyBoolProperty %>' ID="foo" runat="server" ... />
  </ItemTemplate>
</asp:TemplateField> 

or if your content is complex then enclose it into a div and set visibility on the div

<asp:TemplateField>
  <ItemTemplate>
    <div runat="server" visible='<%# MyBoolProperty  %>' >
      <asp:LinkButton ID="attachmentButton" runat="server" ... />
    </div>
  </ItemTemplate>
</asp:TemplateField> 

Make JQuery UI Dialog automatically grow or shrink to fit its contents

This works with jQuery UI v1.10.3

$("selector").dialog({height:'auto', width:'auto'});

Multiple select statements in Single query

select RTRIM(A.FIELD) from SCHEMA.TABLE A where RTRIM(A.FIELD) =  ('10544175A') 
 UNION  
select RTRIM(A.FIELD) from SCHEMA.TABLE A where RTRIM(A.FIELD) = ('10328189B') 
 UNION  
select RTRIM(A.FIELD) from SCHEMA.TABLE A where RTRIM(A.FIELD) = ('103498732H')

How do I use the built in password reset/change views with my own templates

You can do the following:

  1. add to your urlpatterns (r'^/accounts/password/reset/$', password_reset)
  2. put your template in '/templates/registration/password_reset_form.html'
  3. make your app come before 'django.contrib.auth' in INSTALLED_APPS

Explanation:

When the templates are loaded, they are searched in your INSTALLED_APPS variable in settings.py . The order is dictated by the definition's rank in INSTALLED_APPS, so since your app come before 'django.contrib.auth' your template were loaded (reference: https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.loaders.app_directories.Loader).

Motivation of approach:

  1. I want be more dry and don't repeat for any view(defined by django) the template name (they are already defined in django)
  2. I want a smallest url.py

Virtual Memory Usage from Java under Linux, too much memory used

Sun's java 1.4 has the following arguments to control memory size:

-Xmsn Specify the initial size, in bytes, of the memory allocation pool. This value must be a multiple of 1024 greater than 1MB. Append the letter k or K to indicate kilobytes, or m or M to indicate megabytes. The default value is 2MB. Examples:

           -Xms6291456
           -Xms6144k
           -Xms6m

-Xmxn Specify the maximum size, in bytes, of the memory allocation pool. This value must a multiple of 1024 greater than 2MB. Append the letter k or K to indicate kilobytes, or m or M to indicate megabytes. The default value is 64MB. Examples:

           -Xmx83886080
           -Xmx81920k
           -Xmx80m

http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/java.html

Java 5 and 6 have some more. See http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp

How to add a new column to an existing sheet and name it?

Use insert method from range, for example

Sub InsertColumn()
        Columns("C:C").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
        Range("C1").Value = "Loc"
End Sub

Pass user defined environment variable to tomcat

You can use setenv.bat or .sh to pass the environment variables to the Tomcat.

Create CATALINA_BASE/bin/setenv.bat or .sh file and put the following line in it, and then start the Tomcat.

On Windows:

set APP_MASTER_PASSWORD=foo

On Unix like systems:

export APP_MASTER_PASSWORD=foo

How to convert a String to a Date using SimpleDateFormat?

Very Simple Example is.

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
                Date date = new Date();
                Date date1 = new Date();
            try {
                System.out.println("Date1:   "+date1);
                System.out.println("date" + date);

                date = simpleDateFormat.parse("01-01-2013");
                date1 = simpleDateFormat.parse("06-15-2013");

                System.out.println("Date1 is:"+date1);
                System.out.println("date" + date);

            } catch (Exception e) {
                System.out.println(e.getMessage());
            }

best way to create object

Really depends on your requirement, although lately I have seen a trend for classes with at least one bare constructor defined.

The upside of posting your parameters in via constructor is that you know those values can be relied on after instantiation. The downside is that you'll need to put more work in with any library that expects to be able to create objects with a bare constructor.

My personal preference is to go with a bare constructor and set any properties as part of the declaration.

Person p=new Person()
{
   Name = "Han Solo",
   Age = 39
};

This gets around the "class lacks bare constructor" problem, plus reduces maintenance ( I can set more things without changing the constructor ).

Is __init__.py not required for packages in Python 3.3+

Overview

@Mike's answer is correct but too imprecise. It is true that Python 3.3+ supports Implicit Namespace Packages that allows it to create a package without an __init__.py file. This is called a namespace package in contrast to a regular package which does have an __init__.py file (empty or not empty).

However, creating a namespace package should ONLY be done if there is a need for it. For most use cases and developers out there, this doesn't apply so you should stick with EMPTY __init__.py files regardless.

Namespace package use case

To demonstrate the difference between the two types of python packages, lets look at the following example:

google_pubsub/              <- Package 1
    google/                 <- Namespace package (there is no __init__.py)
        cloud/              <- Namespace package (there is no __init__.py)
            pubsub/         <- Regular package (with __init__.py)
                __init__.py <- Required to make the package a regular package
                foo.py

google_storage/             <- Package 2
    google/                 <- Namespace package (there is no __init__.py)
        cloud/              <- Namespace package (there is no __init__.py)
            storage/        <- Regular package (with __init__.py)
                __init__.py <- Required to make the package a regular package
                bar.py

google_pubsub and google_storage are separate packages but they share the same namespace google/cloud. In order to share the same namespace, it is required to make each directory of the common path a namespace package, i.e. google/ and cloud/. This should be the only use case for creating namespace packages, otherwise, there is no need for it.

It's crucial that there are no __init__py files in the google and google/cloud directories so that both directories can be interpreted as namespace packages. In Python 3.3+ any directory on the sys.path with a name that matches the package name being looked for will be recognized as contributing modules and subpackages to that package. As a result, when you import both from google_pubsub and google_storage, the Python interpreter will be able to find them.

This is different from regular packages which are self-contained meaning all parts live in the same directory hierarchy. When importing a package and the Python interpreter encounters a subdirectory on the sys.path with an __init__.py file, then it will create a single directory package containing only modules from that directory, rather than finding all appropriately named subdirectories outside that directory. This is perfectly fine for packages that don't want to share a namespace. I highly recommend taking a look at Traps for the Unwary in Python’s Import System to get a better understanding of how Python importing behaves with regular and namespace package and what __init__.py traps to watch out for.

Summary

  • Only skip __init__.py files if you want to create namespace packages. Only create namespace packages if you have different libraries that reside in different locations and you want them each to contribute a subpackage to the parent package, i.e. the namespace package.
  • Keep on adding empty __init__py to your directories because 99% of the time you just want to create regular packages. Also, Python tools out there such as mypy and pytest require empty __init__.py files to interpret the code structure accordingly. This can lead to weird errors if not done with care.

Resources

My answer only touches the surface of how regular packages and namespace packages work so take a look at the following resources for further information:

Parsing CSV files in C#, with header

This solution is using the official Microsoft.VisualBasic assembly to parse CSV.

Advantages:

  • delimiter escaping
  • ignores Header
  • trim spaces
  • ignore comments

Code:

    using Microsoft.VisualBasic.FileIO;

    public static List<List<string>> ParseCSV (string csv)
    {
        List<List<string>> result = new List<List<string>>();


        // To use the TextFieldParser a reference to the Microsoft.VisualBasic assembly has to be added to the project. 
        using (TextFieldParser parser = new TextFieldParser(new StringReader(csv))) 
        {
            parser.CommentTokens = new string[] { "#" };
            parser.SetDelimiters(new string[] { ";" });
            parser.HasFieldsEnclosedInQuotes = true;

            // Skip over header line.
            //parser.ReadLine();

            while (!parser.EndOfData)
            {
                var values = new List<string>();

                var readFields = parser.ReadFields();
                if (readFields != null)
                    values.AddRange(readFields);
                result.Add(values);
            }
        }

        return result;
    }

What is the difference between precision and scale?

Precision is the total number of digits, can be between 1 and 38.
Scale is the number of digits after the decimal point, may also be set as negative for rounding.

Example:
NUMBER(7,5): 12.12345
NUMBER(5,0): 12345

More details on the ORACLE website:
https://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT1832

Sorting A ListView By Column

Use the ListView.SortExpression.

When multiple columns are sorted, this property contains a comma-separated list of the fields to sort by.

Python: List vs Dict for look up table

As a new set of tests to show @EriF89 is still right after all these years:

$ python -m timeit -s "l={k:k for k in xrange(5000)}"    "[i for i in xrange(10000) if i in l]"
1000 loops, best of 3: 1.84 msec per loop
$ python -m timeit -s "l=[k for k in xrange(5000)]"    "[i for i in xrange(10000) if i in l]"
10 loops, best of 3: 573 msec per loop
$ python -m timeit -s "l=tuple([k for k in xrange(5000)])"    "[i for i in xrange(10000) if i in l]"
10 loops, best of 3: 587 msec per loop
$ python -m timeit -s "l=set([k for k in xrange(5000)])"    "[i for i in xrange(10000) if i in l]"
1000 loops, best of 3: 1.88 msec per loop

Here we also compare a tuple, which are known to be faster than lists (and use less memory) in some use cases. In the case of lookup table, the tuple faired no better .

Both the dict and set performed very well. This brings up an interesting point tying into @SilentGhost answer about uniqueness: if the OP has 10M values in a data set, and it's unknown if there are duplicates in them, then it would be worth keeping a set/dict of its elements in parallel with the actual data set, and testing for existence in that set/dict. It's possible the 10M data points only have 10 unique values, which is a much smaller space to search!

SilentGhost's mistake about dicts is actually illuminating because one could use a dict to correlate duplicated data (in values) into a nonduplicated set (keys), and thus keep one data object to hold all data, yet still be fast as a lookup table. For example, a dict key could be the value being looked up, and the value could be a list of indices in an imaginary list where that value occurred.

For example, if the source data list to be searched was l=[1,2,3,1,2,1,4], it could be optimized for both searching and memory by replacing it with this dict:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> l=[1,2,3,1,2,1,4]
>>> for i, e in enumerate(l):
...     d[e].append(i)
>>> d
defaultdict(<class 'list'>, {1: [0, 3, 5], 2: [1, 4], 3: [2], 4: [6]})

With this dict, one can know:

  1. If a value was in the original dataset (ie 2 in d returns True)
  2. Where the value was in the original dataset (ie d[2] returns list of indices where data was found in original data list: [1, 4])

Run .jar from batch-file

My understanding of the question is that the OP is trying to avoid specifying a class-path in his command line. You can do this by putting the class-path in the Manifest file.

In the manifest:

Class-Path: Library.jar

This document gives more details:

http://docs.oracle.com/javase/tutorial/deployment/jar/downman.html

To create a jar using the a manifest file named MANIFEST, you can use the following command:

jar -cmf MANIFEST MyJar.jar <class files>

If you specify relative class-paths (ie, other jars in the same directory), then you can move the jar's around and the batch file mentioned in mdm's answer will still work.

How do I align spans or divs horizontally?

What you might like to do is look up CSS grid based layouts. This layout method involves specifying some CSS classes to align the page contents to a grid structure. It's more closely related to print-bsed layout than web-based, but it's a technique used on a lot of websites to layout the content into a structure without having to resort to tables.

Try this for starters from Smashing Magazine.

Convert a positive number to negative in C#

X=*-1 may not work on all compilers... since it reads a 'multiply' 'SUBTRACT' 1 instead of NEGATIVE The better alt is X=(0-X), [WHICH IS DIFF FROM X-=X]

How comment a JSP expression?

your <%= //map.size() %> doesnt simply work because it should have been

<% //= map.size() %>

Jquery Date picker Default Date

Use the defaultDate option

$( ".selector" ).datepicker({ defaultDate: '01/01/01' });

If you change your date format, make sure to change the input into defaultDate (e.g. '01-01-2001')

Getting the last element of a split string array

And if you don't want to construct an array ...

var str = "how,are you doing, today?";
var res = str.replace(/(.*)([, ])([^, ]*$)/,"$3");

The breakdown in english is:

/(anything)(any separator once)(anything that isn't a separator 0 or more times)/

The replace just says replace the entire string with the stuff after the last separator.

So you can see how this can be applied generally. Note the original string is not modified.

Secure random token in Node.js

Simple function that gets you a token that is URL safe and has base64 encoding! It's a combination of 2 answers from above.

const randomToken = () => {
    crypto.randomBytes(64).toString('base64').replace(/\//g,'_').replace(/\+/g,'-');
}

In Bash, how can I check if a string begins with some value?

if [ [[ $HOST == user1 ]] -o [[ $HOST == node* ]] ];
then
echo yes
fi

doesn't work, because all of [, [[, and test recognize the same nonrecursive grammar. See section CONDITIONAL EXPRESSIONS on your Bash man page.

As an aside, the SUSv3 says

The KornShell-derived conditional command (double bracket [[]]) was removed from the shell command language description in an early proposal. Objections were raised that the real problem is misuse of the test command ([), and putting it into the shell is the wrong way to fix the problem. Instead, proper documentation and a new shell reserved word (!) are sufficient.

Tests that require multiple test operations can be done at the shell level using individual invocations of the test command and shell logicals, rather than using the error-prone -o flag of test.

You'd need to write it this way, but test doesn't support it:

if [ $HOST == user1 -o $HOST == node* ];
then
echo yes
fi

test uses = for string equality, and more importantly it doesn't support pattern matching.

case / esac has good support for pattern matching:

case $HOST in
user1|node*) echo yes ;;
esac

It has the added benefit that it doesn't depend on Bash, and the syntax is portable. From the Single Unix Specification, The Shell Command Language:

case word in
    [(]pattern1) compound-list;;
    [[(]pattern[ | pattern] ... ) compound-list;;] ...
    [[(]pattern[ | pattern] ... ) compound-list]
esac

JavaScript alert not working in Android WebView

if you wish to hide URL from the user, Show an AlertDialog as below.

myWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                Log.d(TAG, "onJsAlert url: " + url + "; message: " + message);
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        mContext);
                builder.setMessage(message)
                        .setNeutralButton("OK", new OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int arg1) {
                                dialog.dismiss();
                            }
                        }).show();
                result.cancel();
                return true;
            }
    }

Combining multiple condition in single case statement in Sql Server

You can put the condition after the WHEN clause, like so:

SELECT
  CASE
    WHEN PAT_ENT.SCR_DT is not null and PAT_ENTRY.ELIGIBILITY is null THEN 'Favor'
    WHEN PAT_ENT.SCR_DT is not null and PAT_ENTRY.EL = 'No' THEN 'Error'
    WHEN PAT_ENTRY.EL = 'Yes' and ISNULL(DS.DES, 'OFF') = 'OFF' THEN 'Active'
    WHEN DS.DES = 'N' THEN 'Early Term'
    WHEN DS.DES = 'Y' THEN 'Complete'
  END
FROM
  ....

Of course, the argument could be made that complex rules like this belong in your business logic layer, not in a stored procedure in the database...

Firebase TIMESTAMP to date and Time

Firebase.ServerValue.TIMESTAMP is not actual timestamp it is constant that will be replaced with actual value in server if you have it set into some variable.

mySessionRef.update({ startedAt: Firebase.ServerValue.TIMESTAMP });
mySessionRef.on('value', function(snapshot){ console.log(snapshot.val()) })
//{startedAt: 1452508763895}

if you want to get server time then you can use following code

  fb.ref("/.info/serverTimeOffset").on('value', function(offset) {
    var offsetVal = offset.val() || 0;
    var serverTime = Date.now() + offsetVal;
  });

Ternary operators in JavaScript without an "else"

In your case i see the ternary operator as redundant. You could assign the variable directly to the expression, using ||, && operators.

!defaults.slideshowWidth ? defaults.slideshowWidth = obj.find('img').width()+'px' : null ;

will become :

defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px';

It's more clear, it's more "javascript" style.

How to get the concrete class name as a string?

you can also create a dict with the classes themselves as keys, not necessarily the classnames

typefunc={
    int:lambda x: x*2,
    str:lambda s:'(*(%s)*)'%s
}

def transform (param):
    print typefunc[type(param)](param)

transform (1)
>>> 2
transform ("hi")
>>> (*(hi)*)

here typefunc is a dict that maps a function for each type. transform gets that function and applies it to the parameter.

of course, it would be much better to use 'real' OOP

Gunicorn worker timeout error

You need to used an other worker type class an async one like gevent or tornado see this for more explanation : First explantion :

You may also want to install Eventlet or Gevent if you expect that your application code may need to pause for extended periods of time during request processing

Second one :

The default synchronous workers assume that your application is resource bound in terms of CPU and network bandwidth. Generally this means that your application shouldn’t do anything that takes an undefined amount of time. For instance, a request to the internet meets this criteria. At some point the external network will fail in such a way that clients will pile up on your servers.

Can you disable tabs in Bootstrap?

None of the answers work for me. Remove data-toggle="tab" from the a prevents the tab from activating, but it also adds the #tabId hash to the URL. That is unacceptable to me. What is also unacceptable is using javascript.

What does work is added the disabled class to the li and removing the href attribute of its containing a.

asterisk : Unable to connect to remote asterisk (does /var/run/asterisk.ctl exist?)

If you have SELINUX enabled, it will prevent this file being created. You need to turn it off.

  1. vi /etc/selinux/config
  2. set SELINUX=disabled
  3. reboot

Format string to a 3 digit number

Does it have to be String.Format?

This looks like a job for String.Padleft

myString=myString.PadLeft(3, '0');

Or, if you are converting direct from an int:

myInt.toString("D3");

Swift apply .uppercaseString to only the first letter of a string

Capitalize the first character in the string

extension String {
    var capitalizeFirst: String {
        if self.characters.count == 0 {
            return self

        return String(self[self.startIndex]).capitalized + String(self.characters.dropFirst())
    }
}

SQL Server : converting varchar to INT

This is more for someone Searching for a result, than the original post-er. This worked for me...

declare @value varchar(max) = 'sad';
select sum(cast(iif(isnumeric(@value) = 1, @value, 0) as bigint));

returns 0

declare @value varchar(max) = '3';
select sum(cast(iif(isnumeric(@value) = 1, @value, 0) as bigint));

returns 3

how to install python distutils

I know this is an old question, but I just come across the same issue using Python 3.6 in Ubuntu, and I am able to solve it using the following command:

sudo apt-get install python3-distutils

"The certificate chain was issued by an authority that is not trusted" when connecting DB in VM Role from Azure website

You likely don't have a CA signed certificate installed in your SQL VM's trusted root store.

If you have Encrypt=True in the connection string, either set that to off (not recommended), or add the following in the connection string:

TrustServerCertificate=True

SQL Server will create a self-signed certificate if you don't install one for it to use, but it won't be trusted by the caller since it's not CA-signed, unless you tell the connection string to trust any server cert by default.

Long term, I'd recommend leveraging Let's Encrypt to get a CA signed certificate from a known trusted CA for free, and install it on the VM. Don't forget to set it up to automatically refresh. You can read more on this topic in SQL Server books online under the topic of "Encryption Hierarchy", and "Using Encryption Without Validation".

Spring JDBC Template for calling Stored Procedures

There are a number of ways to call stored procedures in Spring.

If you use CallableStatementCreator to declare parameters, you will be using Java's standard interface of CallableStatement, i.e register out parameters and set them separately. Using SqlParameter abstraction will make your code cleaner.

I recommend you looking at SimpleJdbcCall. It may be used like this:

SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
    .withSchemaName(schema)
    .withCatalogName(package)
    .withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);

For simple procedures you may use jdbcTemplate's update method:

jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);

Importing xsd into wsdl

You have a couple of problems here.

First, the XSD has an issue where an element is both named or referenced; in your case should be referenced.

Change:

<xsd:element name="stock" ref="Stock" minOccurs="1" maxOccurs="unbounded"/> 

To:

<xsd:element name="stock" type="Stock" minOccurs="1" maxOccurs="unbounded"/> 

And:

  • Remove the declaration of the global element Stock
  • Create a complex type declaration for a type named Stock

So:

<xsd:element name="Stock">
    <xsd:complexType>

To:

<xsd:complexType name="Stock">

Make sure you fix the xml closing tags.

The second problem is that the correct way to reference an external XSD is to use XSD schema with import/include within a wsdl:types element. wsdl:import is reserved to referencing other WSDL files. More information is available by going through the WS-I specification, section WSDL and Schema Import. Based on WS-I, your case would be:

INCORRECT: (the way you showed it)

<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
    .....xmlns:external="http://stock.com/schemas/services/stock"
    <import namespace="http://stock.com/schemas/services/stock" location="Stock.xsd" />
    <message name="getStockQuoteResp">
        <part name="parameters" element="external:getStockQuoteResponse" />
    </message>
</definitions>

CORRECT:

<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
    .....xmlns:external="http://stock.com/schemas/services/stock"
    <types>
        <schema xmlns="http://www.w3.org/2001/XMLSchema">
            <import namespace="http://stock.com/schemas/services/stock" schemaLocation="Stock.xsd" />             
        </schema>
    </types>
    <message name="getStockQuoteResp">
        <part name="parameters" element="external:getStockQuoteResponse" />
    </message>
</definitions>

SOME processors may support both syntaxes. The XSD you put out shows issues, make sure you first validate the XSD.

It would be better if you go the WS-I way when it comes to WSDL authoring.

Other issues may be related to the use of relative vs. absolute URIs in locating external content.

Current date without time

This should work:

string datetime = DateTime.Today.ToString();

Installed Ruby 1.9.3 with RVM but command line doesn't show ruby -v

You have broken version of RVM. Ubuntu does something to RVM that produces lots of errors, the only safe way of fixing for now is to:

sudo apt-get --purge remove ruby-rvm
sudo rm -rf /usr/share/ruby-rvm /etc/rvmrc /etc/profile.d/rvm.sh

open new terminal and validate environment is clean from old RVM settings (should be no output):

env | grep rvm

if there was output, try to open new terminal, if it does not help then restart your computer.

install RVM:

\curl -L https://get.rvm.io | 
  bash -s stable --ruby --autolibs=enable --auto-dotfiles

If you find you need some hand-holding, take a look at Installing Ruby on Ubuntu 12.04, which gives a bit more explanation.

How to dynamically set bootstrap-datepicker's date value?

var startDate = new Date();

$('#dpStartDate').data({date: startDate}).datepicker('update').children("input").val(startDate);

another way

$('#dpStartDate').data({date: '2012-08-08'});
$('#dpStartDate').datepicker('update');
$('#dpStartDate').datepicker().children('input').val('2012-08-08');
  1. set the calendar date on property data-date
  2. update (required)
  3. set the input value (remember the input is child of datepicker).

this way you are setting the date to '2012-08-08'

Detecting IE11 using CSS Capability/Feature Detection

Detecting IE and its versions actually is extremely easy, at least extremely intuitive:

var uA = navigator.userAgent;
var browser = null;
var ieVersion = null;

if (uA.indexOf('MSIE 6') >= 0) {
    browser = 'IE';
    ieVersion = 6;
}
if (uA.indexOf('MSIE 7') >= 0) {
    browser = 'IE';
    ieVersion = 7;
}
if (document.documentMode) { // as of IE8
    browser = 'IE';
    ieVersion = document.documentMode;
}

.

This way, ou're also catching high IE versions in Compatibility Mode/View. Next, its a matter of assigning conditional classes:

var htmlTag = document.documentElement;
if (browser == 'IE' && ieVersion <= 11)
    htmlTag.className += ' ie11-';

SQL - HAVING vs. WHERE

Didn't see an example of both in one query. So this example might help.

  /**
INTERNATIONAL_ORDERS - table of orders by company by location by day
companyId, country, city, total, date
**/

SELECT country, city, sum(total) totalCityOrders 
FROM INTERNATIONAL_ORDERS with (nolock)
WHERE companyId = 884501253109
GROUP BY country, city
HAVING country = 'MX'
ORDER BY sum(total) DESC

This filters the table first by the companyId, then groups it (by country and city) and additionally filters it down to just city aggregations of Mexico. The companyId was not needed in the aggregation but we were able to use WHERE to filter out just the rows we wanted before using GROUP BY.

Check if a file exists in jenkins pipeline

You need to use brackets when using the fileExists step in an if condition or assign the returned value to a variable

Using variable:

def exists = fileExists 'file'

if (exists) {
    echo 'Yes'
} else {
    echo 'No'
}

Using brackets:

if (fileExists('file')) {
    echo 'Yes'
} else {
    echo 'No'
}

Measure string size in Bytes in php

Further to PhoneixS answer to get the correct length of string in bytes - Since mb_strlen() is slower than strlen(), for the best performance one can check "mbstring.func_overload" ini setting so that mb_strlen() is used only when it is really required:

$content_length = ini_get('mbstring.func_overload') ? mb_strlen($content , '8bit') : strlen($content);

Make div 100% Width of Browser Window

If width:100% works in any cases, just use that, otherwise you can use vw in this case which is relative to 1% of the width of the viewport.

That means if you want to cover off the width, just use 100vw.

Look at the image I draw for you here:

enter image description here

Try the snippet I created for you as below:

_x000D_
_x000D_
.full-width {_x000D_
  width: 100vw;_x000D_
  height: 100px;_x000D_
  margin-bottom: 40px;_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
.one-vw-width {_x000D_
  width: 1vw;_x000D_
  height: 100px;_x000D_
  background-color: red;_x000D_
}
_x000D_
<div class="full-width"></div>_x000D_
<div class="one-vw-width"></div>
_x000D_
_x000D_
_x000D_

Edit a commit message in SourceTree Windows (already pushed to remote)

If the comment message includes non-English characters, using method provided by user456814, those characters will be replaced by question marks. (tested under sourcetree Ver2.5.5.0)

So I have to use the following method.

CAUTION: if the commit has been pulled by other members, changes below might cause chaos for them.

Step1: In the sourcetree main window, locate your repo tab, and click the "terminal" button to open the git command console.

Step2:

[Situation A]: target commit is the latest one.

1) In the git command console, input

git commit --amend -m "new comment message"

2) If the target commit has been pushed to remote, you have to push again by force. In the git command console, input

git push --force

[Situation B]: target commit is not the latest one.

1) In the git command console, input

git rebase -i HEAD~n

It is to squash the latest n commits. e.g. if you want to edit the message before the last one, n is 2. This command will open a vi window, the first word of each line is "pick", and you change the "pick" to "reword" for the line you want to edit. Then, input :wq to save&quit that vi window. Now, a new vi window will be open, in this window you input your new message. Also use :wq to save&quit.

2) If the target commit has been pushed to remote, you have to push again by force. In the git command console, input

git push --force


Finally: In the sourcetree main window, Press F5 to refresh.

How to copy sheets to another workbook using vba?

try this one

Sub Get_Data_From_File()

     'Note: In the Regional Project that's coming up we learn how to import data from multiple Excel workbooks
    ' Also see BONUS sub procedure below (Bonus_Get_Data_From_File_InputBox()) that expands on this by inlcuding an input box
    Dim FileToOpen As Variant
    Dim OpenBook As Workbook
    Application.ScreenUpdating = False
    FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", FileFilter:="Excel Files (*.xls*),*xls*")
    If FileToOpen <> False Then
        Set OpenBook = Application.Workbooks.Open(FileToOpen)
         'copy data from A1 to E20 from first sheet
        OpenBook.Sheets(1).Range("A1:E20").Copy
        ThisWorkbook.Worksheets("SelectFile").Range("A10").PasteSpecial xlPasteValues
        OpenBook.Close False
        
    End If
    Application.ScreenUpdating = True
End Sub

or this one:

Get_Data_From_File_InputBox()

Dim FileToOpen As Variant
Dim OpenBook As Workbook
Dim ShName As String
Dim Sh As Worksheet
On Error GoTo Handle:

FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", FileFilter:="Excel Files (*.xls*),*.xls*")
Application.ScreenUpdating = False
Application.DisplayAlerts = False

If FileToOpen <> False Then
    Set OpenBook = Application.Workbooks.Open(FileToOpen)
    ShName = Application.InputBox("Enter the sheet name to copy", "Enter the sheet name to copy")
    For Each Sh In OpenBook.Worksheets
        If UCase(Sh.Name) Like "*" & UCase(ShName) & "*" Then
            ShName = Sh.Name
        End If
    Next Sh

    'copy data from the specified sheet to this workbook - updae range as you see fit
    OpenBook.Sheets(ShName).Range("A1:CF1100").Copy
    ThisWorkbook.ActiveSheet.Range("A10").PasteSpecial xlPasteValues
    OpenBook.Close False
End If
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Exit Sub

Handle: If Err.Number = 9 Then MsgBox "The sheet name does not exist. Please check spelling" Else MsgBox "An error has occurred." End If OpenBook.Close False Application.ScreenUpdating = True Application.DisplayAlerts = True End Sub

both work as

How to force addition instead of concatenation in javascript

The following statement appends the value to the element with the id of response

$('#response').append(total);

This makes it look like you are concatenating the strings, but you aren't, you're actually appending them to the element

change that to

$('#response').text(total);

You need to change the drop event so that it replaces the value of the element with the total, you also need to keep track of what the total is, I suggest something like the following

$(function() {
    var data = [];
    var total = 0;

    $( "#draggable1" ).draggable();
    $( "#draggable2" ).draggable();
    $( "#draggable3" ).draggable();

    $("#droppable_box").droppable({
        drop: function(event, ui) {
        var currentId = $(ui.draggable).attr('id');
        data.push($(ui.draggable).attr('id'));

        if(currentId == "draggable1"){
            var myInt1 = parseFloat($('#MealplanCalsPerServing1').val());
        }
        if(currentId == "draggable2"){
            var myInt2 = parseFloat($('#MealplanCalsPerServing2').val());
        }
        if(currentId == "draggable3"){
            var myInt3 = parseFloat($('#MealplanCalsPerServing3').val());
        }
        if ( typeof myInt1 === 'undefined' || !myInt1 ) {
            myInt1 = parseInt(0);
        }
        if ( typeof myInt2 === 'undefined' || !myInt2){
            myInt2 = parseInt(0);
        }
        if ( typeof myInt3 === 'undefined' || !myInt3){
        myInt3 = parseInt(0);
        }
        total += parseFloat(myInt1 + myInt2 + myInt3);
        $('#response').text(total);
        }
    });

    $('#myId').click(function(event) {
        $.post("process.php", ({ id: data }), function(return_data, status) {
            alert(data);
            //alert(total);
        });
    });
});

I moved the var total = 0; statement out of the drop event and changed the assignment statment from this

total = parseFloat(myInt1 + myInt2 + myInt3);

to this

total += parseFloat(myInt1 + myInt2 + myInt3);

Here is a working example http://jsfiddle.net/axrwkr/RCzGn/

Maximum request length exceeded.

If you are using IIS for hosting your application, then the default upload file size is 4MB. To increase it, please use this below section in your web.config -

<configuration>
    <system.web>
        <httpRuntime maxRequestLength="1048576" />
    </system.web>
</configuration>

For IIS7 and above, you also need to add the lines below:

 <system.webServer>
   <security>
      <requestFiltering>
         <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
   </security>
 </system.webServer>

Note:

  • maxRequestLength is measured in kilobytes
  • maxAllowedContentLength is measured in bytes

which is why the values differ in this config example. (Both are equivalent to 1 GB.)

Reset CSS display property to default value

According to my understanding to your question, as an example: you had a style at the beginning in style sheet (ex. background-color: red), then using java script you changed it to another style (ex. background-color: green), now you want to reset the style to its original value in style sheet (background-color: red) without mentioning or even knowing its value (ex. element.style.backgroundColor = 'red')...!

If I'm correct, I have a good solution for you which is using another class name for the element:

steps:

  1. set the default styles in style sheet as usual according to your desire.
  2. define a new class name in style sheet and add the new style you want.
  3. when you want to trigger between styles, add the new class name to the element or remove it.

if you want to edit or set a new style, get the element by the new class name and edit the style as desired.

I hope this helps. Regards!

Loop through properties in JavaScript object with Lodash

It would be helpful to understand why you need to do this with lodash. If you just want to check if a key exists in an object, you don't need lodash.

myObject.options.hasOwnProperty('property');

If your looking to see if a value exists, you can use _.invert

_.invert(myObject.options)[value]

SimpleXML - I/O warning : failed to load external entity

this also works:

$url = "http://www.some-url";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$xmlresponse = curl_exec($ch);
$xml=simplexml_load_string($xmlresponse);

then I just run a forloop to grab the stuff from the nodes.

like this:`

for($i = 0; $i < 20; $i++) {
$title = $xml->channel->item[$i]->title;
$link = $xml->channel->item[$i]->link;
$desc = $xml->channel->item[$i]->description;
$html .="<div><h3>$title</h3>$link<br />$desc</div><hr>";
}
echo $html;

***note that your node names will differ, obviously..and your HTML might be structured differently...also your loop might be set to higher or lower amount of results.

Global keyboard capture in C# application

As requested by dube I'm posting my modified version of Siarhei Kuchuk's answer.
If you want to check my changes search for // EDT. I've commented most of it.

The Setup

class GlobalKeyboardHookEventArgs : HandledEventArgs
{
    public GlobalKeyboardHook.KeyboardState KeyboardState { get; private set; }
    public GlobalKeyboardHook.LowLevelKeyboardInputEvent KeyboardData { get; private set; }

    public GlobalKeyboardHookEventArgs(
        GlobalKeyboardHook.LowLevelKeyboardInputEvent keyboardData,
        GlobalKeyboardHook.KeyboardState keyboardState)
    {
        KeyboardData = keyboardData;
        KeyboardState = keyboardState;
    }
}

//Based on https://gist.github.com/Stasonix
class GlobalKeyboardHook : IDisposable
{
    public event EventHandler<GlobalKeyboardHookEventArgs> KeyboardPressed;

    // EDT: Added an optional parameter (registeredKeys) that accepts keys to restict
    // the logging mechanism.
    /// <summary>
    /// 
    /// </summary>
    /// <param name="registeredKeys">Keys that should trigger logging. Pass null for full logging.</param>
    public GlobalKeyboardHook(Keys[] registeredKeys = null)
    {
        RegisteredKeys = registeredKeys;
        _windowsHookHandle = IntPtr.Zero;
        _user32LibraryHandle = IntPtr.Zero;
        _hookProc = LowLevelKeyboardProc; // we must keep alive _hookProc, because GC is not aware about SetWindowsHookEx behaviour.

        _user32LibraryHandle = LoadLibrary("User32");
        if (_user32LibraryHandle == IntPtr.Zero)
        {
            int errorCode = Marshal.GetLastWin32Error();
            throw new Win32Exception(errorCode, $"Failed to load library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
        }



        _windowsHookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, _hookProc, _user32LibraryHandle, 0);
        if (_windowsHookHandle == IntPtr.Zero)
        {
            int errorCode = Marshal.GetLastWin32Error();
            throw new Win32Exception(errorCode, $"Failed to adjust keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
        }
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            // because we can unhook only in the same thread, not in garbage collector thread
            if (_windowsHookHandle != IntPtr.Zero)
            {
                if (!UnhookWindowsHookEx(_windowsHookHandle))
                {
                    int errorCode = Marshal.GetLastWin32Error();
                    throw new Win32Exception(errorCode, $"Failed to remove keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
                }
                _windowsHookHandle = IntPtr.Zero;

                // ReSharper disable once DelegateSubtraction
                _hookProc -= LowLevelKeyboardProc;
            }
        }

        if (_user32LibraryHandle != IntPtr.Zero)
        {
            if (!FreeLibrary(_user32LibraryHandle)) // reduces reference to library by 1.
            {
                int errorCode = Marshal.GetLastWin32Error();
                throw new Win32Exception(errorCode, $"Failed to unload library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
            }
            _user32LibraryHandle = IntPtr.Zero;
        }
    }

    ~GlobalKeyboardHook()
    {
        Dispose(false);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private IntPtr _windowsHookHandle;
    private IntPtr _user32LibraryHandle;
    private HookProc _hookProc;

    delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);

    [DllImport("kernel32.dll")]
    private static extern IntPtr LoadLibrary(string lpFileName);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    private static extern bool FreeLibrary(IntPtr hModule);

    /// <summary>
    /// The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain.
    /// You would install a hook procedure to monitor the system for certain types of events. These events are
    /// associated either with a specific thread or with all threads in the same desktop as the calling thread.
    /// </summary>
    /// <param name="idHook">hook type</param>
    /// <param name="lpfn">hook procedure</param>
    /// <param name="hMod">handle to application instance</param>
    /// <param name="dwThreadId">thread identifier</param>
    /// <returns>If the function succeeds, the return value is the handle to the hook procedure.</returns>
    [DllImport("USER32", SetLastError = true)]
    static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, int dwThreadId);

    /// <summary>
    /// The UnhookWindowsHookEx function removes a hook procedure installed in a hook chain by the SetWindowsHookEx function.
    /// </summary>
    /// <param name="hhk">handle to hook procedure</param>
    /// <returns>If the function succeeds, the return value is true.</returns>
    [DllImport("USER32", SetLastError = true)]
    public static extern bool UnhookWindowsHookEx(IntPtr hHook);

    /// <summary>
    /// The CallNextHookEx function passes the hook information to the next hook procedure in the current hook chain.
    /// A hook procedure can call this function either before or after processing the hook information.
    /// </summary>
    /// <param name="hHook">handle to current hook</param>
    /// <param name="code">hook code passed to hook procedure</param>
    /// <param name="wParam">value passed to hook procedure</param>
    /// <param name="lParam">value passed to hook procedure</param>
    /// <returns>If the function succeeds, the return value is true.</returns>
    [DllImport("USER32", SetLastError = true)]
    static extern IntPtr CallNextHookEx(IntPtr hHook, int code, IntPtr wParam, IntPtr lParam);

    [StructLayout(LayoutKind.Sequential)]
    public struct LowLevelKeyboardInputEvent
    {
        /// <summary>
        /// A virtual-key code. The code must be a value in the range 1 to 254.
        /// </summary>
        public int VirtualCode;

        // EDT: added a conversion from VirtualCode to Keys.
        /// <summary>
        /// The VirtualCode converted to typeof(Keys) for higher usability.
        /// </summary>
        public Keys Key { get { return (Keys)VirtualCode; } }

        /// <summary>
        /// A hardware scan code for the key. 
        /// </summary>
        public int HardwareScanCode;

        /// <summary>
        /// The extended-key flag, event-injected Flags, context code, and transition-state flag. This member is specified as follows. An application can use the following values to test the keystroke Flags. Testing LLKHF_INJECTED (bit 4) will tell you whether the event was injected. If it was, then testing LLKHF_LOWER_IL_INJECTED (bit 1) will tell you whether or not the event was injected from a process running at lower integrity level.
        /// </summary>
        public int Flags;

        /// <summary>
        /// The time stamp stamp for this message, equivalent to what GetMessageTime would return for this message.
        /// </summary>
        public int TimeStamp;

        /// <summary>
        /// Additional information associated with the message. 
        /// </summary>
        public IntPtr AdditionalInformation;
    }

    public const int WH_KEYBOARD_LL = 13;
    //const int HC_ACTION = 0;

    public enum KeyboardState
    {
        KeyDown = 0x0100,
        KeyUp = 0x0101,
        SysKeyDown = 0x0104,
        SysKeyUp = 0x0105
    }

    // EDT: Replaced VkSnapshot(int) with RegisteredKeys(Keys[])
    public static Keys[] RegisteredKeys;
    const int KfAltdown = 0x2000;
    public const int LlkhfAltdown = (KfAltdown >> 8);

    public IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam)
    {
        bool fEatKeyStroke = false;

        var wparamTyped = wParam.ToInt32();
        if (Enum.IsDefined(typeof(KeyboardState), wparamTyped))
        {
            object o = Marshal.PtrToStructure(lParam, typeof(LowLevelKeyboardInputEvent));
            LowLevelKeyboardInputEvent p = (LowLevelKeyboardInputEvent)o;

            var eventArguments = new GlobalKeyboardHookEventArgs(p, (KeyboardState)wparamTyped);

            // EDT: Removed the comparison-logic from the usage-area so the user does not need to mess around with it.
            // Either the incoming key has to be part of RegisteredKeys (see constructor on top) or RegisterdKeys
            // has to be null for the event to get fired.
            var key = (Keys)p.VirtualCode;
            if (RegisteredKeys == null || RegisteredKeys.Contains(key))
            {
                EventHandler<GlobalKeyboardHookEventArgs> handler = KeyboardPressed;
                handler?.Invoke(this, eventArguments);

                fEatKeyStroke = eventArguments.Handled;
            }
        }

        return fEatKeyStroke ? (IntPtr)1 : CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);
    }
}

The Usage differences can be seen here

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private GlobalKeyboardHook _globalKeyboardHook;

    private void buttonHook_Click(object sender, EventArgs e)
    {
        // Hooks only into specified Keys (here "A" and "B").
        _globalKeyboardHook = new GlobalKeyboardHook(new Keys[] { Keys.A, Keys.B });

        // Hooks into all keys.
        _globalKeyboardHook = new GlobalKeyboardHook();
        _globalKeyboardHook.KeyboardPressed += OnKeyPressed;
    }

    private void OnKeyPressed(object sender, GlobalKeyboardHookEventArgs e)
    {
        // EDT: No need to filter for VkSnapshot anymore. This now gets handled
        // through the constructor of GlobalKeyboardHook(...).
        if (e.KeyboardState == GlobalKeyboardHook.KeyboardState.KeyDown)
        {
            // Now you can access both, the key and virtual code
            Keys loggedKey = e.KeyboardData.Key;
            int loggedVkCode = e.KeyboardData.VirtualCode;
        }
    }
}

Thanks to Siarhei Kuchuk for his post. Even tho I've simplified the usage this initial code was very useful for me.

Java: object to byte[] and byte[] to object converter (for Tokyo Cabinet)

If your class extends Serializable, you can write and read objects through a ByteArrayOutputStream, that's what I usually do.

Easiest way to read/write a file's content in Python

Slow, ugly, platform-specific... but one-liner ;-)

import subprocess

contents = subprocess.Popen('cat %s' % filename, shell = True, stdout = subprocess.PIPE).communicate()[0]

How to convert Strings to and from UTF8 byte arrays in Java

String original = "hello world";
byte[] utf8Bytes = original.getBytes("UTF-8");

Adding Access-Control-Allow-Origin header response in Laravel 5.3 Passport

After https://github.com/fruitcake/laravel-cors I had to change in cors.php file as below

     * Sets the Access-Control-Allow-Credentials header.
     */
    'supports_credentials' => true,

How to decode Unicode escape sequences like "\u00ed" to proper UTF-8 encoded characters?

$str = '\u0063\u0061\u0074'.'\ud83d\ude38';
$str2 = '\u0063\u0061\u0074'.'\ud83d';

// U+1F638
var_dump(
    "cat\xF0\x9F\x98\xB8" === escape_sequence_decode($str),
    "cat\xEF\xBF\xBD" === escape_sequence_decode($str2)
);

function escape_sequence_decode($str) {

    // [U+D800 - U+DBFF][U+DC00 - U+DFFF]|[U+0000 - U+FFFF]
    $regex = '/\\\u([dD][89abAB][\da-fA-F]{2})\\\u([dD][c-fC-F][\da-fA-F]{2})
              |\\\u([\da-fA-F]{4})/sx';

    return preg_replace_callback($regex, function($matches) {

        if (isset($matches[3])) {
            $cp = hexdec($matches[3]);
        } else {
            $lead = hexdec($matches[1]);
            $trail = hexdec($matches[2]);

            // http://unicode.org/faq/utf_bom.html#utf16-4
            $cp = ($lead << 10) + $trail + 0x10000 - (0xD800 << 10) - 0xDC00;
        }

        // https://tools.ietf.org/html/rfc3629#section-3
        // Characters between U+D800 and U+DFFF are not allowed in UTF-8
        if ($cp > 0xD7FF && 0xE000 > $cp) {
            $cp = 0xFFFD;
        }

        // https://github.com/php/php-src/blob/php-5.6.4/ext/standard/html.c#L471
        // php_utf32_utf8(unsigned char *buf, unsigned k)

        if ($cp < 0x80) {
            return chr($cp);
        } else if ($cp < 0xA0) {
            return chr(0xC0 | $cp >> 6).chr(0x80 | $cp & 0x3F);
        }

        return html_entity_decode('&#'.$cp.';');
    }, $str);
}

How to find count of Null and Nan values for each column in a PySpark dataframe efficiently?

To make sure it does not fail for string, date and timestamp columns:

import pyspark.sql.functions as F
def count_missings(spark_df,sort=True):
    """
    Counts number of nulls and nans in each column
    """
    df = spark_df.select([F.count(F.when(F.isnan(c) | F.isnull(c), c)).alias(c) for (c,c_type) in spark_df.dtypes if c_type not in ('timestamp', 'string', 'date')]).toPandas()

    if len(df) == 0:
        print("There are no any missing values!")
        return None

    if sort:
        return df.rename(index={0: 'count'}).T.sort_values("count",ascending=False)

    return df

If you want to see the columns sorted based on the number of nans and nulls in descending:

count_missings(spark_df)

# | Col_A | 10 |
# | Col_C | 2  |
# | Col_B | 1  | 

If you don't want ordering and see them as a single row:

count_missings(spark_df, False)
# | Col_A | Col_B | Col_C |
# |  10   |   1   |   2   |

From Now() to Current_timestamp in Postgresql

select * from table where column_date > now()- INTERVAL '6 hours';

How to clone git repository with specific revision/changeset?

Its simple. You just have to set the upstream for the current branch

$ git clone repo
$ git checkout -b newbranch
$ git branch --set-upstream-to=origin/branch newbranch
$ git pull

That's all

Share variables between files in Node.js?

I'm unable to find an scenario where a global var is the best option, of course you can have one, but take a look at these examples and you may find a better way to accomplish the same:

Scenario 1: Put the stuff in config files

You need some value that it's the same across the application, but it changes depending on the environment (production, dev or test), the mailer type as example, you'd need:

// File: config/environments/production.json
{
    "mailerType": "SMTP",
    "mailerConfig": {
      "service": "Gmail",
      ....
}

and

// File: config/environments/test.json
{
    "mailerType": "Stub",
    "mailerConfig": {
      "error": false
    }
}

(make a similar config for dev too)

To decide which config will be loaded make a main config file (this will be used all over the application)

// File: config/config.js
var _ = require('underscore');

module.exports = _.extend(
    require(__dirname + '/../config/environments/' + process.env.NODE_ENV + '.json') || {});

And now you can get the data like this:

// File: server.js
...
var config = require('./config/config');
...
mailer.setTransport(nodemailer.createTransport(config.mailerType, config.mailerConfig));

Scenario 2: Use a constants file

// File: constants.js
module.exports = {
  appName: 'My neat app',
  currentAPIVersion: 3
};

And use it this way

// File: config/routes.js

var constants = require('../constants');

module.exports = function(app, passport, auth) {
  var apiroot = '/api/v' + constants.currentAPIVersion;
...
  app.post(apiroot + '/users', users.create);
...

Scenario 3: Use a helper function to get/set the data

Not a big fan of this one, but at least you can track the use of the 'name' (citing the OP's example) and put validations in place.

// File: helpers/nameHelper.js

var _name = 'I shall not be null'

exports.getName = function() {
  return _name;
};

exports.setName = function(name) {
  //validate the name...
  _name = name;
};

And use it

// File: controllers/users.js

var nameHelper = require('../helpers/nameHelper.js');

exports.create = function(req, res, next) {
  var user = new User();
  user.name = req.body.name || nameHelper.getName();
  ...

There could be a use case when there is no other solution than having a global var, but usually you can share the data in your app using one of these scenarios, if you are starting to use node.js (as I was sometime ago) try to organize the way you handle the data over there because it can get messy really quick.

Git pull command from different user

This command will help to pull from the repository as the different user:

git pull https://[email protected]/projectfolder/projectname.git master

It is a workaround, when you are using same machine that someone else used before you, and had saved credentials

Jquery select change not firing

This works for me!

$('#<%= ddlstuff.ClientID %>').change(function () {
    alert('Change Happened');
     $('#<%= txtBoxToClear.ClientID %>').val('');
});

Does hosts file exist on the iPhone? How to change it?

It might exist, but you cannot change it on a non-jailbreaked iPhone.

Assuming that your development webserver is on a Mac, why don't you simply use its Bonjour name (e.g. MyMac.local.) instead of myrealwebserverontheinternet.com?

Set UITableView content inset permanently

      self.rx.viewDidAppearOnce
            .flatMapLatest { _ in RxKeyboard.instance.isHidden }
            .bind(onNext: { [unowned self] isHidden in
                guard !isHidden else { return }
                self.tableView.beginUpdates()
                self.tableView.contentInsetAdjustmentBehavior = .automatic
                self.tableView.endUpdates()
            })
            .disposed(by: self.disposeBag)

#1064 -You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version

One obvious thing is that you will have to remove the comma here

receipt int(10),

but the actual problem is because of the line

amount double(10) NOT NULL,

change it to

amount double NOT NULL,

How do I convert between ISO-8859-1 and UTF-8 in Java?

Apache Commons IO Charsets class can come in handy:

String utf8String = new String(org.apache.commons.io.Charsets.ISO_8859_1.encode(latinString).array())

What is the effect of extern "C" in C++?

It changes the linkage of a function in such a way that the function is callable from C. In practice that means that the function name is not mangled.

How to show text on image when hovering?

It's simple. Wrap the image and the "appear on hover" description in a div with the same dimensions of the image. Then, with some CSS, order the description to appear while hovering that div.

_x000D_
_x000D_
/* quick reset */_x000D_
* {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  border: 0;_x000D_
}_x000D_
_x000D_
/* relevant styles */_x000D_
.img__wrap {_x000D_
  position: relative;_x000D_
  height: 200px;_x000D_
  width: 257px;_x000D_
}_x000D_
_x000D_
.img__description {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  background: rgba(29, 106, 154, 0.72);_x000D_
  color: #fff;_x000D_
  visibility: hidden;_x000D_
  opacity: 0;_x000D_
_x000D_
  /* transition effect. not necessary */_x000D_
  transition: opacity .2s, visibility .2s;_x000D_
}_x000D_
_x000D_
.img__wrap:hover .img__description {_x000D_
  visibility: visible;_x000D_
  opacity: 1;_x000D_
}
_x000D_
<div class="img__wrap">_x000D_
  <img class="img__img" src="http://placehold.it/257x200.jpg" />_x000D_
  <p class="img__description">This image looks super neat.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

A nice fiddle: https://jsfiddle.net/govdqd8y/

How to bring back "Browser mode" in IE11?

How to bring back “Browser mode” in IE11?

Easy way to bring back is just go to Emulation (ctrl +8)

and do change user agent string. (see attached image)

enter image description here

Refresh (reload) a page once using jQuery?

Use this instead

function timedRefresh(timeoutPeriod) {
    setTimeout("location.reload(true);",timeoutPeriod);
}

<a href="javascript:timedRefresh(2000)">image</a>

.rar, .zip files MIME Type

As extension might contain more or less that three characters the following will test for an extension regardless of the length of it.

Try this:

$allowedExtensions = array( 'mkv', 'mp3', 'flac' );

$temp = explode(".", $_FILES[$file]["name"]);
$extension = strtolower(end($temp));

if( in_array( $extension, $allowedExtensions ) ) { ///

to check for all characters after the last '.'

What is define([ , function ]) in JavaScript?

That's probably a requireJS module definition

Check here for more details

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.

How to Export-CSV of Active Directory Objects?

HI you can try this...

Try..

$Ad = Get-ADUser -SearchBase "OU=OUi,DC=company,DC=com"  -Filter * -Properties employeeNumber | ? {$_.employeenumber -eq ""}
$Ad | Sort-Object -Property sn, givenName | Select * | Export-Csv c:\scripts\ceridian\NoClockNumber_2013_02_12.csv -NoTypeInformation

Or

$Ad = Get-ADUser -SearchBase "OU=OUi,DC=company,DC=com"  -Filter * -Properties employeeNumber | ? {$_.employeenumber -eq $null}
$Ad | Sort-Object -Property sn, givenName | Select * | Export-Csv c:\scripts\cer

Hope it works for you.

OSError: [WinError 193] %1 is not a valid Win32 application

I got the same error while I forgot to use shell=True in the subprocess.call.

subprocess.call('python modify_depth_images.py', shell=True)

Running External Command

To run an external command without interacting with it, such as one would do with os.system(), Use the call() function.

import subprocess

Simple command subprocess.call(['ls', '-1'], shell=True)

Generate sha256 with OpenSSL and C++

Here's how I did it:

void sha256_hash_string (unsigned char hash[SHA256_DIGEST_LENGTH], char outputBuffer[65])
{
    int i = 0;

    for(i = 0; i < SHA256_DIGEST_LENGTH; i++)
    {
        sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
    }

    outputBuffer[64] = 0;
}


void sha256_string(char *string, char outputBuffer[65])
{
    unsigned char hash[SHA256_DIGEST_LENGTH];
    SHA256_CTX sha256;
    SHA256_Init(&sha256);
    SHA256_Update(&sha256, string, strlen(string));
    SHA256_Final(hash, &sha256);
    int i = 0;
    for(i = 0; i < SHA256_DIGEST_LENGTH; i++)
    {
        sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
    }
    outputBuffer[64] = 0;
}

int sha256_file(char *path, char outputBuffer[65])
{
    FILE *file = fopen(path, "rb");
    if(!file) return -534;

    unsigned char hash[SHA256_DIGEST_LENGTH];
    SHA256_CTX sha256;
    SHA256_Init(&sha256);
    const int bufSize = 32768;
    unsigned char *buffer = malloc(bufSize);
    int bytesRead = 0;
    if(!buffer) return ENOMEM;
    while((bytesRead = fread(buffer, 1, bufSize, file)))
    {
        SHA256_Update(&sha256, buffer, bytesRead);
    }
    SHA256_Final(hash, &sha256);

    sha256_hash_string(hash, outputBuffer);
    fclose(file);
    free(buffer);
    return 0;
}

It's called like this:

static unsigned char buffer[65];
sha256("string", buffer);
printf("%s\n", buffer);

How to get span tag inside a div in jQuery and assign a text?

Try this

$("#message span").text("hello world!");

function Errormessage(txt) {
    var elem = $("#message");
    elem.fadeIn("slow");
    // find the span inside the div and assign a text
    elem.children("span").text("your text");

    elem.children("a.close-notify").click(function() {
        elem.fadeOut("slow");
    });
}

Show/hide forms using buttons and JavaScript

Would you want the same form with different parts, showing each part accordingly with a button?

Here an example with three steps, that is, three form parts, but it is expandable to any number of form parts. The HTML characters &laquo; and &raquo; just print respectively « and » which might be interesting for the previous and next button characters.

_x000D_
_x000D_
shows_form_part(1)_x000D_
_x000D_
/* this function shows form part [n] and hides the remaining form parts */_x000D_
function shows_form_part(n){_x000D_
  var i = 1, p = document.getElementById("form_part"+1);_x000D_
  while (p !== null){_x000D_
    if (i === n){_x000D_
      p.style.display = "";_x000D_
    }_x000D_
    else{_x000D_
      p.style.display = "none";_x000D_
    }_x000D_
    i++;_x000D_
    p = document.getElementById("form_part"+i);_x000D_
  }_x000D_
}_x000D_
_x000D_
/* this is called at the last step using info filled during the previous steps*/_x000D_
function calc_sum() {_x000D_
  var sum =_x000D_
    parseInt(document.getElementById("num1").value) +_x000D_
    parseInt(document.getElementById("num2").value) +_x000D_
    parseInt(document.getElementById("num3").value);_x000D_
_x000D_
  alert("The sum is: " + sum);_x000D_
}
_x000D_
<div id="form_part1">_x000D_
  Part 1<br>_x000D_
  <input type="number" value="1" id="num1"><br>_x000D_
  <button type="button" onclick="shows_form_part(2)">&raquo;</button>_x000D_
</div>_x000D_
_x000D_
<div id="form_part2">_x000D_
  Part 2<br>_x000D_
  <input type="number" value="2" id="num2"><br>_x000D_
  <button type="button" onclick="shows_form_part(1)">&laquo;</button>_x000D_
  <button type="button" onclick="shows_form_part(3)">&raquo;</button>_x000D_
</div>_x000D_
_x000D_
<div id="form_part3">_x000D_
  Part 3<br>_x000D_
  <input type="number" value="3" id="num3"><br>_x000D_
  <button type="button" onclick="shows_form_part(2)">&laquo;</button>_x000D_
  <button type="button" onclick="calc_sum()">Sum</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Image UriSource and Data Binding

WPF has built-in converters for certain types. If you bind the Image's Source property to a string or Uri value, under the hood WPF will use an ImageSourceConverter to convert the value to an ImageSource.

So

<Image Source="{Binding ImageSource}"/>

would work if the ImageSource property was a string representation of a valid URI to an image.

You can of course roll your own Binding converter:

public class ImageConverter : IValueConverter
{
    public object Convert(
        object value, Type targetType, object parameter, CultureInfo culture)
    {
        return new BitmapImage(new Uri(value.ToString()));
    }

    public object ConvertBack(
        object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

and use it like this:

<Image Source="{Binding ImageSource, Converter={StaticResource ImageConverter}}"/>

How to insert new row to database with AUTO_INCREMENT column without specifying column names?

Even better, use DEFAULT instead of NULL. You want to store the default value, not a NULL that might trigger a default value.

But you'd better name all columns, with a piece of SQL you can create all the INSERT, UPDATE and DELETE's you need. Just check the information_schema and construct the queries you need. There is no need to do it all by hand, SQL can help you out.

Shell script to copy files from one location to another location and rename add the current date to every file

path_src=./folder1
path_dst=./folder2
date=$(date +"%m%d%y")
for file_src in $path_src/*; do
  file_dst="$path_dst/$(basename $file_src | \
    sed "s/^\(.*\)\.\(.*\)/\1$date.\2/")"
  echo mv "$file_src" "$file_dst"
done

"This SqlTransaction has completed; it is no longer usable."... configuration error?

Also check for any long running processes executed from your .NET app against the DB. For example you may be calling a stored procedure or query which does not have enough time to finish which can show in your logs as:

  • Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

    • This SqlTransaction has completed; it is no longer usable.

Check the command timeout settings Try to run a trace (profiler) and see what is happening on the DB side...

What values for checked and selected are false?

The empty string is false as a rule.

Apparently the empty string is not respected as empty in all browsers and the presence of the checked attribute is taken to mean checked. So the entire attribute must either be present or omitted.

Show current assembly instruction in GDB

The command

x/i $pc

can be set to run all the time using the usual configuration mechanism.

MySQL does not start when upgrading OSX to Yosemite or El Capitan

2 steps solved my problem:

1) Delete "/Library/LaunchDaemons/com.mysql.mysql.plist"

2) Restart Yosemite

Hexadecimal To Decimal in Shell Script

The error as reported appears when the variables are null (or empty):

$ unset var3 var4; var5=$(($var4-$var3))
bash: -: syntax error: operand expected (error token is "-")

That could happen because the value given to bc was incorrect. That might well be that bc needs UPPERcase values. It needs BFCA3000, not bfca3000. That is easily fixed in bash, just use the ^^ expansion:

var3=bfca3000; var3=`echo "ibase=16; ${var1^^}" | bc`

That will change the script to this:

#!/bin/bash

var1="bfca3000"
var2="efca3250"

var3="$(echo "ibase=16; ${var1^^}" | bc)"
var4="$(echo "ibase=16; ${var2^^}" | bc)"

var5="$(($var4-$var3))"

echo "Diference $var5"

But there is no need to use bc [1], as bash could perform the translation and substraction directly:

#!/bin/bash

var1="bfca3000"
var2="efca3250"

var5="$(( 16#$var2 - 16#$var1 ))"

echo "Diference $var5"

[1]Note: I am assuming the values could be represented in 64 bit math, as the difference was calculated in bash in your original script. Bash is limited to integers less than ((2**63)-1) if compiled in 64 bits. That will be the only difference with bc which does not have such limit.

.NET Excel Library that can read/write .xls files

You may consider 3rd party tool that called Excel Jetcell .NET component for read/write excel files:

C# sample

// Create New Excel Workbook
ExcelWorkbook Wbook = new ExcelWorkbook();
ExcelCellCollection Cells = Wbook.Worksheets.Add("Sheet1").Cells;

Cells["A1"].Value = "Excel writer example (C#)";
Cells["A1"].Style.Font.Bold = true;
Cells["B1"].Value = "=550 + 5";

// Write Excel XLS file
Wbook.WriteXLS("excel_net.xls");

VB.NET sample

' Create New Excel Workbook
Dim Wbook As ExcelWorkbook = New ExcelWorkbook()
Dim Cells As ExcelCellCollection = Wbook.Worksheets.Add("Sheet1").Cells

Cells("A1").Value = "Excel writer example (C#)"
Cells("A1").Style.Font.Bold = True
Cells("B1").Value = "=550 + 5"

' Write Excel XLS file
Wbook.WriteXLS("excel_net.xls")

Select value if condition in SQL Server

Try Case

SELECT   stock.name,
      CASE 
         WHEN stock.quantity <20 THEN 'Buy urgent'
         ELSE 'There is enough'
      END
FROM stock

grep's at sign caught as whitespace

No -P needed; -E is sufficient:

grep -E '(^|\s)abc(\s|$)' 

or even without -E:

grep '\(^\|\s\)abc\(\s\|$\)' 

How to disable Paste (Ctrl+V) with jQuery?

_x000D_
_x000D_
 $(document).ready(function(){_x000D_
   $('#txtInput').on("cut copy paste",function(e) {_x000D_
      e.preventDefault();_x000D_
   });_x000D_
});
_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
    <input type="text" id="txtInput" />
_x000D_
_x000D_
_x000D_

PDF Blob - Pop up window not showing content

I ended up just downloading my pdf using below code

function downloadPdfDocument(fileName){

var req = new XMLHttpRequest();
req.open("POST", "/pdf/" + fileName, true);
req.responseType = "blob";
fileName += "_" + new Date() + ".pdf";

req.onload = function (event) {

    var blob = req.response;

    //for IE
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else {

        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
    }
};

req.send();

}

PHP get dropdown value and text

$animals = array('--Select Animal--', 'Cat', 'Dog', 'Cow');
$selected_key = $_POST['animal'];
$selected_val = $animals[$_POST['animal']];

Use your $animals list to generate your dropdown list; you now can get the key & the value of that key.

How to properly assert that an exception gets raised in pytest?

you can try

def test_exception():
    with pytest.raises(Exception) as excinfo:   
        function_that_raises_exception()   
    assert str(excinfo.value) == 'some info' 

Linux Script to check if process is running and act on the result

In case you're looking for a more modern way to check to see if a service is running (this will not work for just any old process), then systemctl might be what you're looking for.

Here's the basic command:

systemctl show --property=ActiveState your_service_here

Which will yield very simple output (one of the following two lines will appear depending on whether the service is running or not running):

ActiveState=active
ActiveState=inactive

And if you'd like to know all of the properties you can get:

systemctl show --all your_service_here

If you prefer that alphabetized:

systemctl show --all your_service_here | sort

And the full code to act on it:

service=$1
result=`systemctl show --property=ActiveState $service`
if [[ "$result" == 'ActiveState=active' ]]; then
    echo "$service is running" # Do something here
else
    echo "$service is not running" # Do something else here
fi 

Split a string by another string in C#

Regex.Split(string, "xx")

is the way I do it usually.


Of course you'll need:

using System.Text.RegularExpressions;

or :

System.Text.RegularExpressions.Regex.Split(string, "xx")

but then again I need that library all the time.

What database does Google use?

And it's maybe also handy to know that BigTable is not a relational database (like MySQL) but a huge (distributed) hash table which has very different characteristics. You can play around with (a limited version) of BigTable yourself on the Google AppEngine platform.

Next to Hadoop mentioned above there are many other implementations that try to solve the same problems as BigTable (scalability, availability). I saw a nice blog post yesterday listing most of them here.

Iterating through array - java

Since atleast Java 1.5.0 (Java 5) the code can be cleaned up a bit. Arrays and anything that implements Iterator (e.g. Collections) can be looped as such:

public static boolean inArray(int[] array, int check) {
   for (int o : array){
      if (o == check) {
         return true;
      }
   }
   return false;
}

In Java 8 you can also do something like:

// import java.util.stream.IntStream;

public static boolean inArray(int[] array, int check) {
   return IntStream.of(array).anyMatch(val -> val == check);
}

Although converting to a stream for this is probably overkill.

Purpose of installing Twitter Bootstrap through npm?

  1. The point of using CDN is that it is faster, first of all, because it is a distributed network, but secondly, because the static files are being cached by the browsers and chances are high that, for example, the CDN's jquery library that your site uses had already been downloaded by the user's browser, and therefore the file had been cached, and therefore no unnecessary download is taking place. That being said, it is still a good idea to provide a fallback.

    Now, the point of bootstrap's npm package

    is that it provides bootstrap's javascript file as a module. As has been mentioned above, this makes it possible to require it using browserify, which is the most likely use case and, as I understand it, the main reason for bootstrap being published on npm.

  2. How to use it

    Imagine the following project structure:

    project
    |-- node_modules
    |-- public
    |   |-- css
    |   |-- img
    |   |-- js
    |   |-- index.html
    |-- package.json
    
    

In your index.html you can reference both css and js files like this:

<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.min.css">
<script src="../node_modules/bootstrap/dist/js/bootstrap.min.js"></script>

Which is the simplest way, and correct for the .css files. But it is much better to include the bootstrap.js file like this somewhere in your public/js/*.js files:

var bootstrap = require('bootstrap');

And you include this code only in those javascript files where you actually need bootstrap.js. Browserify takes care of including this file for you.

Now, the drawback is that you now have your front-end files as node_modules dependencies, and the node_modules folder is usually not checked in with git. I think this is the most controversial part, with many opinions and solutions.


UPDATE March 2017

Almost two years have passed since I wrote this answer and an update is in place.

Now the generally accepted way is to use a bundler like webpack (or another bundler of choice) to bundle all your assets in a build step.

Firstly, it allows you to use commonjs syntax just like browserify, so to include bootstrap js code in your project you do the same:

const bootstrap = require('bootstrap');

As for the css files, webpack has so called "loaders". They allow you write this in your js code:

require('bootstrap/dist/css/bootstrap.css');

and the css files will be "magically" included in your build. They will be dynamically added as <style /> tags when your app runs, but you can configure webpack to export them as a separate css file. You can read more about that in webpack's documentation.

In conclusion.

  1. You should "bundle" your app code with a bundler
  2. You shouldn't commit neither node_modules nor the dynamically built files to git. You can add a build script to npm which should be used to deploy files on server. Anyway, this can be done in different ways depending on your preferred build process.

Add Items to ListView - Android

ListView myListView = (ListView) rootView.findViewById(R.id.myListView);
ArrayList<String> myStringArray1 = new ArrayList<String>();
myStringArray1.add("something");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);

Try it like this

public OnClickListener moreListener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        adapter = null;
        myStringArray1.add("Andrea");
        adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
        myListView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }       
};

How to create a localhost server to run an AngularJS project

An angular application can be deployed using any Web server on localhost. The options below outline the deployment instructions for several possible webserver deployments depending on your deployment requirements.


Microsofts Internet Information Services (IIS)

  1. Windows IIS must be enabled

    1.1. In Windows, access the Control Panel and click Add or Remove Programs.

    1.2. In the Add or Remove Programs window, click Add/Remove Windows Components.

    1.3. Select the Internet Information Services (IIS) check box, click Next, then click Finish.

    1.4. Copy and extract the Angular Application Zip file to the webserver root directory: C:\inetpub\wwwroot

  2. The Angular application can now be accessed using the following URL: http://localhost:8080

NPMs Lightweight Web Server

  1. Installing a lightweight web server 1.1. Download and install npm from: https://www.npmjs.com/get-npm 1.2. Once, npm has been installed open a command prompt and type: npm install -g http-server 1.3. Extract the Angular Zip file
  2. To run the web server, open a command prompt, and navigate to the directory where you extracted the Angular previously and type: http-server
  3. The Angular Application application can now be accessed using the following URL: http://localhost:8080

Apache Tomcat Web Server

  1. Installing Apache Tomcat version 8 1.1. Download and install Apache Tomcat from: https://tomcat.apache.org/ 1.2. Copy and extract the Angular Application Zip file to the webserver root directory C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps
  2. The Angular Application can now be accessed using the following URL: http://localhost:8080

Can you 'exit' a loop in PHP?

You can use the break keyword.

Converting a number with comma as decimal point to float

Might look excessive but will convert any given format no mater the locale:

function normalizeDecimal($val, int $precision = 4): string
{
    $input = str_replace(' ', '', $val);
    $number = str_replace(',', '.', $input);
    if (strpos($number, '.')) {
        $groups = explode('.', str_replace(',', '.', $number));
        $lastGroup = array_pop($groups);
        $number = implode('', $groups) . '.' . $lastGroup;
    }
    return bcadd($number, 0, $precision);
}

Output:

.12           -> 0.1200
123           -> 123.0000
123.91        -> 12345678.9100
123 456 78.91 -> 12345678.9100
123,456,78.91 -> 12345678.9100
123.456.78,91 -> 12345678.9100
123 456 78,91 -> 12345678.9100

What's the difference between a temp table and table variable in SQL Server?

In which scenarios does one out-perform the other?

For smaller tables (less than 1000 rows) use a temp variable, otherwise use a temp table.

how to set radio button checked in edit mode in MVC razor view

Here is the code for get value of checked radio button and set radio button checked according to it's value in edit form:

Controller:

[HttpPost]
public ActionResult Create(FormCollection collection)
{
    try
    {
        CommonServiceReference.tbl_user user = new CommonServiceReference.tbl_user();
        user.user_gender = collection["rdbtnGender"];
        return RedirectToAction("Index");
    }
    catch(Exception e)
    {
        throw e;
    }
}

public ActionResult Edit(int id)
{
    CommonServiceReference.ViewUserGroup user = clientObj.getUserById(id);
    ViewBag.UserObj = user;
    return View();
}

VIEW:

Create:

<input type="radio" id="rdbtnGender1" name="rdbtnGender" value="Male" required>
<label for="rdbtnGender1">MALE</label>
<input type="radio" id="rdbtnGender2" name="rdbtnGender" value="Female" required>
<label  for="rdbtnGender2">FEMALE</label>

Edit:

<input type="radio" id="rdbtnGender1" name="rdbtnGender" value="Male" @(ViewBag.UserObj.user_gender == "Male" ? "checked='true'" : "") required>
<label for="rdbtnGender1">MALE</label>

<input type="radio" id="rdbtnGender2" name="rdbtnGender" value="Female" @(ViewBag.UserObj.user_gender == "Female" ? "checked='true'" : "") required>
<label for="rdbtnGender2">FEMALE</label>

What does the CSS rule "clear: both" do?

The clear property indicates that the left, right or both sides of an element can not be adjacent to earlier floated elements within the same block formatting context. Cleared elements are pushed below the corresponding floated elements. Examples:

clear: none; Element remains adjacent to floated elements

_x000D_
_x000D_
body {_x000D_
  font-family: monospace;_x000D_
  background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
  float: left;_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.float-right {_x000D_
  float: right;_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.clear-none {_x000D_
  clear: none;_x000D_
  background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="float-right">float: right;</div>_x000D_
<div class="clear-none">clear: none;</div>
_x000D_
_x000D_
_x000D_

clear: left; Element pushed below left floated elements

_x000D_
_x000D_
body {_x000D_
  font-family: monospace;_x000D_
  background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
  float: left;_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.float-right {_x000D_
  float: right;_x000D_
  width: 60px;_x000D_
  height: 120px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.clear-left {_x000D_
  clear: left;_x000D_
  background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="float-right">float: right;</div>_x000D_
<div class="clear-left">clear: left;</div>
_x000D_
_x000D_
_x000D_

clear: right; Element pushed below right floated elements

_x000D_
_x000D_
body {_x000D_
  font-family: monospace;_x000D_
  background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
  float: left;_x000D_
  width: 60px;_x000D_
  height: 120px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.float-right {_x000D_
  float: right;_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.clear-right {_x000D_
  clear: right;_x000D_
  background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="float-right">float: right;</div>_x000D_
<div class="clear-right">clear: right;</div>
_x000D_
_x000D_
_x000D_

clear: both; Element pushed below all floated elements

_x000D_
_x000D_
body {_x000D_
  font-family: monospace;_x000D_
  background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
  float: left;_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.float-right {_x000D_
  float: right;_x000D_
  width: 60px;_x000D_
  height: 60px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.clear-both {_x000D_
  clear: both;_x000D_
  background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="float-right">float: right;</div>_x000D_
<div class="clear-both">clear: both;</div>
_x000D_
_x000D_
_x000D_

clear does not affect floats outside the current block formatting context

_x000D_
_x000D_
body {_x000D_
  font-family: monospace;_x000D_
  background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
  float: left;_x000D_
  width: 60px;_x000D_
  height: 120px;_x000D_
  background: #CEF;_x000D_
}_x000D_
.inline-block {_x000D_
  display: inline-block;_x000D_
  background: #BDF;_x000D_
}_x000D_
.inline-block .float-left {_x000D_
  height: 60px;_x000D_
}_x000D_
.clear-both {_x000D_
  clear: both;_x000D_
  background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="inline-block">_x000D_
  <div>display: inline-block;</div>_x000D_
  <div class="float-left">float: left;</div>_x000D_
  <div class="clear-both">clear: both;</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to show imageView full screen on imageView click?

Yes I got the trick.

public void onClick(View v) {

            if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH ){
                imgDisplay.setSystemUiVisibility( View.SYSTEM_UI_FLAG_HIDE_NAVIGATION );

            }
            else if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB )
                imgDisplay.setSystemUiVisibility( View.STATUS_BAR_HIDDEN );
            else{}

    }

But it didn't solve my problem completely. I want to hide the horizontal scrollview too, which is in front of the imageView (below), which can't be hidden in this.

Tesseract OCR simple example

I had same problem, now its resolved. I have tesseract2, under this folders for 32 bit and 64 bit, I copied files 64 bit folder(as my system is 64 bit) to main folder ("Tesseract2") and under bin/Debug folder. Now my solution is working fine.

Comment shortcut Android Studio

Ctrl + Shift + / works well for me on Windows.

How to install Ruby 2.1.4 on Ubuntu 14.04

First of all, install the prerequisite libraries:

sudo apt-get update
sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties libffi-dev

Then install rbenv, which is used to install Ruby:

cd
git clone https://github.com/rbenv/rbenv.git ~/.rbenv
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
exec $SHELL

git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build
echo 'export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"' >> ~/.bashrc
exec $SHELL

rbenv install 2.3.1
rbenv global 2.3.1
ruby -v

Then (optional) tell Rubygems to not install local documentation:

echo "gem: --no-ri --no-rdoc" > ~/.gemrc

Credits: https://gorails.com/setup/ubuntu/14.10

Warning!!! There are issues with Gnome-Shell. See comment below.

Delete cookie by name?

In my case I used blow code for different environment.

  document.cookie = name +`=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;Domain=.${document.domain.split('.').splice(1).join('.')}`;

Executing multiple SQL queries in one statement with PHP

Pass 65536 to mysql_connect as 5th parameter.

Example:

$conn = mysql_connect('localhost','username','password', true, 65536 /* here! */) 
    or die("cannot connect");
mysql_select_db('database_name') or die("cannot use database");
mysql_query("
    INSERT INTO table1 (field1,field2) VALUES(1,2);

    INSERT INTO table2 (field3,field4,field5) VALUES(3,4,5);

    DELETE FROM table3 WHERE field6 = 6;

    UPDATE table4 SET field7 = 7 WHERE field8 = 8;

    INSERT INTO table5
       SELECT t6.field11, t6.field12, t7.field13
       FROM table6 t6
       INNER JOIN table7 t7 ON t7.field9 = t6.field10;

    -- etc
");

When you are working with mysql_fetch_* or mysql_num_rows, or mysql_affected_rows, only the first statement is valid.

For example, the following codes, the first statement is INSERT, you cannot execute mysql_num_rows and mysql_fetch_*. It is okay to use mysql_affected_rows to return how many rows inserted.

$conn = mysql_connect('localhost','username','password', true, 65536) or die("cannot connect");
mysql_select_db('database_name') or die("cannot use database");
mysql_query("
    INSERT INTO table1 (field1,field2) VALUES(1,2);
    SELECT * FROM table2;
");

Another example, the following codes, the first statement is SELECT, you cannot execute mysql_affected_rows. But you can execute mysql_fetch_assoc to get a key-value pair of row resulted from the first SELECT statement, or you can execute mysql_num_rows to get number of rows based on the first SELECT statement.

$conn = mysql_connect('localhost','username','password', true, 65536) or die("cannot connect");
mysql_select_db('database_name') or die("cannot use database");
mysql_query("
    SELECT * FROM table2;
    INSERT INTO table1 (field1,field2) VALUES(1,2);
");

How to create nonexistent subdirectories recursively using Bash?

While existing answers definitely solve the purpose, if your'e looking to replicate nested directory structure under two different subdirectories, then you can do this

mkdir -p {main,test}/{resources,scala/com/company}

It will create following directory structure under the directory from where it is invoked

+-- main
¦   +-- resources
¦   +-- scala
¦       +-- com
¦           +-- company
+-- test
    +-- resources
    +-- scala
        +-- com
            +-- company

The example was taken from this link for creating SBT directory structure

How to use border with Bootstrap

There's a property in CSS called box-sizing. It determines the total width of an element on your page. The default value is content-box, which doesn't include the padding, margin, or border of the element.

Hence, if you set a div to have width: 500px and 20px padding all around, it will take up 540px on your website (500 + 20 + 20).

This is what is causing your problem. Bootstrap calculates set widths for things just like the above example, and these things don't have borders. Since Bootstrap fits together like a puzzle, adding a border to one of the sides would yield a total width of 501px (continuing the above example) and break your layout.

The easiest way to fix this is to adjust your box-sizing. The value you would use is box-sizing: border-box. This includes the padding and border in your box elements. You can read more about box-sizing here.

A problem with this solution is that it only works on IE8+. Consequently, if you need deeper IE support you'll need to override the Bootstrap widths to account for your border.

To give an example of how to calculate a new width, begin by checking the width that Bootstrap sets on your element. Let's say it's a span6 and has a width of 320px (this is purely hypothetical, the actual width of your span6 will depend on your specific configuration of Bootstrap). If you wanted to add a single border on the right hand side with a 20px padding over there, you'd write this CSS in your stylesheet

.span6 {
  padding-right: 20px;
  border-right: 1px solid #ddd;
  width: 299px;
 }

where the new width is calculated by:

old width - padding - border

How can I check if a string represents an int, without using try/except?

I guess the question is related with speed since the try/except has a time penalty:

 test data

First, I created a list of 200 strings, 100 failing strings and 100 numeric strings.

from random import shuffle
numbers = [u'+1'] * 100
nonumbers = [u'1abc'] * 100
testlist = numbers + nonumbers
shuffle(testlist)
testlist = np.array(testlist)

 numpy solution (only works with arrays and unicode)

np.core.defchararray.isnumeric can also work with unicode strings np.core.defchararray.isnumeric(u'+12') but it returns and array. So, it's a good solution if you have to do thousands of conversions and have missing data or non numeric data.

import numpy as np
%timeit np.core.defchararray.isnumeric(testlist)
10000 loops, best of 3: 27.9 µs per loop # 200 numbers per loop

try/except

def check_num(s):
  try:
    int(s)
    return True
  except:
    return False

def check_list(l):
  return [check_num(e) for e in l]

%timeit check_list(testlist)
1000 loops, best of 3: 217 µs per loop # 200 numbers per loop

Seems that numpy solution is much faster.

How do I get the Date & Time (VBS)

To expound on Numenor's answer you can do something like, Format(Now(),"HH:mm:ss") using these custom date/time formating options


For everyone who is tempted to downvote this answer please be aware that the question was originally tagged VB and vbscript hence my answer, the VB tag was edited out leaving only the vbscript tag. The OP accepted this answer which I take to mean that it gave him the information that he needed.

How to set width to 100% in WPF

It is the container of the Grid that is imposing on its width. In this case, that's a ListBoxItem, which is left-aligned by default. You can set it to stretch as follows:

<ListBox>
    <!-- other XAML omitted, you just need to add the following bit -->
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="HorizontalAlignment" Value="Stretch"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

jQuery - find child with a specific class

Based on your comment, moddify this:

$( '.bgHeaderH2' ).html (); // will return whatever is inside the DIV

to:

$( '.bgHeaderH2', $( this ) ).html (); // will return whatever is inside the DIV

More about selectors: https://api.jquery.com/category/selectors/

How do you round a floating point number in Perl?

If you decide to use printf or sprintf, note that they use the Round half to even method.

foreach my $i ( 0.5, 1.5, 2.5, 3.5 ) {
    printf "$i -> %.0f\n", $i;
}
__END__
0.5 -> 0
1.5 -> 2
2.5 -> 2
3.5 -> 4

How to use if statements in LESS

I stumbled over the same question and I've found a solution.

First make sure you upgrade to LESS 1.6 at least. You can use npm for that case.

Now you can use the following mixin:

.if (@condition, @property, @value) when (@condition = true){
     @{property}: @value;
 }

Since LESS 1.6 you are able to pass PropertyNames to Mixins as well. So for example you could just use:

.myHeadline {
   .if(@include-lineHeight,  line-height, '35px');
}

If @include-lineheight resolves to true LESS will print the line-height: 35px and it will skip the mixin if @include-lineheight is not true.

How SQL query result insert in temp table?

Look at SELECT INTO. This will create a new table for you, which can be temporary if you want by prefixing the table name with a pound sign (#).

For example, you can do:

SELECT * 
INTO #YourTempTable
FROM YourReportQuery

Print a string as hex bytes?

Print a string as hex bytes?

The accepted answer gives:

s = "Hello world !!"
":".join("{:02x}".format(ord(c)) for c in s)

returns:

'48:65:6c:6c:6f:20:77:6f:72:6c:64:20:21:21'

The accepted answer works only so long as you use bytes (mostly ascii characters). But if you use unicode, e.g.:

a_string = u"?????? ???!!" # "Prevyet mir", or "Hello World" in Russian.

You need to convert to bytes somehow.

If your terminal doesn't accept these characters, you can decode from UTF-8 or use the names (so you can paste and run the code along with me):

a_string = (
    "\N{CYRILLIC CAPITAL LETTER PE}"
    "\N{CYRILLIC SMALL LETTER ER}"
    "\N{CYRILLIC SMALL LETTER I}"
    "\N{CYRILLIC SMALL LETTER VE}"
    "\N{CYRILLIC SMALL LETTER IE}"
    "\N{CYRILLIC SMALL LETTER TE}"
    "\N{SPACE}"
    "\N{CYRILLIC SMALL LETTER EM}"
    "\N{CYRILLIC SMALL LETTER I}"
    "\N{CYRILLIC SMALL LETTER ER}"
    "\N{EXCLAMATION MARK}"
    "\N{EXCLAMATION MARK}"
)

So we see that:

":".join("{:02x}".format(ord(c)) for c in a_string)

returns

'41f:440:438:432:435:442:20:43c:438:440:21:21'

a poor/unexpected result - these are the code points that combine to make the graphemes we see in Unicode, from the Unicode Consortium - representing languages all over the world. This is not how we actually store this information so it can be interpreted by other sources, though.

To allow another source to use this data, we would usually need to convert to UTF-8 encoding, for example, to save this string in bytes to disk or to publish to html. So we need that encoding to convert the code points to the code units of UTF-8 - in Python 3, ord is not needed because bytes are iterables of integers:

>>> ":".join("{:02x}".format(c) for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'

Or perhaps more elegantly, using the new f-strings (only available in Python 3):

>>> ":".join(f'{c:02x}' for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'

In Python 2, pass c to ord first, i.e. ord(c) - more examples:

>>> ":".join("{:02x}".format(ord(c)) for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'
>>> ":".join(format(ord(c), '02x') for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'

Cross browser JavaScript (not jQuery...) scroll to top animation

function scrollTo(element, to, duration) {
    if (duration <= 0) return;
    var difference = to - element.scrollTop;
    var perTick = difference / duration * 10;

    setTimeout(function() {
        element.scrollTop = element.scrollTop + perTick;
        if (element.scrollTop === to) return;
        scrollTo(element, to, duration - 10);
    }, 10);
}

Demo:

_x000D_
_x000D_
function runScroll() {_x000D_
  scrollTo(document.body, 0, 600);_x000D_
}_x000D_
var scrollme;_x000D_
scrollme = document.querySelector("#scrollme");_x000D_
scrollme.addEventListener("click",runScroll,false)_x000D_
_x000D_
function scrollTo(element, to, duration) {_x000D_
  if (duration <= 0) return;_x000D_
  var difference = to - element.scrollTop;_x000D_
  var perTick = difference / duration * 10;_x000D_
_x000D_
  setTimeout(function() {_x000D_
    element.scrollTop = element.scrollTop + perTick;_x000D_
    if (element.scrollTop == to) return;_x000D_
    scrollTo(element, to, duration - 10);_x000D_
  }, 10);_x000D_
}
_x000D_
<p>Very long page.Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page.  Very long page.Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page.  Very long page.Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page.  Very long page.Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page.  Very long page.Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page._x000D_
</p>_x000D_
<button id=scrollme type="button">To the top</button>
_x000D_
_x000D_
_x000D_

Set Font Color, Font Face and Font Size in PHPExcel

I recommend you start reading the documentation (4.6.18. Formatting cells). When applying a lot of formatting it's better to use applyFromArray() According to the documentation this method is also suppose to be faster when you're setting many style properties. There's an annex where you can find all the possible keys for this function.

This will work for you:

$phpExcel = new PHPExcel();

$styleArray = array(
    'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));

$phpExcel->getActiveSheet()->getCell('A1')->setValue('Some text');
$phpExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);

To apply font style to complete excel document:

 $styleArray = array(
   'font'  => array(
        'bold'  => true,
        'color' => array('rgb' => 'FF0000'),
        'size'  => 15,
        'name'  => 'Verdana'
    ));      
 $phpExcel->getDefaultStyle()
    ->applyFromArray($styleArray);

Fixed size div?

This is a fairly trivial effect to accomplish. One way to achieve this is to simply place floated div elements within a common parent container, and set their width and height. In order to clear the floated elements, we set the overflow property of the parent.

<div class="container">
    <div class="cube">do</div>
    <div class="cube">ray</div>
    <div class="cube">me</div>
    <div class="cube">fa</div>
    <div class="cube">so</div>
    <div class="cube">la</div>
    <div class="cube">te</div>
    <div class="cube">do</div>
</div>

The CSS resembles the strategy outlined in the first paragraph above:

.container {
    width: 450px;
    overflow: auto;
}

.cube {
    float: left;
    width: 150px; 
    height: 150px;
}

You can see the end result here: http://jsfiddle.net/Qjum2/2/

Browsers that support pseudo elements provide an alternative way to clear:

.container::after {
    content: "";
    clear: both;
    display: block;
}

You can see the results here: http://jsfiddle.net/Qjum2/3/

I hope this helps.

How to read data from a zip file without having to unzip the entire file

In such case you will need to parse zip local header entries. Each file, stored in zip file, has preceding Local File Header entry, which (normally) contains enough information for decompression, Generally, you can make simple parsing of such entries in stream, select needed file, copy header + compressed file data to other file, and call unzip on that part (if you don't want to deal with the whole Zip decompression code or library).

What size should apple-touch-icon.png be for iPad and iPhone?

Updated list December 2019, iOS13 One icon for iOS 180x180 px and one for android 192x192 px (declared in site.webmanifest).

<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="manifest" href="/site.webmanifest">
#### site.webmanifest
{
    "name": "",
    "short_name": "",
    "icons": [
        {
            "src": "/android-chrome-192x192.png",
            "sizes": "192x192",
            "type": "image/png"
        }
    ],
    "display": "standalone"
}

Deprecated list October 2017, iOS11

List for iPhone and iPad with and without retina

<!-- iPhone(first generation or 2G), iPhone 3G, iPhone 3GS -->
<link rel="apple-touch-icon" sizes="57x57" href="touch-icon-iphone.png">
<!-- iPad and iPad mini @1x -->
<link rel="apple-touch-icon" sizes="76x76" href="touch-icon-ipad.png">
<!-- iPhone 4, iPhone 4s, iPhone 5, iPhone 5c, iPhone 5s, iPhone 6, iPhone 6s, iPhone 7, iPhone 7s, iPhone8 -->
<link rel="apple-touch-icon" sizes="120x120" href="touch-icon-iphone-retina.png">
<!-- iPad and iPad mini @2x -->
<link rel="apple-touch-icon" sizes="152x152" href="touch-icon-ipad-retina.png">
<!-- iPad Pro -->
<link rel="apple-touch-icon" sizes="167x167" href="touch-icon-ipad-pro.png">
<!-- iPhone X, iPhone 8 Plus, iPhone 7 Plus, iPhone 6s Plus, iPhone 6 Plus -->
<link rel="apple-touch-icon" sizes="180x180" href="touch-icon-iphone-6-plus.png">
<!-- Android Devices High Resolution -->
<link rel="icon" sizes="192x192" href="icon-hd.png">
<!-- Android Devices Normal Resolution -->
<link rel="icon" sizes="128x128" href="icon.png">

Update Oct 2017 iOS 11: iOS 11 checked, iPhone X and iPhone 8 introduced

Update Nov 2016 iOS 10: New iOS version iPhone 7 and iPhone 7plus introduced, they have the same display resolution, dpi, etc as iPhone 6s and iPhone 7plus, until now no changes found respecting the update 2015

Update Mid 2016 Android: Add Android Devices to the list as the apple-touch links are marked as deprecated by Google and will be not supported anytime for their devices

<!-- Android Devices High Resolution -->
<link rel="icon" sizes="192x192" href="icon-hd.png">
<!-- Android Devices High Resolution -->
<link rel="icon" sizes="128x128" href="icon.png">

Update 2015 iOS 9: For iOS 9 and iPad pro

<link rel="apple-touch-icon" sizes="167x167" href="touch-icon-ipad-pro.png">

The new iPhones (6s and 6s Plus) are using the same sizes as the iPhone(6 and 6 Plus), the new iPad pro uses an image of size 167x167 px, the other resolutions are still the same.

Update 2014 iOS 8:

For iOS 8 and iPhone 6 plus

<link rel="apple-touch-icon" sizes="180x180" href="touch-icon-iphone-6-plus.png"> 

Iphone 6 uses the same 120 x 120 px image as iphone 4 and 5 the rest is the same as for iOS 7

Update 2013 iOS7:

For iOS 7 the recommended resolutions changed:

  • for iPhone Retina from 114 x 114 px to 120 x 120 px
  • for iPad Retina from 144 x 144 px to 152 x 152 px

The other resolution are still the same

  • 57 x 57 px default
  • 76 x 76 px for iPads without retina

Source: https://developer.apple.com/ios/human-interface-guidelines/icons-and-images/app-icon/

Jquery Ajax, return success/error from mvc.net controller

Use Json class instead of Content as shown following:

    //  When I want to return an error:
    if (!isFileSupported)
    {
        Response.StatusCode = (int) HttpStatusCode.BadRequest;
        return Json("The attached file is not supported", MediaTypeNames.Text.Plain);
    }
    else
    {
        //  When I want to return sucess:
        Response.StatusCode = (int)HttpStatusCode.OK; 
        return Json("Message sent!", MediaTypeNames.Text.Plain);
    }

Also set contentType:

contentType: 'application/json; charset=utf-8',

String comparison in Objective-C

You can compare string with below functions.

NSString *first = @"abc";
NSString *second = @"abc";
NSString *third = [[NSString alloc] initWithString:@"abc"];
NSLog(@"%d", (second == third))  
NSLog(@"%d", (first == second)); 
NSLog(@"%d", [first isEqualToString:second]); 
NSLog(@"%d", [first isEqualToString:third]); 

Output will be :-
    0
    1
    1
    1

Incorrect string value: '\xF0\x9F\x8E\xB6\xF0\x9F...' MySQL

FOR SQLALCHEMY AND PYTHON

The encoding used for Unicode has traditionally been 'utf8'. However, for MySQL versions 5.5.3 on forward, a new MySQL-specific encoding 'utf8mb4' has been introduced, and as of MySQL 8.0 a warning is emitted by the server if plain utf8 is specified within any server-side directives, replaced with utf8mb3. The rationale for this new encoding is due to the fact that MySQL’s legacy utf-8 encoding only supports codepoints up to three bytes instead of four. Therefore, when communicating with a MySQL database that includes codepoints more than three bytes in size, this new charset is preferred, if supported by both the database as well as the client DBAPI, as in:

e = create_engine(
    "mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4")
All modern DBAPIs should support the utf8mb4 charset.

enter link description here

How can I style an Android Switch?

It's an awesome detailed reply by Janusz. But just for the sake of people who are coming to this page for answers, the easier way is at http://android-holo-colors.com/ (dead link) linked from Android Asset Studio

A good description of all the tools are at AndroidOnRocks.com (site offline now)

However, I highly recommend everybody to read the reply from Janusz as it will make understanding clearer. Use the tool to do stuffs real quick

Export html table data to Excel using JavaScript / JQuery is not working properly in chrome browser

You can use tableToExcel.js to export table in excel file.

This works in a following way :

1). Include this CDN in your project/file

<script src="https://cdn.jsdelivr.net/gh/linways/[email protected]/dist/tableToExcel.js"></script>

2). Either Using JavaScript:

<button id="btnExport" onclick="exportReportToExcel(this)">EXPORT REPORT</button>

function exportReportToExcel() {
  let table = document.getElementsByTagName("table"); // you can use document.getElementById('tableId') as well by providing id to the table tag
  TableToExcel.convert(table[0], { // html code may contain multiple tables so here we are refering to 1st table tag
    name: `export.xlsx`, // fileName you could use any name
    sheet: {
      name: 'Sheet 1' // sheetName
    }
  });
}

3). Or by Using Jquery

<button id="btnExport">EXPORT REPORT</button>

$(document).ready(function(){
    $("#btnExport").click(function() {
        let table = document.getElementsByTagName("table");
        TableToExcel.convert(table[0], { // html code may contain multiple tables so here we are refering to 1st table tag
           name: `export.xlsx`, // fileName you could use any name
           sheet: {
              name: 'Sheet 1' // sheetName
           }
        });
    });
});

You may refer to this github link for any other information

https://github.com/linways/table-to-excel/tree/master

or for referring the live example visit the following link

https://codepen.io/rohithb/pen/YdjVbb

Hope this will help someone :-)

Converting newline formatting from Mac to Windows

Windows uses carriage return + line feed for newline:

\r\n

Unix only uses Line feed for newline:

\n

In conclusion, simply replace every occurence of \n by \r\n.
Both unix2dos and dos2unix are not by default available on Mac OSX.
Fortunately, you can simply use Perl or sed to do the job:

sed -e 's/$/\r/' inputfile > outputfile                # UNIX to DOS  (adding CRs)
sed -e 's/\r$//' inputfile > outputfile                # DOS  to UNIX (removing CRs)
perl -pe 's/\r\n|\n|\r/\r\n/g' inputfile > outputfile  # Convert to DOS
perl -pe 's/\r\n|\n|\r/\n/g'   inputfile > outputfile  # Convert to UNIX
perl -pe 's/\r\n|\n|\r/\r/g'   inputfile > outputfile  # Convert to old Mac

Code snippet from:
http://en.wikipedia.org/wiki/Newline#Conversion_utilities

How to use PDO to fetch results array in PHP?

There are three ways to fetch multiple rows returned by PDO statement.

The simplest one is just to iterate over PDOStatement itself:

$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// iterating over a statement
foreach($stmt as $row) {
    echo $row['name'];
}

another one is to fetch rows using fetch() method inside a familiar while statement:

$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// using while
while($row = $stmt->fetch()) {
    echo $row['name'];
}

but for the modern web application we should have our datbase iteractions separated from output and thus the most convenient method would be to fetch all rows at once using fetchAll() method:

$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// fetching rows into array
$data = $stmt->fetchAll();

or, if you need to preprocess some data first, use the while loop and collect the data into array manually

$result = [];
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// using while
while($row = $stmt->fetch()) {
    $result[] = [
        'newname' => $row['oldname'],
        // etc
    ];
}

and then output them in a template:

<ul>
<?php foreach($data as $row): ?>
    <li><?=$row['name']?></li>
<?php endforeach ?>
</ul>

Note that PDO supports many sophisticated fetch modes, allowing fetchAll() to return data in many different formats.

Removing an element from an Array (Java)

Some more pre-conditions are needed for the ones written by Bill K and dadinn

Object[] newArray = new Object[src.length - 1];
if (i > 0){
    System.arraycopy(src, 0, newArray, 0, i);
}

if (newArray.length > i){
    System.arraycopy(src, i + 1, newArray, i, newArray.length - i);
}

return newArray;

Extracting an attribute value with beautifulsoup

I am using this with Beautifulsoup 4.8.1 to get the value of all class attributes of certain elements:

from bs4 import BeautifulSoup

html = "<td class='val1'/><td col='1'/><td class='val2' />"

bsoup = BeautifulSoup(html, 'html.parser')

for td in bsoup.find_all('td'):
    if td.has_attr('class'):
        print(td['class'][0])

Its important to note that the attribute key retrieves a list even when the attribute has only a single value.

How to select all the columns of a table except one column?

This is not a generic solution, but some databases allow you to use regular expressions to specify the columns.

For instance, in the case of Hive, the following query selects all columns except ds and hr:

SELECT `(ds|hr)?+.+` FROM sales

https://cwiki.apache.org/confluence/display/Hive/LanguageManual+Select#LanguageManualSelect-REGEXColumnSpecification

How to set up googleTest as a shared library on Linux

I was similarly underwhelmed by this situation and ended up making my own Ubuntu source packages for this. These source packages allow you to easily produce a binary package. They are based on the latest gtest & gmock source as of this post.

Google Test DEB Source Package

Google Mock DEB Source Package

To build the binary package do this:

tar -xzvf gtest-1.7.0.tar.gz
cd gtest-1.7.0
dpkg-source -x gtest_1.7.0-1.dsc
cd gtest-1.7.0
dpkg-buildpackage

It may tell you that you need some pre-requisite packages in which case you just need to apt-get install them. Apart from that, the built .deb binary packages should then be sitting in the parent directory.

For GMock, the process is the same.

As a side note, while not specific to my source packages, when linking gtest to your unit test, ensure that gtest is included first (https://bbs.archlinux.org/viewtopic.php?id=156639) This seems like a common gotcha.

Print Currency Number Format in PHP

PHP has a function called money_format for doing this. Read about this here.

C++ Get name of type in template

I just leave it there. If someone will still need it, then you can use this:

template <class T>
bool isString(T* t) { return false;  } // normal case returns false

template <>
bool isString(char* t) { return true; }  // but for char* or String.c_str() returns true
.
.
.

This will only CHECK type not GET it and only for 1 type or 2.

displayname attribute vs display attribute

They both give you the same results but the key difference I see is that you cannot specify a ResourceType in DisplayName attribute. For an example in MVC 2, you had to subclass the DisplayName attribute to provide resource via localization. Display attribute (new in MVC3 and .NET4) supports ResourceType overload as an "out of the box" property.

Cannot open local file - Chrome: Not allowed to load local resource

Google Chrome does not allow to load local resources because of the security. Chrome need http url. Internet Explorer and Edge allows to load local resources, but Safari, Chrome, and Firefox doesn't allows to load local resources.

Go to file location and start the Python Server from there.

python -m SimpleHttpServer

then put that url into function:

function run(){
var URL = "http://172.271.1.20:8000/" /* http://0.0.0.0:8000/ or http://127.0.0.1:8000/; */
window.open(URL, null);
}

Shell Script — Get all files modified after <date>

You can do this directly with tar and even better:

tar -N '2014-02-01 18:00:00' -jcvf archive.tar.bz2 files

This instructs tar to compress files newer than 1st of January 2014, 18:00:00.

sqlite3.OperationalError: unable to open database file

I faced exactly same issue. Here is my setting which worked.

'ENGINE': 'django.db.backends.sqlite3', 
'NAME': '/home/path/to/your/db/data.sqlite3'

Other setting in case of sqlite3 will be same/default.
And you need to create data.sqlite3.

Capturing TAB key in text box

I would advise against changing the default behaviour of a key. I do as much as possible without touching a mouse, so if you make my tab key not move to the next field on a form I will be very aggravated.

A shortcut key could be useful however, especially with large code blocks and nesting. Shift-TAB is a bad option because that normally takes me to the previous field on a form. Maybe a new button on the WMD editor to insert a code-TAB, with a shortcut key, would be possible?

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

Simpal an easy In my case it solved by as below

enter image description here

Make sure your pakage name in mainifests file same as your gradle's applicationId.

Cross Domain Form POSTing

It is possible to build an arbitrary GET or POST request and send it to any server accessible to a victims browser. This includes devices on your local network, such as Printers and Routers.

There are many ways of building a CSRF exploit. A simple POST based CSRF attack can be sent using .submit() method. More complex attacks, such as cross-site file upload CSRF attacks will exploit CORS use of the xhr.withCredentals behavior.

CSRF does not violate the Same-Origin Policy For JavaScript because the SOP is concerned with JavaScript reading the server's response to a clients request. CSRF attacks don't care about the response, they care about a side-effect, or state change produced by the request, such as adding an administrative user or executing arbitrary code on the server.

Make sure your requests are protected using one of the methods described in the OWASP CSRF Prevention Cheat Sheet. For more information about CSRF consult the OWASP page on CSRF.

How to select multiple files with <input type="file">?

There is also HTML5 <input type="file[]" multiple /> (specification).

Browser support is quite good on desktop (just not supported by IE 9 and prior), less good on mobile, I guess because it's harder to implement correctly depending on the platform and version.

How to set text color to a text view programmatically

Use,..

Color.parseColor("#bdbdbd");

like,

mTextView.setTextColor(Color.parseColor("#bdbdbd"));

Or if you have defined color code in resource's color.xml file than

(From API >= 23)

mTextView.setTextColor(ContextCompat.getColor(context, R.color.<name_of_color>));

(For API < 23)

mTextView.setTextColor(getResources().getColor(R.color.<name_of_color>));

How do I exclude all instances of a transitive dependency when using Gradle?

Your approach is correct. (Depending on the circumstances, you might want to use configurations.all { exclude ... }.) If these excludes really exclude more than a single dependency (I haven't ever noticed that when using them), please file a bug at http://forums.gradle.org, ideally with a reproducible example.

How to test an Internet connection with bash?

Ping your default gateway:

#!/bin/bash
ping -q -w 1 -c 1 `ip r | grep default | cut -d ' ' -f 3` > /dev/null && echo ok || echo error

Is there a TRY CATCH command in Bash

You can do:

#!/bin/bash
if <command> ; then # TRY
    <do-whatever-you-want>
else # CATCH
    echo 'Exception'
    <do-whatever-you-want>
fi

Validation of file extension before uploading file

I came here because I was sure none of the answers here were quite...poetic:

_x000D_
_x000D_
function checkextension() {_x000D_
  var file = document.querySelector("#fUpload");_x000D_
  if ( /\.(jpe?g|png|gif)$/i.test(file.files[0].name) === false ) { alert("not an image!"); }_x000D_
}
_x000D_
<input type="file" id="fUpload" onchange="checkextension()"/>
_x000D_
_x000D_
_x000D_

Error: No module named psycopg2.extensions

This error raise because you not install postgres database in you project virtutal environment. you should run one of these command. from a terminal you can you command for sudo.

sudo apt-get install build-dep python-psycopg2

for pip (pip basically work for python)

pip install psycopg2

or

pip3 install psycopg2-binary

i'm pretty sure it will work for you.

HTTP response header content disposition for attachments

neither use inline; nor attachment; just use

response.setContentType("text/xml");
response.setHeader( "Content-Disposition", "filename=" + filename );

or

response.setHeader( "Content-Disposition", "filename=\"" + filename + "\"" );

or

response.setHeader( "Content-Disposition", "filename=\"" + 
  filename.substring(0, filename.lastIndexOf('.')) + "\"");

href image link download on click

The easiest way of creating download link for image or html is setting download attribute, but this solution works in modern browsers only.

<a href="/path/to/image" download="myimage"><img src="/path/to/image" /></a>

"myimage" is a name of file to download. Extension will be added automatically Example here

How can I use regex to get all the characters after a specific character, e.g. comma (",")

Short answer

Either:

  • ,[\s\S]*$ or ,.*$ to match everything after the first comma (see explanation for which one to use); or

  • [^,]*$ to match everything after the last comma (which is probably what you want).

You can use, for example, /[^,]*/.exec(s)[0] in JavaScript, where s is the original string. If you wanted to use multiline mode and find all matches that way, you could use s.match(/[^,]*/mg) to get an array (if you have more than one of your posted example lines in the variable on separate lines).

Explanation

  • [\s\S] is a character class that matches both whitespace and non-whitespace characters (i.e. all of them). This is different from . in that it matches newlines.
  • [^,] is a negated character class that matches everything except for commas.
  • * means that the previous item can repeat 0 or more times.
  • $ is the anchor that requires that the end of the match be at the end of the string (or end of line if using the /m multiline flag).

For the first match, the first regex finds the first comma , and then matches all characters afterward until the end of line [\s\S]*$, including commas.

The second regex matches as many non-comma characters as possible before the end of line. Thus, the entire match will be after the last comma.

How do I select child elements of any depth using XPath?

Also, you can do it with css selectors:

form#myform input[type='submit']

space beween elements in css elector means searching input[type='submit'] that elements at any depth of parent form#myform element

Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' with pdo

I got the same error, on debian6, when I had not yet installed php5-mysql.

So I installed it, then restarted apache2

apt-get install php5-mysql
/etc/init.d/apache2 restart

Then the error went away.

If you have the same error on Ubuntu, instead of:

/etc/init.d/apache2 restart  

Type:

service apache2 restart

Eclipse Build Path Nesting Errors

I had the same issue and correct answer above did not work for me. What I did to resolve it was to go to Build Path->Configure Build Path and under the source tab I removed all the sources (which only had one source) and reconfigured them from there. I ended up removing the project from eclipse and import the maven project again in order to clear up the error.

How to check whether a select box is empty using JQuery/Javascript

One correct way to get selected value would be

var selected_value = $('#fruit_name').val()

And then you should do

if(selected_value) { ... }

List files in local git repo?

This command:

git ls-tree --full-tree -r --name-only HEAD

lists all of the already committed files being tracked by your git repo.

How to check if all list items have the same value and return it, or return an “otherValue” if they don’t?

var val = yyy.First().Value;
return yyy.All(x=>x.Value == val) ? val : otherValue; 

Cleanest way I can think of. You can make it a one-liner by inlining val, but First() would be evaluated n times, doubling execution time.

To incorporate the "empty set" behavior specified in the comments, you simply add one more line before the two above:

if(yyy == null || !yyy.Any()) return otherValue;