Programs & Examples On #Initwithcontentsoffile

Use NSInteger as array index

According to the error message, you declared myLoc as a pointer to an NSInteger (NSInteger *myLoc) rather than an actual NSInteger (NSInteger myLoc). It needs to be the latter.

How do I get a plist as a Dictionary in Swift?

Simple struct to access plist file (Swift 2.0)

struct Configuration {      
  static let path = NSBundle.mainBundle().pathForResource("Info", ofType: "plist")!
  static let dict = NSDictionary(contentsOfFile: path) as! [String: AnyObject]

  static let someValue = dict["someKey"] as! String
}

Usage:

print("someValue = \(Configuration.someValue)")

Compiler error: "initializer element is not a compile-time constant"

Because you are asking the compiler to initialize a static variable with code that is inherently dynamic.

VBA Object doesn't support this property or method

Object doesn't support this property or method.

Think of it like if anything after the dot is called on an object. It's like a chain.

An object is a class instance. A class instance supports some properties defined in that class type definition. It exposes whatever intelli-sense in VBE tells you (there are some hidden members but it's not related to this). So after each dot . you get intelli-sense (that white dropdown) trying to help you pick the correct action.

(you can start either way - front to back or back to front, once you understand how this works you'll be able to identify where the problem occurs)

Type this much anywhere in your code area

Dim a As Worksheets
a.

you get help from VBE, it's a little dropdown called Intelli-sense

enter image description here

It lists all available actions that particular object exposes to any user. You can't see the .Selection member of the Worksheets() class. That's what the error tells you exactly.

Object doesn't support this property or method.

If you look at the example on MSDN

Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count

It activates the sheet first then calls the Selection... it's not connected together because Selection is not a member of Worksheets() class. Simply, you can't prefix the Selection

What about

Sub DisplayColumnCount()
    Dim iAreaCount As Integer
    Dim i As Integer

    Worksheets("GRA").Activate
    iAreaCount = Selection.Areas.Count

    If iAreaCount <= 1 Then
        MsgBox "The selection contains " & Selection.Columns.Count & " columns."
    Else
        For i = 1 To iAreaCount
        MsgBox "Area " & i & " of the selection contains " & _
        Selection.Areas(i).Columns.Count & " columns."
        Next i
    End If
End Sub

from HERE

How to upload a project to Github

What you need it an SSH connection and GitHub init into your project. I will explain under Linux machine.

Let's start with some easy stuff: navigate into your project in the terminal, and use:

git init
git add .
git commit 

now let's add SSH into your machine: use ssh-keygen -t rsa -C "[email protected]" and copy the public key, then add it to your GitHub repo Deploy keys -> add one back to your machine project now launch: git push origin master if there is an error config your .github/config by nano .github/config and change the URL to ssh one by url = [email protected]:username/repo.... and that's it

Just disable scroll not hide it?

Crude but working way will be to force the scroll back to top, thus effectively disabling scrolling:

var _stopScroll = false;
window.onload = function(event) {
    document.onscroll = function(ev) {
        if (_stopScroll) {
            document.body.scrollTop = "0px";
        }
    }
};

When you open the lightbox raise the flag and when closing it,lower the flag.

Live test case.

What does it mean when an HTTP request returns status code 0?

In my case, it was because the AJAX call was being blocked by the browser because of the same-origin policy. It was the least expected thing, because all my HTMLs and scripts where being served from 127.0.0.1. How could they be considered as having different origins?

Anyway, the root cause was an innocent-looking <base> tag:

<base href='<%=request.getScheme()%>://<%=request.getServerName() + ":" + request.getServerPort() + request.getContextPath()%>/'/>

I removed the <base> tag, which I did not need by the way, and now it works fine!

Difference of keywords 'typename' and 'class' in templates?

  1. No difference
  2. Template type parameter Container is itself a template with two type parameters.

The maximum recursion 100 has been exhausted before statement completion

it is just a sample to avoid max recursion error. we have to use option (maxrecursion 365); or option (maxrecursion 0);

DECLARE @STARTDATE datetime; 
DECLARE @EntDt datetime; 
set @STARTDATE = '01/01/2009';  
set @EntDt = '12/31/2009'; 
declare @dcnt int; 
;with DateList as   
 (   
    select @STARTDATE DateValue   
    union all   
    select DateValue + 1 from    DateList      
    where   DateValue + 1 < convert(VARCHAR(15),@EntDt,101)   
 )   
  select count(*) as DayCnt from (   
  select DateValue,DATENAME(WEEKDAY, DateValue ) as WEEKDAY from DateList
  where DATENAME(WEEKDAY, DateValue ) not IN ( 'Saturday','Sunday' )     
  )a
option (maxrecursion 365);

Regular expression: find spaces (tabs/space) but not newlines

As @Eiríkr Útlendi noted, the accepted solution only considers two white space characters: the horizontal tab (U+0009), and a breaking space (U+0020). It does not consider other whitespace characters such as non-breaking spaces (which happen to be in the text I am trying to deal with). A more complete whitespace character listing is included on Wikipedia and also referenced in the linked Perl answer. A simple C# solution that accounts for these other characters can be built using character class subtraction

[\s-[\r\n]]

or, including Eiríkr Útlendi's solution, you get

[\s\u3000-[\r\n]]

Creating a JSON array in C#

You're close. This should do the trick:

new {items = new [] {
    new {name = "command" , index = "X", optional = "0"}, 
    new {name = "command" , index = "X", optional = "0"}
}}

If your source was an enumerable of some sort, you might want to do this:

new {items = source.Select(item => new 
{
    name = item.Name, index = item.Index, options = item.Optional
})};

How to parse unix timestamp to time.Time

I do a lot of logging where the timestamps are float64 and use this function to get the timestamps as string:

func dateFormat(layout string, d float64) string{
    intTime := int64(d)
    t := time.Unix(intTime, 0)
    if layout == "" {
        layout = "2006-01-02 15:04:05"
    }
    return t.Format(layout)
}

How can I fix assembly version conflicts with JSON.NET after updating NuGet package references in a new ASP.NET MVC 5 project?

Here the steps I used to fix the warning:

  • Unload project in VS
  • Edit .csproj file
  • Search for all references to Newtonsoft.Json assembly
    • Found two, one to v6 and one to v5
    • Replace the reference to v5 with v6
  • Reload project
  • Build and notice assembly reference failure
  • View References and see that there are now two to Newtonsoft.Json. Remove the one that's failing to resolve.
  • Rebuild - no warnings

Adding a y-axis label to secondary y-axis in matplotlib

There is a straightforward solution without messing with matplotlib: just pandas.

Tweaking the original example:

table = sql.read_frame(query,connection)

ax = table[0].plot(color=colors[0],ylim=(0,100))
ax2 = table[1].plot(secondary_y=True,color=colors[1], ax=ax)

ax.set_ylabel('Left axes label')
ax2.set_ylabel('Right axes label')

Basically, when the secondary_y=True option is given (eventhough ax=ax is passed too) pandas.plot returns a different axes which we use to set the labels.

I know this was answered long ago, but I think this approach worths it.

What is the role of "Flatten" in Keras?

I came across this recently, it certainly helped me understand: https://www.cs.ryerson.ca/~aharley/vis/conv/

So there's an input, a Conv2D, MaxPooling2D etc, the Flatten layers are at the end and show exactly how they are formed and how they go on to define the final classifications (0-9).

Math operations from string

If you want to do it safely, you may want to use http://docs.python.org/library/ast.html#ast.literal_eval

from this answer: Python "safe" eval (string to bool/int/float/None/string)

It might not do math, but you could parse the math operators and then operate on safely evaluated terms.

Detect if an element is visible with jQuery

if($('#testElement').is(':visible')){
    //what you want to do when is visible
}

Binary numbers in Python

'''
I expect the intent behind this assignment was to work in binary string format.
This is absolutely doable.
'''

def compare(bin1, bin2):
    return bin1.lstrip('0') == bin2.lstrip('0')

def add(bin1, bin2):
    result = ''
    blen = max((len(bin1), len(bin2))) + 1
    bin1, bin2 = bin1.zfill(blen), bin2.zfill(blen)
    carry_s = '0'
    for b1, b2 in list(zip(bin1, bin2))[::-1]:
        count = (carry_s, b1, b2).count('1')
        carry_s = '1' if count >= 2 else '0'
        result += '1' if count % 2 else '0'
    return result[::-1]

if __name__ == '__main__':
    print(add('101', '100'))

I leave the subtraction func as an exercise for the reader.

Transpose a range in VBA

First copy the source range then paste-special on target range with Transpose:=True, short sample:

Option Explicit

Sub test()
  Dim sourceRange As Range
  Dim targetRange As Range

  Set sourceRange = ActiveSheet.Range(Cells(1, 1), Cells(5, 1))
  Set targetRange = ActiveSheet.Cells(6, 1)

  sourceRange.Copy
  targetRange.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True
End Sub

The Transpose function takes parameter of type Varaiant and returns Variant.

  Sub transposeTest()
    Dim transposedVariant As Variant
    Dim sourceRowRange As Range
    Dim sourceRowRangeVariant As Variant

    Set sourceRowRange = Range("A1:H1") ' one row, eight columns
    sourceRowRangeVariant = sourceRowRange.Value
    transposedVariant = Application.Transpose(sourceRowRangeVariant)

    Dim rangeFilledWithTransposedData As Range
    Set rangeFilledWithTransposedData = Range("I1:I8") ' eight rows, one column
    rangeFilledWithTransposedData.Value = transposedVariant
  End Sub

I will try to explaine the purpose of 'calling transpose twice'. If u have row data in Excel e.g. "a1:h1" then the Range("a1:h1").Value is a 2D Variant-Array with dimmensions 1 to 1, 1 to 8. When u call Transpose(Range("a1:h1").Value) then u get transposed 2D Variant Array with dimensions 1 to 8, 1 to 1. And if u call Transpose(Transpose(Range("a1:h1").Value)) u get 1D Variant Array with dimension 1 to 8.

First Transpose changes row to column and second transpose changes the column back to row but with just one dimension.

If the source range would have more rows (columns) e.g. "a1:h3" then Transpose function just changes the dimensions like this: 1 to 3, 1 to 8 Transposes to 1 to 8, 1 to 3 and vice versa.

Hope i did not confuse u, my english is bad, sorry :-).

How do I find out which keystore was used to sign an app?

First, unzip the APK and extract the file /META-INF/ANDROID_.RSA (this file may also be CERT.RSA, but there should only be one .RSA file).

Then issue this command:

keytool -printcert -file ANDROID_.RSA

You will get certificate fingerprints like this:

     MD5:  B3:4F:BE:07:AA:78:24:DC:CA:92:36:FF:AE:8C:17:DB
     SHA1: 16:59:E7:E3:0C:AA:7A:0D:F2:0D:05:20:12:A8:85:0B:32:C5:4F:68
     Signature algorithm name: SHA1withRSA

Then use the keytool again to print out all the aliases of your signing keystore:

keytool -list -keystore my-signing-key.keystore

You will get a list of aliases and their certificate fingerprint:

android_key, Jan 23, 2010, PrivateKeyEntry,
Certificate fingerprint (MD5): B3:4F:BE:07:AA:78:24:DC:CA:92:36:FF:AE:8C:17:DB

Voila! we can now determined the apk has been signed with this keystore, and with the alias 'android_key'.

Keytool is part of Java, so make sure your PATH has Java installation dir in it.

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

Using PHP with Socket.io

We are now in 2018 and hoola, there is a way to implement WS and WAMPServer on php. It 's Called Ratchet.

How does functools partial do what it does?

Also worth to mention, that when partial function passed another function where we want to "hard code" some parameters, that should be rightmost parameter

def func(a,b):
    return a*b
prt = partial(func, b=7)
    print(prt(4))
#return 28

but if we do the same, but changing a parameter instead

def func(a,b):
    return a*b
 prt = partial(func, a=7)
    print(prt(4))

it will throw error, "TypeError: func() got multiple values for argument 'a'"

Custom Adapter for List View

check this link, in very simple via the convertView, we can get the layout of a row which will be displayed in listview (which is the parentView).

View v = convertView;

if (v == null) {

    LayoutInflater vi;
    vi = LayoutInflater.from(getContext());
    v = vi.inflate(R.layout.itemlistrow, null);

}

using the position, you can get the objects of the List<Item>.

Item p = items.get(position);

after that we'll have to set the desired details of the object to the identified form widgets.

if (p != null) {

    TextView tt = (TextView) v.findViewById(R.id.id);
    TextView tt1 = (TextView) v.findViewById(R.id.categoryId);
    TextView tt3 = (TextView) v.findViewById(R.id.description);

    if (tt != null) {
        tt.setText(p.getId());
    }
    if (tt1 != null) {

        tt1.setText(p.getCategory().getId());
    }
    if (tt3 != null) {

        tt3.setText(p.getDescription());
    }
}

then it will return the constructed view which will be attached to the parentView (which is a ListView/GridView).

How do I fetch multiple columns for use in a cursor loop?

Here is slightly modified version. Changes are noted as code commentary.

BEGIN TRANSACTION

declare @cnt int
declare @test nvarchar(128)
-- variable to hold table name
declare @tableName nvarchar(255)
declare @cmd nvarchar(500) 
-- local means the cursor name is private to this code
-- fast_forward enables some speed optimizations
declare Tests cursor local fast_forward for
 SELECT COLUMN_NAME, TABLE_NAME
   FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE COLUMN_NAME LIKE 'pct%' 
    AND TABLE_NAME LIKE 'TestData%'

open Tests
-- Instead of fetching twice, I rather set up no-exit loop
while 1 = 1
BEGIN
  -- And then fetch
  fetch next from Tests into @test, @tableName
  -- And then, if no row is fetched, exit the loop
  if @@fetch_status <> 0
  begin
     break
  end
  -- Quotename is needed if you ever use special characters
  -- in table/column names. Spaces, reserved words etc.
  -- Other changes add apostrophes at right places.
  set @cmd = N'exec sp_rename ''' 
           + quotename(@tableName) 
           + '.' 
           + quotename(@test) 
           + N''',''' 
           + RIGHT(@test,LEN(@test)-3) 
           + '_Pct''' 
           + N', ''column''' 

  print @cmd

  EXEC sp_executeSQL @cmd
END

close Tests 
deallocate Tests

ROLLBACK TRANSACTION
--COMMIT TRANSACTION

If else on WHERE clause

Note the following is functionally different to Gordon Linoff's answer. His answer assumes that you want to use email2 if email is NULL. Mine assumes you want to use email2 if email is an empty-string. The correct answer will depend on your database (or you could perform a NULL check and an empty-string check - it all depends on what is appropriate for your database design).

SELECT  `id` ,  `naam` 
FROM  `klanten` 
WHERE `email` LIKE  '%[email protected]%'
OR (LENGTH(email) = 0 AND `email2` LIKE  '%[email protected]%')

Parse XML document in C#

Try this:

XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");

Or alternatively if you have the XML in a string use the LoadXml method.

Once you have it loaded, you can use SelectNodes and SelectSingleNode to query specific values, for example:

XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "[email protected]"

Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:

<Data>
    <Employee>
        <Name>Test</Name>
        <ID>123</ID>
    </Employee>
    <Company>
        <Name>ABC</Name>
        <Email>[email protected]</Email>
    </Company>
</Data>

What's the difference between `raw_input()` and `input()` in Python 3?

In Python 3, raw_input() doesn't exist which was already mentioned by Sven.

In Python 2, the input() function evaluates your input.

Example:

name = input("what is your name ?")
what is your name ?harsha

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    name = input("what is your name ?")
  File "<string>", line 1, in <module>
NameError: name 'harsha' is not defined

In the example above, Python 2.x is trying to evaluate harsha as a variable rather than a string. To avoid that, we can use double quotes around our input like "harsha":

>>> name = input("what is your name?")
what is your name?"harsha"
>>> print(name)
harsha

raw_input()

The raw_input()` function doesn't evaluate, it will just read whatever you enter.

Example:

name = raw_input("what is your name ?")
what is your name ?harsha
>>> name
'harsha'

Example:

 name = eval(raw_input("what is your name?"))
what is your name?harsha

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    name = eval(raw_input("what is your name?"))
  File "<string>", line 1, in <module>
NameError: name 'harsha' is not defined

In example above, I was just trying to evaluate the user input with the eval function.

Python: Get HTTP headers from urllib2.urlopen call?

Actually, it appears that urllib2 can do an HTTP HEAD request.

The question that @reto linked to, above, shows how to get urllib2 to do a HEAD request.

Here's my take on it:

import urllib2

# Derive from Request class and override get_method to allow a HEAD request.
class HeadRequest(urllib2.Request):
    def get_method(self):
        return "HEAD"

myurl = 'http://bit.ly/doFeT'
request = HeadRequest(myurl)

try:
    response = urllib2.urlopen(request)
    response_headers = response.info()

    # This will just display all the dictionary key-value pairs.  Replace this
    # line with something useful.
    response_headers.dict

except urllib2.HTTPError, e:
    # Prints the HTTP Status code of the response but only if there was a 
    # problem.
    print ("Error code: %s" % e.code)

If you check this with something like the Wireshark network protocol analazer, you can see that it is actually sending out a HEAD request, rather than a GET.

This is the HTTP request and response from the code above, as captured by Wireshark:

HEAD /doFeT HTTP/1.1
Accept-Encoding: identity
Host: bit.ly
Connection: close
User-Agent: Python-urllib/2.7

HTTP/1.1 301 Moved
Server: nginx
Date: Sun, 19 Feb 2012 13:20:56 GMT
Content-Type: text/html; charset=utf-8
Cache-control: private; max-age=90
Location: http://www.kidsidebyside.org/?p=445
MIME-Version: 1.0
Content-Length: 127
Connection: close
Set-Cookie: _bit=4f40f738-00153-02ed0-421cf10a;domain=.bit.ly;expires=Fri Aug 17 13:20:56 2012;path=/; HttpOnly

However, as mentioned in one of the comments in the other question, if the URL in question includes a redirect then urllib2 will do a GET request to the destination, not a HEAD. This could be a major shortcoming, if you really wanted to only make HEAD requests.

The request above involves a redirect. Here is request to the destination, as captured by Wireshark:

GET /2009/05/come-and-draw-the-circle-of-unity-with-us/ HTTP/1.1
Accept-Encoding: identity
Host: www.kidsidebyside.org
Connection: close
User-Agent: Python-urllib/2.7

An alternative to using urllib2 is to use Joe Gregorio's httplib2 library:

import httplib2

url = "http://bit.ly/doFeT"
http_interface = httplib2.Http()

try:
    response, content = http_interface.request(url, method="HEAD")
    print ("Response status: %d - %s" % (response.status, response.reason))

    # This will just display all the dictionary key-value pairs.  Replace this
    # line with something useful.
    response.__dict__

except httplib2.ServerNotFoundError, e:
    print (e.message)

This has the advantage of using HEAD requests for both the initial HTTP request and the redirected request to the destination URL.

Here's the first request:

HEAD /doFeT HTTP/1.1
Host: bit.ly
accept-encoding: gzip, deflate
user-agent: Python-httplib2/0.7.2 (gzip)

Here's the second request, to the destination:

HEAD /2009/05/come-and-draw-the-circle-of-unity-with-us/ HTTP/1.1
Host: www.kidsidebyside.org
accept-encoding: gzip, deflate
user-agent: Python-httplib2/0.7.2 (gzip)

How to send a pdf file directly to the printer using JavaScript?

I think this Library of JavaScript might Help you:

It's called Print.js

First Include

<script src="print.js"></script>
<link rel="stylesheet" type="text/css" href="print.css">

It's basic usage is to call printJS() and just pass in a PDF document url: printJS('docs/PrintJS.pdf')

What I did was something like this, this will also show "Loading...." if PDF document is too large.

<button type="button" onclick="printJS({printable:'docs/xx_large_printjs.pdf', type:'pdf', showModal:true})">
    Print PDF with Message
</button>

However keep in mind that:

Firefox currently doesn't allow printing PDF documents using iframes. There is an open bug in Mozilla's website about this. When using Firefox, Print.js will open the PDF file into a new tab.

set option "selected" attribute from dynamic created option

// get the OPTION we want selected
var $option = $('#SelectList').children('option[value="'+ id +'"]');
// and now set the option we want selected
$option.attr('selected', true);??

matplotlib has no attribute 'pyplot'

Did you import it? Importing matplotlib is not enough.

>>> import matplotlib
>>> matplotlib.pyplot
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'

but

>>> import matplotlib.pyplot
>>> matplotlib.pyplot

works.

pyplot is a submodule of matplotlib and not immediately imported when you import matplotlib.

The most common form of importing pyplot is

import matplotlib.pyplot as plt

Thus, your statements won't be too long, e.g.

plt.plot([1,2,3,4,5])

instead of

matplotlib.pyplot.plot([1,2,3,4,5])

And: pyplot is not a function, it's a module! So don't call it, use the functions defined inside this module instead. See my example above

How To Execute SSH Commands Via PHP

//Update 2018, works//

Method1:

Download phpseclib v1 and use this code:

<?php
set_include_path(__DIR__ . '/phpseclib1.0.11');
include("Net/SSH2.php");

$key ="MyPassword";
  /* ### if using PrivateKey ### 
  include("Crypt/RSA.php");
  $key = new Crypt_RSA();
  $key->loadKey(file_get_contents('private-key.ppk'));
  */

$ssh = new Net_SSH2('www.example.com', 22);   // Domain or IP
if (!$ssh->login('your_username', $key))  exit('Login Failed');

echo $ssh->exec('pwd');
?>

or Method2:

Download newest phpseclib v2 (requires composer install at first):

<?php

set_include_path($path=__DIR__ . '/phpseclib-master/phpseclib');
include ($path.'/../vendor/autoload.php');

$loader = new \Composer\Autoload\ClassLoader();

use phpseclib\Net\SSH2;

$key ="MyPassword";
  /* ### if using PrivateKey ### 
  use phpseclib\Crypt\RSA;
  $key = new RSA();
  $key->load(file_get_contents('private-key.ppk'));
  */

$ssh = new SSH2('www.example.com', 22);   // Domain or IP
if (!$ssh->login('your_username', $key))   exit('Login Failed'); 

echo $ssh->exec('pwd');
?>

p.s. if you get "Connection timed out" then it's probably the issue of HOST/FIREWALL (local or remote) or like that, not a fault of script.

How to add a new project to Github using VS Code

Install git on your PC and setup configuration values in either Command Prompt (cmd) or VS Code terminal (Ctrl + `)

git config --global user.name "Your Name"
git config --global user.email [email protected]

Setup editor

Windows eg.:

git config --global core.editor "'C:/Program Files/Notepad++/notepad++.exe' -multiInst -nosession"

Linux / Mac eg.:

git config --global core.editor vim

Check git settings which displays configuration details

git config --list

Login to github and create a remote repository. Copy the URL of this repository

Navigate to your project directory and execute the below commands

git init                                                           // start tracking current directory
git add -A                                                         // add all files in current directory to staging area, making them available for commit
git commit -m "commit message"                                     // commit your changes
git remote add origin https://github.com/username/repo-name.git    // add remote repository URL which contains the required details
git pull origin master                                             // always pull from remote before pushing
git push -u origin master                                          // publish changes to your remote repository

Listing all extras of an Intent

If for debugging all you want is a string (sort of implied by the OP but not explicitly stated), simply use toString on the extras Bundle:

intent.getExtras().toString()

It returns a string such as:

Bundle[{key1=value1, key2=value2, key3=value3}]

Documentation: Bundle.toString() (it's unfortunately the default Object.toString() javadoc and as such quite useless here.)

Tensorflow r1.0 : could not a find a version that satisfies the requirement tensorflow

From your python version output, looks like that you are using Anaconda python, in that case, there is a simple way to install tensorflow.

conda install -c conda-forge tensorflow

This command will take care of all dependencies like upgrade/downgrade etc.

javascript object max size limit

Step 1 is always to first determine where the problem lies. Your title and most of your question seem to suggest that you're running into quite a low length limit on the length of a string in JavaScript / on browsers, an improbably low limit. You're not. Consider:

var str;

document.getElementById('theButton').onclick = function() {
  var build, counter;

  if (!str) {
    str = "0123456789";
    build = [];
    for (counter = 0; counter < 900; ++counter) {
      build.push(str);
    }
    str = build.join("");
  }
  else {
    str += str;
  }
  display("str.length = " + str.length);
};

Live copy

Repeatedly clicking the relevant button keeps making the string longer. With Chrome, Firefox, Opera, Safari, and IE, I've had no trouble with strings more than a million characters long:

str.length = 9000
str.length = 18000
str.length = 36000
str.length = 72000
str.length = 144000
str.length = 288000
str.length = 576000
str.length = 1152000
str.length = 2304000
str.length = 4608000
str.length = 9216000
str.length = 18432000

...and I'm quite sure I could got a lot higher than that.

So it's nothing to do with a length limit in JavaScript. You haven't show your code for sending the data to the server, but most likely you're using GET which means you're running into the length limit of a GET request, because GET parameters are put in the query string. Details here.

You need to switch to using POST instead. In a POST request, the data is in the body of the request rather than in the URL, and can be very, very large indeed.

CSS: how do I create a gap between rows in a table?

If you stick with the design using tables the best idea will be to give an empty row with no content and specified height between each rows in the table.

You can use div to avoid this complexity. Just give a margin to each div.

How to split a string in Haskell?

Example in the ghci:

>  import qualified Text.Regex as R
>  R.splitRegex (R.mkRegex "x") "2x3x777"
>  ["2","3","777"]

.NET console application as Windows service

I've had great success with TopShelf.

TopShelf is a Nuget package designed to make it easy to create .NET Windows apps that can run as console apps or as Windows Services. You can quickly hook up events such as your service Start and Stop events, configure using code e.g. to set the account it runs as, configure dependencies on other services, and configure how it recovers from errors.

From the Package Manager Console (Nuget):

Install-Package Topshelf

Refer to the code samples to get started.

Example:

HostFactory.Run(x =>                                 
{
    x.Service<TownCrier>(s =>                        
    {
       s.ConstructUsing(name=> new TownCrier());     
       s.WhenStarted(tc => tc.Start());              
       s.WhenStopped(tc => tc.Stop());               
    });
    x.RunAsLocalSystem();                            

    x.SetDescription("Sample Topshelf Host");        
    x.SetDisplayName("Stuff");                       
    x.SetServiceName("stuff");                       
}); 

TopShelf also takes care of service installation, which can save a lot of time and removes boilerplate code from your solution. To install your .exe as a service you just execute the following from the command prompt:

myservice.exe install -servicename "MyService" -displayname "My Service" -description "This is my service."

You don't need to hook up a ServiceInstaller and all that - TopShelf does it all for you.

no target device found android studio 2.1.1

  1. Set up a device for development https://developer.android.com/studio/run/device.html#setting-up

  2. Enable developer options and debugging https://developer.android.com/studio/debug/dev-options.html#enable

Optional

  1. How to enable Developer options and USB debugging
    • Open Settings menu on Home screen.
    • Scroll to About Tablet and tap it.
    • Click on Build number for seven times until a pop-up message says “You are now a developer!”

How do you do a ‘Pause’ with PowerShell 2.0?

In addition to Michael Sorens' answer:

<6> ReadKey in a new process

Start-Process PowerShell {[void][System.Console]::ReadKey($true)} -Wait -NoNewWindow
  • Advantage: Accepts any key but properly excludes Shift, Alt, Ctrl modifier keys.
  • Advantage: Works in PS-ISE.

Paste in insert mode?

No not directly. What you can do though is quickly exit insert mode for a single normal mode operation with Ctrl-O and then paste from there which will end by putting you back in insert mode.

Key Combo: Ctrl-O p

EDIT: Interesting. It does appear that there is a way as several other people have listed.

What is the difference between AF_INET and PF_INET in socket programming?

In fact, AF_ and PF_ are the same thing. There are some words on Wikipedia will clear your confusion

The original design concept of the socket interface distinguished between protocol types (families) and the specific address types that each may use. It was envisioned that a protocol family may have several address types. Address types were defined by additional symbolic constants, using the prefix AF_ instead of PF_. The AF_-identifiers are intended for all data structures that specifically deal with the address type and not the protocol family. However, this concept of separation of protocol and address type has not found implementation support and the AF_-constants were simply defined by the corresponding protocol identifier, rendering the distinction between AF_ versus PF_ constants a technical argument of no significant practical consequence. Indeed, much confusion exists in the proper usage of both forms.

How do I filter date range in DataTables?

Using other posters code with some tweaks:

<table id="MainContent_tbFilterAsp" style="margin-top:-15px;">
        <tbody>
            <tr>
                <td style="vertical-align:initial;"><label for="datepicker_from" id="MainContent_datepicker_from_lbl" style="margin-top:7px;">From date:</label>&nbsp;
                </td>
                
                <td style="padding-right: 20px;"><input name="ctl00$MainContent$datepicker_from" type="text" id="datepicker_from" class="datepick form-control hasDatepicker" autocomplete="off" style="cursor:pointer; background-color: #FFFFFF">&nbsp;&nbsp;&nbsp;
                </td>
                
                <td style="vertical-align:initial"><label for="datepicker_to" id="MainContent_datepicker_to_lbl" style="margin-top:7px;">To date:</label>&nbsp;
                </td>
                
                <td style="padding-right: 20px;"><input name="ctl00$MainContent$datepicker_to" type="text" id="datepicker_to" class="datepick form-control hasDatepicker" autocomplete="off" style="cursor:pointer; background-color: #FFFFFF">&nbsp;&nbsp;&nbsp;                        
                </td>
                
                <td style="vertical-align:initial"><a onclick="$('#datepicker_from').val(''); $('#datepicker_to').val(''); return false;" id="datepicker_clear_lnk" style="margin-top:7px;">Clear</a></td>
            </tr>
        </tbody>
    </table>
    
    <script>
        $(document).ready(function() {
            $(function() {
                var oTable = $('#tbAD').DataTable({
                "oLanguage": {
                    "sSearch": "Filter Data"
                },
                "iDisplayLength": -1,
                "sPaginationType": "full_numbers",
                "pageLength": 50, 
                });

                $("#datepicker_from").datepicker();
                $("#datepicker_to").datepicker();

                $('#datepicker_from').change(function (e) {
                    oTable.draw();
                });
                $('#datepicker_to').change(function (e) {
                    oTable.draw();
                });
                $('#datepicker_clear_lnk').click(function (e) {
                    oTable.draw();
                });
            });   

            $.fn.dataTable.ext.search.push(
                function (settings, data, dataIndex) {
                var min = $('#datepicker_from').datepicker("getDate") == null ? null : $('#datepicker_from').datepicker("getDate").setHours(0,0,0,0);
                var max = $('#datepicker_to').datepicker("getDate") == null ? null : $('#datepicker_to').datepicker("getDate").setHours(0,0,0,0);
                var startDate = new Date(data[9]).setHours(0,0,0,0);
                if (min == null && max == null) { return true; }
                if (min == null && startDate <= max) { return true; }
                if (max == null && startDate >= min) { return true; }
                if (startDate <= max && startDate >= min) { return true; }                    
                return false;
                }
            );
        });
</script>

Running a simple shell script as a cronjob

Specify complete path and grant proper permission to scriptfile. I tried following script file to run through cron:

#!/bin/bash
/bin/mkdir /scratch/ofsaaweb/CHEF_FICHOME/ficdb/bin/crondir

And crontab command is

* * * * * /bin/bash /scratch/ofsaaweb/CHEF_FICHOME/ficdb/bin/test.sh

It worked for me.

Convert timedelta to total seconds

You have a problem one way or the other with your datetime.datetime.fromtimestamp(time.mktime(time.gmtime())) expression.

(1) If all you need is the difference between two instants in seconds, the very simple time.time() does the job.

(2) If you are using those timestamps for other purposes, you need to consider what you are doing, because the result has a big smell all over it:

gmtime() returns a time tuple in UTC but mktime() expects a time tuple in local time.

I'm in Melbourne, Australia where the standard TZ is UTC+10, but daylight saving is still in force until tomorrow morning so it's UTC+11. When I executed the following, it was 2011-04-02T20:31 local time here ... UTC was 2011-04-02T09:31

>>> import time, datetime
>>> t1 = time.gmtime()
>>> t2 = time.mktime(t1)
>>> t3 = datetime.datetime.fromtimestamp(t2)
>>> print t0
1301735358.78
>>> print t1
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=9, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=0) ### this is UTC
>>> print t2
1301700663.0
>>> print t3
2011-04-02 10:31:03 ### this is UTC+1
>>> tt = time.time(); print tt
1301736663.88
>>> print datetime.datetime.now()
2011-04-02 20:31:03.882000 ### UTC+11, my local time
>>> print datetime.datetime(1970,1,1) + datetime.timedelta(seconds=tt)
2011-04-02 09:31:03.880000 ### UTC
>>> print time.localtime()
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=20, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=1) ### UTC+11, my local time

You'll notice that t3, the result of your expression is UTC+1, which appears to be UTC + (my local DST difference) ... not very meaningful. You should consider using datetime.datetime.utcnow() which won't jump by an hour when DST goes on/off and may give you more precision than time.time()

Passing multiple parameters to pool.map() function in Python

In case you don't have access to functools.partial, you could use a wrapper function for this, as well.

def target(lock):
    def wrapped_func(items):
        for item in items:
            # Do cool stuff
            if (... some condition here ...):
                lock.acquire()
                # Write to stdout or logfile, etc.
                lock.release()
    return wrapped_func

def main():
    iterable = [1, 2, 3, 4, 5]
    pool = multiprocessing.Pool()
    lck = multiprocessing.Lock()
    pool.map(target(lck), iterable)
    pool.close()
    pool.join()

This makes target() into a function that accepts a lock (or whatever parameters you want to give), and it will return a function that only takes in an iterable as input, but can still use all your other parameters. That's what is ultimately passed in to pool.map(), which then should execute with no problems.

R apply function with multiple parameters

Just pass var2 as an extra argument to one of the apply functions.

mylist <- list(a=1,b=2,c=3)
myfxn <- function(var1,var2){
  var1*var2
}
var2 <- 2

sapply(mylist,myfxn,var2=var2)

This passes the same var2 to every call of myfxn. If instead you want each call of myfxn to get the 1st/2nd/3rd/etc. element of both mylist and var2, then you're in mapply's domain.

How can I calculate the time between 2 Dates in typescript

This is how it should be done in typescript:

(new Date()).valueOf() - (new Date("2013-02-20T12:01:04.753Z")).valueOf()

Better readability:

      var eventStartTime = new Date(event.startTime);
      var eventEndTime = new Date(event.endTime);
      var duration = eventEndTime.valueOf() - eventStartTime.valueOf();

Share data between AngularJS controllers

Simplest Solution:

I have used an AngularJS service.

Step1: I have created an AngularJS service named SharedDataService.

myApp.service('SharedDataService', function () {
     var Person = {
        name: ''

    };
    return Person;
});

Step2: Create two controllers and use the above created service.

//First Controller
myApp.controller("FirstCtrl", ['$scope', 'SharedDataService',
   function ($scope, SharedDataService) {
   $scope.Person = SharedDataService;
   }]);

//Second Controller
myApp.controller("SecondCtrl", ['$scope', 'SharedDataService',
   function ($scope, SharedDataService) {
   $scope.Person = SharedDataService;
   }]);

Step3: Simply use the created controllers in the view.

<body ng-app="myApp">

<div ng-controller="FirstCtrl">
<input type="text" ng-model="Person.name">
<br>Input is : <strong>{{Person.name}}</strong>
</div>

<hr>

<div ng-controller="SecondCtrl">
Input should also be here: {{Person.name}}
</div>

</body>

To see working solution to this problem please press the link below

https://codepen.io/wins/pen/bmoYLr

.html file:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body ng-app="myApp">

  <div ng-controller="FirstCtrl">
    <input type="text" ng-model="Person.name">
    <br>Input is : <strong>{{Person.name}}</strong>
   </div>

<hr>

  <div ng-controller="SecondCtrl">
    Input should also be here: {{Person.name}}
  </div>

//Script starts from here

<script>

var myApp = angular.module("myApp",[]);
//create SharedDataService
myApp.service('SharedDataService', function () {
     var Person = {
        name: ''

    };
    return Person;
});

//First Controller
myApp.controller("FirstCtrl", ['$scope', 'SharedDataService',
    function ($scope, SharedDataService) {
    $scope.Person = SharedDataService;
    }]);

//Second Controller
myApp.controller("SecondCtrl", ['$scope', 'SharedDataService',
    function ($scope, SharedDataService) {
    $scope.Person = SharedDataService;
}]);

</script>


</body>
</html>

Installing TensorFlow on Windows (Python 3.6.x)

https://i.stack.imgur.com/1Y3kf.png

pip install -- tensorflow This worked for me for this version of python Python 3.6.4 : : Anaconda, Inc.

Xcode 5 and iOS 7: Architecture and Valid architectures

When you set 64-bit the resulting binary is a "Fat" binary, which contains all three Mach-O images bundled with a thin fat header. You can see that using otool or jtool. You can check out some fat binaries included as part of the iOS 7.0 SDK, for example the AVFoundation Framework, like so:

% cd  /Developer/Platforms/iPhoneOS.platform/DeviceSupport/7.0\ \(11A465\)/Symbols/System/Library/Frameworks/AVFoundation.framework/

%otool -V -f AVFoundation                                                                     9:36
Fat headers
fat_magic FAT_MAGIC
nfat_arch 3
architecture arm64     # The 64-bit version (A7)
    cputype CPU_TYPE_ARM64
    cpusubtype CPU_SUBTYPE_ARM64_ALL
    capabilities 0x0
    offset 16384
    size 2329888
    align 2^14 (16384)
architecture armv7        # A5X - packaged after the arm64version
    cputype CPU_TYPE_ARM
    cpusubtype CPU_SUBTYPE_ARM_V7
    capabilities 0x0
    offset 2359296
    size 2046336
    align 2^14 (16384)
architecture armv7s       # A6 - packaged after the armv7 version
    cputype CPU_TYPE_ARM
    cpusubtype CPU_SUBTYPE_ARM_V7S
    capabilities 0x0
    offset 4407296
    size 2046176
    align 2^14 (16384)

As for the binary itself, it uses the ARM64 bit instruction set, which is (mostly compatible with 32-bit, but) a totally different instruction set. This is especially important for graphics program (using NEON instructions and registers). Likewise, the CPU has more registers, which makes quite an impact on program speed. There's an interesting discussion in http://blogs.barrons.com/techtraderdaily/2013/09/19/apple-the-64-bit-question/?mod=yahoobarrons on whether or not this makes a difference; benchmarking tests have so far clearly indicated that it does.

Using otool -tV will dump the assembly (if you have XCode 5 and later), and then you can see the instruction set differences for yourself. Most (but not all) developers will remain agnostic to the changes, as for the most part they do not directly affect Obj-C (CG* APIs notwithstanding), and have to do more with low level pointer handling. The compiler will work its magic and optimizations.

Permission denied on accessing host directory in Docker

It is an SELinux issue.

You can temporarily issue

su -c "setenforce 0"

on the host to access or else add an SELinux rule by running

chcon -Rt svirt_sandbox_file_t /path/to/volume

Are there any style options for the HTML5 Date picker?

You can use the following CSS to style the input element.

_x000D_
_x000D_
input[type="date"] {_x000D_
  background-color: red;_x000D_
  outline: none;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-clear-button {_x000D_
  font-size: 18px;_x000D_
  height: 30px;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-inner-spin-button {_x000D_
  height: 28px;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-calendar-picker-indicator {_x000D_
  font-size: 15px;_x000D_
}
_x000D_
<input type="date" value="From" name="from" placeholder="From" required="" />
_x000D_
_x000D_
_x000D_

Angular 5 - Copy to clipboard

Modified version of jockeisorby's answer that fixes the event handler not being properly removed.

copyToClipboard(item): void {
    let listener = (e: ClipboardEvent) => {
        e.clipboardData.setData('text/plain', (item));
        e.preventDefault();
    };

    document.addEventListener('copy', listener);
    document.execCommand('copy');
    document.removeEventListener('copy', listener);
}

When using .net MVC RadioButtonFor(), how do you group so only one selection can be made?

The first parameter of Html.RadioButtonFor() should be the property name you're using, and the second parameter should be the value of that specific radio button. Then they'll have the same name attribute value and the helper will select the given radio button when/if it matches the property value.

Example:

<div class="editor-field">
    <%= Html.RadioButtonFor(m => m.Gender, "M" ) %> Male
    <%= Html.RadioButtonFor(m => m.Gender, "F" ) %> Female
</div>

Here's a more specific example:

I made a quick MVC project named "DeleteMeQuestion" (DeleteMe prefix so I know that I can remove it later after I forget about it).

I made the following model:

namespace DeleteMeQuestion.Models
{
    public class QuizModel
    {
        public int ParentQuestionId { get; set; }
        public int QuestionId { get; set; }
        public string QuestionDisplayText { get; set; }
        public List<Response> Responses { get; set; }

        [Range(1,999, ErrorMessage = "Please choose a response.")]
        public int SelectedResponse { get; set; }
    }

    public class Response
    {
        public int ResponseId { get; set; }
        public int ChildQuestionId { get; set; }
        public string ResponseDisplayText { get; set; }
    }
}

There's a simple range validator in the model, just for fun. Next up, I made the following controller:

namespace DeleteMeQuestion.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index(int? id)
        {
            // TODO: get question to show based on method parameter 
            var model = GetModel(id);
            return View(model);
        }

        [HttpPost]
        public ActionResult Index(int? id, QuizModel model)
        {
            if (!ModelState.IsValid)
            {
                var freshModel = GetModel(id);
                return View(freshModel);
            }

            // TODO: save selected answer in database
            // TODO: get next question based on selected answer (hard coded to 999 for now)

            var nextQuestionId = 999;
            return RedirectToAction("Index", "Home", new {id = nextQuestionId});
        }

        private QuizModel GetModel(int? questionId)
        {
            // just a stub, in lieu of a database

            var model = new QuizModel
            {
                QuestionDisplayText = questionId.HasValue ? "And so on..." : "What is your favorite color?",
                QuestionId = 1,
                Responses = new List<Response>
                                                {
                                                    new Response
                                                        {
                                                            ChildQuestionId = 2,
                                                            ResponseId = 1,
                                                            ResponseDisplayText = "Red"
                                                        },
                                                    new Response
                                                        {
                                                            ChildQuestionId = 3,
                                                            ResponseId = 2,
                                                            ResponseDisplayText = "Blue"
                                                        },
                                                    new Response
                                                        {
                                                            ChildQuestionId = 4,
                                                            ResponseId = 3,
                                                            ResponseDisplayText = "Green"
                                                        },
                                                }
            };

            return model;
        }
    }
}

Finally, I made the following view that makes use of the model:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<DeleteMeQuestion.Models.QuizModel>" %>

<asp:Content ContentPlaceHolderID="TitleContent" runat="server">
    Home Page
</asp:Content>

<asp:Content ContentPlaceHolderID="MainContent" runat="server">

    <% using (Html.BeginForm()) { %>

        <div>

            <h1><%: Model.QuestionDisplayText %></h1>

            <div>
            <ul>
            <% foreach (var item in Model.Responses) { %>
                <li>
                    <%= Html.RadioButtonFor(m => m.SelectedResponse, item.ResponseId, new {id="Response" + item.ResponseId}) %>
                    <label for="Response<%: item.ResponseId %>"><%: item.ResponseDisplayText %></label>
                </li>
            <% } %>
            </ul>

            <%= Html.ValidationMessageFor(m => m.SelectedResponse) %>

        </div>

        <input type="submit" value="Submit" />

    <% } %>

</asp:Content>

As I understand your context, you have questions with a list of available answers. Each answer will dictate the next question. Hopefully that makes sense from my model and TODO comments.

This gives you the radio buttons with the same name attribute, but different ID attributes.

Cannot start session without errors in phpMyAdmin

Knowing this thread is marked as solved, it shows up early on Google Search for the given term. So I thought it might be useful to mention another reason that can lead to this error.

If you enabled "safe/secure cookies", that has to be disabled for phpMyAdmin as it wont work with them being activated. So make sure you have nothing like:

Header set Set-Cookie HttpOnly;Secure

in your config.

Gson library in Android Studio

There is no need of adding JAR to your project by yourself, just add dependency in build.gradle (Module lavel). ALSO always try to use the upgraded version, as of now is

dependencies {
  implementation 'com.google.code.gson:gson:2.8.5'
}

As every incremental version has some bugs fixes or up-gradations as mentioned here

VB.NET Empty String Array

try this Dim Arraystr() as String ={}

How can I create an utility class?

I would make the class final and every method would be static.

So the class cannot be extended and the methods can be called by Classname.methodName. If you add members, be sure that they work thread safe ;)

Angular expression if array contains

Somewhere in your initialisation put this code.

Array.prototype.contains = function contains(obj) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
};

Then, you can use it this way:

<li ng-class="{approved: selectedForApproval.contains(jobSet)}"></li>

fetch gives an empty response body

I just ran into this. As mentioned in this answer, using mode: "no-cors" will give you an opaque response, which doesn't seem to return data in the body.

opaque: Response for “no-cors” request to cross-origin resource. Severely restricted.

In my case I was using Express. After I installed cors for Express and configured it and removed mode: "no-cors", I was returned a promise. The response data will be in the promise, e.g.

fetch('http://example.com/api/node', {
  // mode: 'no-cors',
  method: 'GET',
  headers: {
    Accept: 'application/json',
  },
},
).then(response => {
  if (response.ok) {
    response.json().then(json => {
      console.log(json);
    });
  }
});

jQuery Array of all selected checkboxes (by class)

You can also add underscore.js to your project and will be able to do it in one line:

_.map($("input[name='category_ids[]']:checked"), function(el){return $(el).val()})

SQL Select between dates

SQLLite requires dates to be in YYYY-MM-DD format. Since the data in your database and the string in your query isn't in that format, it is probably treating your "dates" as strings.

Is there a workaround for ORA-01795: maximum number of expressions in a list is 1000 error?

I ran into this issue recently and figured out a cheeky way of doing it without stringing together additional IN clauses

You could make use of Tuples

SELECT field1, field2, field3
FROM table1
WHERE (1, name) IN ((1, value1), (1, value2), (1, value3),.....(1, value5000));

Oracle does allow >1000 Tuples but not simple values. More on this here,

https://community.oracle.com/message/3515498#3515498
and
https://community.oracle.com/thread/958612

This is of course if you don't have the option of using a subquery inside IN to get the values you need from a temp table.

Get a json via Http Request in NodeJS

Just setting json option to true, the body will contain the parsed json:

request({
  url: 'http://...',
  json: true
}, function(error, response, body) {
  console.log(body);
});

What do the return values of Comparable.compareTo mean in Java?

Answer in short: (search your situation)

  • 1.compareTo(0) (return: 1)
  • 1.compareTo(1) (return: 0)
  • 0.comapreTo(1) (return: -1)

Hiding the R code in Rmarkdown/knit and just showing the results

Alternatively, you can also parse a standard markdown document (without code blocks per se) on the fly by the markdownreports package.

Method List in Visual Studio Code

In VSCode 1.24 you can do that.

Right click on EXPLORER on the side bar and checked Outline.

VBA Date as integer

Public SUB test()
    Dim mdate As Date
    mdate = now()
    MsgBox (Round(CDbl(mdate), 0))
End SUB

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I've gotten same problem. The servers logs showed:

DEBUG: <-- origin: null

I've investigated that and it occurred that this is not populated when I've been calling from file from local drive. When I've copied file to the server and used it from server - the request worked perfectly fine

Remove duplicates from a dataframe in PySpark

if you have a data frame and want to remove all duplicates -- with reference to duplicates in a specific column (called 'colName'):

count before dedupe:

df.count()

do the de-dupe (convert the column you are de-duping to string type):

from pyspark.sql.functions import col
df = df.withColumn('colName',col('colName').cast('string'))

df.drop_duplicates(subset=['colName']).count()

can use a sorted groupby to check to see that duplicates have been removed:

df.groupBy('colName').count().toPandas().set_index("count").sort_index(ascending=False)

Google Maps JS API v3 - Simple Multiple Marker Example

Source Link

Demo Link

Complete HTML code

  • Show InfoWindow on Click or Hover.
  • Only one InfoWindow will be shown

enter image description here

    <!DOCTYPE html>
    <html>

    <head>
        <style>
            /*  <span class="metadata-marker" style="display: none;" data-region_tag="css"></span>       Set the size of the div element that contains the map */
            #map {
                height: 400px;
                /* The height is 400 pixels */
                width: 100%;
                /* The width is the width of the web page */
            }
        </style>
        <script>
            var map;
            var InforObj = [];
            var centerCords = {
                lat: -25.344,
                lng: 131.036
            };
            var markersOnMap = [{
                    placeName: "Australia (Uluru)",
                    LatLng: [{
                        lat: -25.344,
                        lng: 131.036
                    }]
                },
                {
                    placeName: "Australia (Melbourne)",
                    LatLng: [{
                        lat: -37.852086,
                        lng: 504.985963
                    }]
                },
                {
                    placeName: "Australia (Canberra)",
                    LatLng: [{
                        lat: -35.299085,
                        lng: 509.109615
                    }]
                },
                {
                    placeName: "Australia (Gold Coast)",
                    LatLng: [{
                        lat: -28.013044,
                        lng: 513.425586
                    }]
                },
                {
                    placeName: "Australia (Perth)",
                    LatLng: [{
                        lat: -31.951994,
                        lng: 475.858081
                    }]
                }
            ];

            window.onload = function () {
                initMap();
            };

            function addMarkerInfo() {
                for (var i = 0; i < markersOnMap.length; i++) {
                    var contentString = '<div id="content"><h1>' + markersOnMap[i].placeName +
                        '</h1><p>Lorem ipsum dolor sit amet, vix mutat posse suscipit id, vel ea tantas omittam detraxit.</p></div>';

                    const marker = new google.maps.Marker({
                        position: markersOnMap[i].LatLng[0],
                        map: map
                    });

                    const infowindow = new google.maps.InfoWindow({
                        content: contentString,
                        maxWidth: 200
                    });

                    marker.addListener('click', function () {
                        closeOtherInfo();
                        infowindow.open(marker.get('map'), marker);
                        InforObj[0] = infowindow;
                    });
                    // marker.addListener('mouseover', function () {
                    //     closeOtherInfo();
                    //     infowindow.open(marker.get('map'), marker);
                    //     InforObj[0] = infowindow;
                    // });
                    // marker.addListener('mouseout', function () {
                    //     closeOtherInfo();
                    //     infowindow.close();
                    //     InforObj[0] = infowindow;
                    // });
                }
            }

            function closeOtherInfo() {
                if (InforObj.length > 0) {
                    /* detach the info-window from the marker ... undocumented in the API docs */
                    InforObj[0].set("marker", null);
                    /* and close it */
                    InforObj[0].close();
                    /* blank the array */
                    InforObj.length = 0;
                }
            }

            function initMap() {
                map = new google.maps.Map(document.getElementById('map'), {
                    zoom: 4,
                    center: centerCords
                });
                addMarkerInfo();
            }
        </script>
    </head>

    <body>
        <h3>My Google Maps Demo</h3>
        <!--The div element for the map -->
        <div id="map"></div>

        <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>

    </body>

    </html>

Parsing xml using powershell

If you want to start with a file you can do this

[xml]$cn = Get-Content config.xml
$cn.xml.Section.BEName

Use PowerShell to Parse an XML File

Accessing a Shared File (UNC) From a Remote, Non-Trusted Domain With Credentials

Most SFTP servers support SCP as well which can be a lot easier to find libraries for. You could even just call an existing client from your code like pscp included with PuTTY.

If the type of file you're working with is something simple like a text or XML file, you could even go so far as to write your own client/server implementation to manipulate the file using something like .NET Remoting or web services.

diff to output only the file names

On my linux system to get just the filenames

diff -q /dir1 /dir2|cut -f2 -d' '

Mongodb: Failed to connect to 127.0.0.1:27017, reason: errno:10061

Point to your mongodb instalation e.g C:\Program Files\MongoDB\Serve\bin and run mongod.exe so you can open connection to 127.0.0.1:27017.

How to apply border radius in IE8 and below IE8 browsers?

As the answer said above, CSS PIE makes things like border-radius and box-shadow work in IE6-IE8: http://css3pie.com/

That said I have still found things to be somewhat flaky when using PIE and now just accept that people using older browsers aren't going to see rounded corners and dropshadows.

Using Cookie in Asp.Net Mvc 4

userCookie.Expires.AddDays(365); 

This line of code doesn't do anything. It is the equivalent of:

DateTime temp = userCookie.Expires.AddDays(365); 
//do nothing with temp

You probably want

userCookie.Expires = DateTime.Now.AddDays(365); 

jquery toggle slide from left to right and back

There is no such method as slideLeft() and slideRight() which looks like slideUp() and slideDown(), but you can simulate these effects using jQuery’s animate() function.

HTML Code:

<div class="text">Lorem ipsum.</div>

JQuery Code:

  $(document).ready(function(){
    var DivWidth = $(".text").width();
    $(".left").click(function(){
      $(".text").animate({
        width: 0
      });
    });
    $(".right").click(function(){
      $(".text").animate({
        width: DivWidth
      });
    });
  });

You can see an example here: How to slide toggle a DIV from Left to Right?

Detect Browser Language in PHP

Unfortunately, none of the answers to this question takes into account some valid HTTP_ACCEPT_LANGUAGE such as:

  • q=0.8,en-US;q=0.5,en;q=0.3: having the q priority value at first place.
  • ZH-CN: old browsers that capitalise (wrongly) the whole langcode.
  • *: that basically say "serve whatever language you have".

After a comprehensive test with thousands of different Accept-Languages in my server, I ended up having this language detection method:

define('SUPPORTED_LANGUAGES', ['en', 'es']);

function detect_language() {
    foreach (preg_split('/[;,]/', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $sub) {
        if (substr($sub, 0, 2) == 'q=') continue;
        if (strpos($sub, '-') !== false) $sub = explode('-', $sub)[0];
        if (in_array(strtolower($sub), SUPPORTED_LANGUAGES)) return $sub;
    }
    return 'en';
}

Force HTML5 youtube video

If you're using the iframe embed api, you can put html5:1 as one of the playerVars arguments, like so:

player = new YT.Player('player', {
    height: '390',
    width: '640',
    videoId: '<VIDEO ID>',
    playerVars: {
        html5: 1
    },
});

Totally works.

How to save traceback / sys.exc_info() values in a variable?

This is how I do it:

>>> import traceback
>>> try:
...   int('k')
... except:
...   var = traceback.format_exc()
... 
>>> print var
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ValueError: invalid literal for int() with base 10: 'k'

You should however take a look at the traceback documentation, as you might find there more suitable methods, depending to how you want to process your variable afterwards...

How to make script execution wait until jquery is loaded

Check this:

https://jsfiddle.net/neohunter/ey2pqt5z/

It will create a fake jQuery object, that allows you to use the onload methods of jquery, and they will be executed as soon as jquery is loaded.

It's not perfect.

_x000D_
_x000D_
// This have to be on <HEAD> preferibly inline_x000D_
var delayed_jquery = [];_x000D_
jQuery = function() {_x000D_
  if (typeof arguments[0] == "function") {_x000D_
    jQuery(document).ready(arguments[0]);_x000D_
  } else {_x000D_
    return {_x000D_
      ready: function(fn) {_x000D_
        console.log("registering function");_x000D_
        delayed_jquery.push(fn);_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
};_x000D_
$ = jQuery;_x000D_
var waitForLoad = function() {_x000D_
  if (typeof jQuery.fn != "undefined") {_x000D_
    console.log("jquery loaded!!!");_x000D_
    for (k in delayed_jquery) {_x000D_
      delayed_jquery[k]();_x000D_
    }_x000D_
  } else {_x000D_
    console.log("jquery not loaded..");_x000D_
    window.setTimeout(waitForLoad, 500);_x000D_
  }_x000D_
};_x000D_
window.setTimeout(waitForLoad, 500);_x000D_
// end_x000D_
_x000D_
_x000D_
_x000D_
// now lets use jQuery (the fake version)_x000D_
jQuery(document).ready(function() {_x000D_
  alert('Jquery now exists!');_x000D_
});_x000D_
_x000D_
jQuery(function() {_x000D_
  alert('Jquery now exists, this is using an alternative call');_x000D_
})_x000D_
_x000D_
// And lets load the real jquery after 3 seconds.._x000D_
window.setTimeout(function() {_x000D_
  var newscript = document.createElement('script');_x000D_
  newscript.type = 'text/javascript';_x000D_
  newscript.async = true;_x000D_
  newscript.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js';_x000D_
  (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(newscript);_x000D_
}, 3000);
_x000D_
_x000D_
_x000D_

Is there a way to "limit" the result with ELOQUENT ORM of Laravel?

Also, we can use it following ways

To get only first

 $cat_details = DB::table('an_category')->where('slug', 'people')->first();

To get by limit and offset

$top_articles = DB::table('an_pages')->where('status',1)->limit(30)->offset(0)->orderBy('id', 'DESC')->get();
$remaining_articles = DB::table('an_pages')->where('status',1)->limit(30)->offset(30)->orderBy('id', 'DESC')->get();

How do you get the current page number of a ViewPager for Android?

For this problem Onpagechange listener is the best one But it will also have one small mistake that is it will not detect the starting time time of 0th position Once you will change the page it will starts to detect the Page selected position...For this problem I fount the easiest solution

1.You have to maintain the selected position value then use it....
2. Case 1: At the starting of the position is always Zero....
Case 2: Suppose if you set the current item means you will set that value into maintain position
3.Then do your action with the use of that maintain in your activity...

Public int maintain=0;
myViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int i, float v, int i2) {
             //Toast.makeText(MyActivity.this, i+"  Is Selected  "+data.size(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onPageSelected( int i) {
          // here you will get the position of selected page
            maintain = i;


        }

        @Override
        public void onPageScrollStateChanged(int i) {

        }
    });


updateButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            Toast.makeText(MyActivity.this, i+"  Is Selected  "+data.size(), Toast.LENGTH_SHORT).show();
            data.set(maintain, "Replaced "+maintain);         
            myViewPager.getAdapter().notifyDataSetChanged();
        }
    });

How to round the minute of a datetime object

Pandas has a datetime round feature, but as with most things in Pandas it needs to be in Series format.

>>> ts = pd.Series(pd.date_range(Dt(2019,1,1,1,1),Dt(2019,1,1,1,4),periods=8))
>>> print(ts)
0   2019-01-01 01:01:00.000000000
1   2019-01-01 01:01:25.714285714
2   2019-01-01 01:01:51.428571428
3   2019-01-01 01:02:17.142857142
4   2019-01-01 01:02:42.857142857
5   2019-01-01 01:03:08.571428571
6   2019-01-01 01:03:34.285714285
7   2019-01-01 01:04:00.000000000
dtype: datetime64[ns]

>>> ts.dt.round('1min')
0   2019-01-01 01:01:00
1   2019-01-01 01:01:00
2   2019-01-01 01:02:00
3   2019-01-01 01:02:00
4   2019-01-01 01:03:00
5   2019-01-01 01:03:00
6   2019-01-01 01:04:00
7   2019-01-01 01:04:00
dtype: datetime64[ns]

Docs - Change the frequency string as needed.

base64 encoded images in email signatures

The image should be embedded in the message as an attachment like this:

--boundary
Content-Type: image/png; name="sig.png"
Content-Disposition: inline; filename="sig.png"
Content-Transfer-Encoding: base64
Content-ID: <0123456789>
Content-Location: sig.png

base64 data

--boundary

And, the HTML part would reference the image like this:

<img src="cid:0123456789">

In some clients, src="sig.png" will work too.

You'd basically have a multipart/mixed, multipart/alternative, multipart/related message where the image attachment is in the related part.

Clients shouldn't block this image either as it isn't remote.

Or, here's a multipart/alternative, multipart/related example as an mbox file (save as windows newline format and put a blank line at the end. And, use no extension or the .mbs extension):

From 
From: [email protected]
To: [email protected]
Subject: HTML Messages with Embedded Pic in Signature
MIME-Version: 1.0
Content-Type: multipart/alternative; boundary="alternative_boundary"

This is a message with multiple parts in MIME format.

--alternative_boundary
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 8bit

test

-- 
[Picture of a Christmas Tree]

--alternative_boundary
Content-Type: multipart/related; boundary="related_boundary"

--related_boundary
Content-Type: text/html; charset="utf-8"
Content-Transfer-Encoding: 8bit

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <p>test</p>
        <p class="sig">-- <br><img src="cid:0123456789"></p>
    </body>
</html>

--related_boundary
Content-Type: image/png; name="sig.png"
Content-Disposition: inline; filename="sig.png"
Content-Location: sig.png
Content-ID: <0123456789>
Content-Transfer-Encoding: base64

R0lGODlhKAA8AIMLAAD//wAhAABKAABrAACUAAC1AADeAAD/AGsAAP8zM///AP//
///M//////+ZAMwAACH/C05FVFNDQVBFMi4wAwGgDwAh+QQJFAALACwAAAAAKAA8
AAME+3DJSWt1Nuu9Mf+g5IzK6IXopaxn6orlKy/jMc6vQRy4GySABK+HAiaIoQdg
uUSCBAKAYTBwbgyGA2AgsGqo0wMh7K0YEuj0sUxRoAfqB1vycBN21Ki8vOofBndR
c1AKgH8ETE1lBgo7O2JaU2UFAgRoDGoAXV4PD2qYagl7Vp0JDKenfwado0QCAQOQ
DIcDBgIFVgYBAlOxswR5r1VIUbCHwH8HlQWFRLYABVOWamACCkiJAAehaX0rPZ1B
oQSg3Z04AuFqB2IMd+atLwUBtpAHqKdUtbwGM1BTOgA5YhBr374ZAxhAqRVLzA53
OwTEAjhDIZYs09aBASYq+94HfAq3cRt57sWDct2EvEsTpBMVF6sYeEpDQIFDdo62
BHwZApjEhjW94RyQTWK/FPx+Ahpg09GdOzoJ/ESx0JaOQ42e2tsiEYpCEFwAGi04
8g6gSgNOovD0gBeVjCPR2BIAkgOrmSNxPo3rbhgHZiMFPnLkBg2BAuQ2XdmlwK1Z
ooZu1sRz6xWlxd4U9GIHwOmdzFgCFKCERYNoeo2BZsPp0KY+A/OAfZDYWKJZLZBo
1mQXdlojvxNYiXrD8I+2uEvTdFJQksID0XjXiUwjJm6CzBVeBQgwBop1ZPpC8RKt
YN5RCpS6XiyMht093o8KcFFf/vKE0dCmaLeWYhQMwbeQaHLRfNk9o5Q13lQGklFQ
aMLFRLcwcN5qSWmGxS2jKQQFL9nEAgxsDEiwlAHaPPJWIfroo6FVEun0VkL4UABA
CAjUiIAFM2YQogzcoLCjC3HNsYB1aSBB5JFrZBABACH5BAkUAAsALAAAAAAoADwA
AwT7cMlJa3U2670x/6DkjKQXnleJrqnJruMxvq8xHDQbJEyC5yheAnh6MI5HYkgg
YNgGSo7BcGAMBNHNYGA7ELpZiyFBLg/DFvLArEBPHoAEgXDYChQP90IAoNYJCoGB
aACFhX8HBwoGegYAdHReijZoBXxmPWRYYQ8PZmSZZHmcnqBITp2jSgIBN5BVBFwC
BVkGAQJPiVV2rFCrCq1/sXUHAgQFAL45BncFNgSfW8wASoKBB59lhoVAnQqfDNCf
AJ05At5msHPiCeSqLwUBzF6nVnXSuIwvTDYGsXPhiMmSRUOWAC436HmZU+yGDQYF
81FhV+aevzUM3oHoZBD7W7Zs9VaUIhOn4pwE38p0srLCQCqSciBFUuBFGgEryj7E
Ojhg2yOG1hQMIMCEy4p8PB8llKmAIReiW040keUvmUygiexcwbWJwxUrzBDW+Thn
qLEB5UDUe0LxYwJmAhKk+pAqVLZE69qWGZpTQwG7ZISuw7uwzDFAXTXYYoJraKym
Q/HSASDpiiUFljbYitfYRtCF635yMRBUn4UA8aYclCw0shefW7gUgPxBKGPHA5pK
MpwsKy5AcmNZSIVHjdjI2eLwVZlK44IHQT8lkq7XTDznrAIEWMTErZwbsT/hQj1L
noXLV6YwS5eIJqIDf4tyLZB5Av1ZNrLzQSplrXVkOgxItBU1E+DCwC2xFZUME5dZ
c5AB9aw2jXkSQLhFIrj4xAx9szGWzwABdkGATwuAeEokW4wY24oK8MMViAjxxcc8
E0CUAYETIKAjAifgWGMI2ehBgVtCeleGEkYmeUYGEQAAIfkECRQACwAsAAAAACgA
PAADBPtwyUlrdTbrvTH/oOSMpBeeV4muqcmu4zG+r6EcNBskSoLnJ4VQCAw9ErzE
oxgSCBSGwYDJMRgOhIGAupFGsVEG12JAmpHicaU3QDPe6fHjoSAQDlIBY6leDIUD
dnp9C04DdXh3eAaEUTeKdwJRagUCBGdnW3JHmJh8XHNmWAeLDwCfRQIBA6MMiQMG
AgBcBgGSUgeuWQMAvb1MAgWruXAMrJYAUkU2wVGXDGZeAIxMCgVfaJhOVkB/PWeX
nXM5AnScSKR2dmZzqCwFUAKjo1l4XpLULNuwWXYHAHgWCYD15AXBgV+wEACg7sDA
A45oaLFy5ZKvXvYMEPCGYvvOwQOYAHRCQufFuU7/wp2Zo2AKCgPtwN3xR8/LLpcg
kg1khaVlQyw8GRAwlC8nvp2HeM5UR8CYxp05L8ay8YcplmLGtmniwCtKLFhJR9oR
amnAuBAiH9wK9G1kAgaxBCg5u6HdSUzp1LlNCqJAgZGBaC41Q6DAUAUfajm5ZUdK
v7z08ATjmKGWAltecaVTqE5oFisB/EIpSiH06IcKpQTa3JSVagPCWm7wZsgOwJkg
3xaTrJFkFgvtFHDywmt1J2iB2pC0C9x0yItnsLx1K8xdoQDYCcQ9I5KwaynaalUS
RnpBpYH4YiXoTipgIlIFtLSUFKwSBb/NtGCnb2Zl51fHo8hnhRZbSfCEKkgZkkcw
TgBgyVdxeQNRMNNMoMBOpBxFUSx+ObgYPgS1BBRss/jxxzwAqsbLRfwh1VJyF5WI
2AkIAIAAAiiUKMGMICDRXQIn6IiCW4Qs4NYZTByppBkbRAAAIf4ZQm95J3MgSGFw
cHkgSG9saWRheXMgUGFnZQA7

--related_boundary--

--alternative_boundary--

You can import that into Sylpheed or Thunderbird (with the Import/Export tools extension) or Opera's built-in mail client. Then, in Opera for example, you can toggle "prefer plain text" to see the difference between the HTML and text version. Anyway, you'll see the HTML version makes use of the embedded pic in the sig.

Where is the default log location for SharePoint/MOSS?

In Sharepoint Server 2010 they are stored here:

"c:\Program Files\Common Files\Microsoft Shared\web server extensions\14\LOGS"

To view them you can use ULS Viewer by Microsoft (unsupported). http://ulsviewer.codeplex.com/

How can I expand and collapse a <div> using javascript?

Okay, so you've got two options here :

  1. Use jQuery UI's accordion - its nice, easy and fast. See more info here
  2. Or, if you still wanna do this by yourself, you could remove the fieldset (its not semantically right to use it for this anyway) and create a structure by yourself.

Here's how you do that. Create a HTML structure like this :

<div class="container">
    <div class="header"><span>Expand</span>

    </div>
    <div class="content">
        <ul>
            <li>This is just some random content.</li>
            <li>This is just some random content.</li>
            <li>This is just some random content.</li>
            <li>This is just some random content.</li>
        </ul>
    </div>
</div>

With this CSS: (This is to hide the .content stuff when the page loads.

.container .content {
    display: none;
    padding : 5px;
}

Then, using jQuery, write a click event for the header.

$(".header").click(function () {

    $header = $(this);
    //getting the next element
    $content = $header.next();
    //open up the content needed - toggle the slide- if visible, slide up, if not slidedown.
    $content.slideToggle(500, function () {
        //execute this after slideToggle is done
        //change text of header based on visibility of content div
        $header.text(function () {
            //change text based on condition
            return $content.is(":visible") ? "Collapse" : "Expand";
        });
    });

});

Here's a demo : http://jsfiddle.net/hungerpain/eK8X5/7/

How to have the formatter wrap code with IntelliJ?

Do you mean that the formatter does not break long lines? Check Settings / Project Settings / Code Style / Wrapping.

Update: in later versions of IntelliJ, the option is under Settings / Editor / Code Style. And select Wrap when typing reaches right margin.

Accessing clicked element in angularjs

While AngularJS allows you to get a hand on a click event (and thus a target of it) with the following syntax (note the $event argument to the setMaster function; documentation here: http://docs.angularjs.org/api/ng.directive:ngClick):

function AdminController($scope) {    
  $scope.setMaster = function(obj, $event){
    console.log($event.target);
  }
}

this is not very angular-way of solving this problem. With AngularJS the focus is on the model manipulation. One would mutate a model and let AngularJS figure out rendering.

The AngularJS-way of solving this problem (without using jQuery and without the need to pass the $event argument) would be:

<div ng-controller="AdminController">
    <ul class="list-holder">
        <li ng-repeat="section in sections" ng-class="{active : isSelected(section)}">
            <a ng-click="setMaster(section)">{{section.name}}</a>
        </li>
    </ul>
    <hr>
    {{selected | json}}
</div>

where methods in the controller would look like this:

$scope.setMaster = function(section) {
    $scope.selected = section;
}

$scope.isSelected = function(section) {
    return $scope.selected === section;
}

Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/WXJ3p/15/

Memory errors and list limits?

First off, see How Big can a Python Array Get? and Numpy, problem with long arrays

Second, the only real limit comes from the amount of memory you have and how your system stores memory references. There is no per-list limit, so Python will go until it runs out of memory. Two possibilities:

  1. If you are running on an older OS or one that forces processes to use a limited amount of memory, you may need to increase the amount of memory the Python process has access to.
  2. Break the list apart using chunking. For example, do the first 1000 elements of the list, pickle and save them to disk, and then do the next 1000. To work with them, unpickle one chunk at a time so that you don't run out of memory. This is essentially the same technique that databases use to work with more data than will fit in RAM.

How can I print message in Makefile?

$(info your_text) : Information. This doesn't stop the execution.

$(warning your_text) : Warning. This shows the text as a warning.

$(error your_text) : Fatal Error. This will stop the execution.

How to send value attribute from radio button in PHP

Should be :

HTML :

<form method="post" action="">
    <input id="name" name="name" type="text" size="40"/>
    <input type="radio" name="radio" value="test"/>Test
    <input type="submit" name="submit" value="submit"/>
</form>

PHP Code :

if(isset($_POST['submit']))
{

    echo $radio_value = $_POST["radio"];
}

How to compare objects by multiple fields

Better late than never - if you're looking for unnecessary clutter or overhead then it's hard to beat the following in terms of least code/fast execution at the same time.

Data class:

public class MyData {
    int id;
    boolean relevant;
    String name;
    float value;
}

Comparator:

public class MultiFieldComparator implements Comparator<MyData> {
    @Override
    public int compare(MyData dataA, MyData dataB) {
        int result;
        if((result = Integer.compare(dataA.id, dataB.id)) == 0 &&
           (result = Boolean.compare(dataA.relevant, dataB.relevant)) == 0 &&
           (result = dataA.name.compareTo(dataB.name)) == 0)
            result = Float.compare(dataA.value, dataB.value);
        return result;
    }
}

If you are just looking to sort a collection by a custom order then the following is even cleaner:

myDataList.sort((dataA, dataB) -> {
    int result;
    if((result = Integer.compare(dataA.id, dataB.id)) == 0 &&
       (result = Boolean.compare(dataA.relevant, dataB.relevant)) == 0 &&
       (result = dataA.name.compareTo(dataB.name)) == 0)
        result = Float.compare(dataA.value, dataB.value);
    return result;
});

How do I edit a file after I shell to a Docker container?

You can just edit your file on host and quickly copy it into and run it inside the container. Here is my one-line shortcut to copy and run a Python file:

docker cp main.py my-container:/data/scripts/ ; docker exec -it my-container python /data/scripts/main.py

Request format is unrecognized for URL unexpectedly ending in

For the record I was getting this error when I moved an old app from one server to another. I added the <add name="HttpGet"/> <add name="HttpPost"/> elements to the web.config, which changed the error to:

System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at BitMeter2.DataBuffer.incrementCurrent(Int64 val)
   at BitMeter2.DataBuffer.WindOn(Int64 count, Int64 amount)
   at BitMeter2.DataHistory.windOnBuffer(DataBuffer buffer, Int64 totalAmount, Int32 increments)
   at BitMeter2.DataHistory.NewData(Int64 downloadValue, Int64 uploadValue)
   at BitMeter2.frmMain.tickProcessing(Boolean fromTimerEvent)

In order to fix this error I had to add the ScriptHandlerFactory lines to web.config:

  <system.webServer>
    <handlers>
      <remove name="ScriptHandlerFactory" />
      <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    </handlers>
  </system.webServer>

Why it worked without these lines on one web server and not the other I don't know.

"Could not find a version that satisfies the requirement opencv-python"

Another problem can be that the python version you are using is not yet supported by opencv-python.

E.g. as of right now there is no opencv-python for python 3.8. You would need to downgrade your python to 3.7.5 for now.

Listing all the folders subfolders and files in a directory using php

In case you want to use directoryIterator

Following function is a re-implementation of @Shef answer with directoryIterator

function listFolderFiles($dir)
{
    echo '<ol>';
    foreach (new DirectoryIterator($dir) as $fileInfo) {
        if (!$fileInfo->isDot()) {
            echo '<li>' . $fileInfo->getFilename();
            if ($fileInfo->isDir()) {
                listFolderFiles($fileInfo->getPathname());
            }
            echo '</li>';
        }
    }
    echo '</ol>';
}
listFolderFiles('Main Dir');

How to Display Selected Item in Bootstrap Button Dropdown Title

This single jQuery function will do all you need.

$( document ).ready(function() {
    $('.dropdown').each(function (key, dropdown) {
        var $dropdown = $(dropdown);
        $dropdown.find('.dropdown-menu a').on('click', function () {
            $dropdown.find('button').text($(this).text()).append(' <span class="caret"></span>');
        });
    });
});

How do I subscribe to all topics of a MQTT broker

You can use mosquitto_sub (which is part of the mosquitto-clients package) and subscribe to the wildcard topic #:

mosquitto_sub -v -h broker_ip -p 1883 -t '#'

Inserting an item in a Tuple

Since tuples are immutable, this will result in a new tuple. Just place it back where you got the old one.

sometuple + (someitem,)

How can I rollback a git repository to a specific commit?

Most suggestions are assuming that you need to somehow destroy the last 20 commits, which is why it means "rewriting history", but you don't have to.

Just create a new branch from the commit #80 and work on that branch going forward. The other 20 commits will stay on the old orphaned branch.

If you absolutely want your new branch to have the same name, remember that branch are basically just labels. Just rename your old branch to something else, then create the new branch at commit #80 with the name you want.

How to iterate through a DataTable

DataTable dt = new DataTable();

SqlDataAdapter adapter = new SqlDataAdapter(cmd);

adapter.Fill(dt);

foreach(DataRow row in dt.Rows)
{
    TextBox1.Text = row["ImagePath"].ToString();
}

...assumes the connection is open and the command is set up properly. I also didn't check the syntax, but it should give you the idea.

How to save the output of a console.log(object) to a file?

There is another open-source tool that allows you to save all console.log output in a file on your server - JS LogFlush (plug!).

JS LogFlush is an integrated JavaScript logging solution which include:

  • cross-browser UI-less replacement of console.log - on client side.
  • log storage system - on server side.

Demo

Twitter bootstrap scrollable modal

I´ve done a tiny solution using only jQuery.

First, you need to put an additional class to your <div class="modal-body"> I called "ativa-scroll", so it becomes something like this:

<div class="modal-body ativa-scroll">

So now just put this piece of code on your page, near your JS loading:

<script type="text/javascript">
  $(document).ready(ajustamodal);
  $(window).resize(ajustamodal);
  function ajustamodal() {
    var altura = $(window).height() - 155; //value corresponding to the modal heading + footer
    $(".ativa-scroll").css({"height":altura,"overflow-y":"auto"});
  }
</script>

I works perfectly for me, also in a responsive way! :)

How to delay the .keyup() handler until the user stops typing?

Use

mytimeout = setTimeout( expression, timeout );

where expression is the script to run and timeout is the time to wait in milliseconds before it runs - this does NOT hault the script, but simply delays execution of that part until the timeout is done.

clearTimeout(mytimeout);

will reset/clear the timeout so it does not run the script in expression (like a cancel) as long as it has not yet been executed.

In Angular, What is 'pathmatch: full' and what effect does it have?

pathMatch = 'full' results in a route hit when the remaining, unmatched segments of the URL match is the prefix path

pathMatch = 'prefix' tells the router to match the redirect route when the remaining URL begins with the redirect route's prefix path.

Ref: https://angular.io/guide/router#set-up-redirects

pathMatch: 'full' means, that the whole URL path needs to match and is consumed by the route matching algorithm.

pathMatch: 'prefix' means, the first route where the path matches the start of the URL is chosen, but then the route matching algorithm is continuing searching for matching child routes where the rest of the URL matches.

Check if object exists in JavaScript

There are a lot of half-truths here, so I thought I make some things clearer.

Actually you can't accurately tell if a variable exists (unless you want to wrap every second line into a try-catch block).

The reason is Javascript has this notorious value of undefined which strikingly doesn't mean that the variable is not defined, or that it doesn't exist undefined !== not defined

var a;
alert(typeof a); // undefined (declared without a value)
alert(typeof b); // undefined (not declared)

So both a variable that exists and another one that doesn't can report you the undefined type.

As for @Kevin's misconception, null == undefined. It is due to type coercion, and it's the main reason why Crockford keeps telling everyone who is unsure of this kind of thing to always use strict equality operator === to test for possibly falsy values. null !== undefined gives you what you might expect. Please also note, that foo != null can be an effective way to check if a variable is neither undefined nor null. Of course you can be explicit, because it may help readability.

If you restrict the question to check if an object exists, typeof o == "object" may be a good idea, except if you don't consider arrays objects, as this will also reported to be the type of object which may leave you a bit confused. Not to mention that typeof null will also give you object which is simply wrong.

The primal area where you really should be careful about typeof, undefined, null, unknown and other misteries are host objects. They can't be trusted. They are free to do almost any dirty thing they want. So be careful with them, check for functionality if you can, because it's the only secure way to use a feature that may not even exist.

How to create batch file in Windows using "start" with a path and command with spaces

start "" "c:\path with spaces\app.exe" "C:\path parameter\param.exe"

When I used above suggestion, I've got:

'c:\path' is not recognized a an internal or external command, operable program or batch file.

I think second qoutation mark prevent command to run. After some search below solution save my day:

start "" CALL "c:\path with spaces\app.exe" "C:\path parameter\param.exe"

in querySelector: how to get the first and get the last elements? what traversal order is used in the dom?

To access the first and last elements, try.

var nodes = div.querySelectorAll('[move_id]');
var first = nodes[0];
var last = nodes[nodes.length- 1];

For robustness, add index checks.

Yes, the order of nodes is pre-order depth-first. DOM's document order is defined as,

There is an ordering, document order, defined on all the nodes in the document corresponding to the order in which the first character of the XML representation of each node occurs in the XML representation of the document after expansion of general entities. Thus, the document element node will be the first node. Element nodes occur before their children. Thus, document order orders element nodes in order of the occurrence of their start-tag in the XML (after expansion of entities). The attribute nodes of an element occur after the element and before its children. The relative order of attribute nodes is implementation-dependent.

Is there a good jQuery Drag-and-drop file upload plugin?

Shameless Plug:

Filepicker.io handles uploading for you and returns a url. It supports drag/drop, cross browser. Also, people can upload from Dropbox/Facebook/Gmail which is super handy on a mobile device.

ScalaTest in sbt: is there a way to run a single test without tags?

I wanted to add a concrete example to accompany the other answers

You need to specify the name of the class that you want to test, so if you have the following project (this is a Play project):

Play Project

You can test just the Login tests by running the following command from the SBT console:

test:testOnly *LoginServiceSpec

If you are running the command from outside the SBT console, you would do the following:

sbt "test:testOnly *LoginServiceSpec"

How to expire a cookie in 30 minutes using jQuery?

I had issues getting the above code to work within cookie.js. The following code managed to create the correct timestamp for the cookie expiration in my instance.

var inFifteenMinutes = new Date(new Date().getTime() + 15 * 60 * 1000);

This was from the FAQs for Cookie.js

How do I load the contents of a text file into a javascript variable?

If your input was structured as XML, you could use the importXML function. (More info here at quirksmode).

If it isn't XML, and there isn't an equivalent function for importing plain text, then you could open it in a hidden iframe and then read the contents from there.

How to cast from List<Double> to double[] in Java?

As per your question,

List<Double> frameList =  new ArrayList<Double>();
  1. First you have to convert List<Double> to Double[] by using

    Double[] array = frameList.toArray(new Double[frameList.size()]);
    
  2. Next you can convert Double[] to double[] using

    double[] doubleArray = ArrayUtils.toPrimitive(array);
    

You can directly use it in one line:

double[] array = ArrayUtils.toPrimitive(frameList.toArray(new Double[frameList.size()]));

How to split a string in Ruby and get all items except the first one?

You can also do this:

String is ex="test1, test2, test3, test4, test5"
array = ex.split(/,/)
array.size.times do |i|
  p array[i]
end 

In Python, how to display current time in readable format

All you need is in the documentation.

import time
time.strftime('%X %x %Z')
'16:08:12 05/08/03 AEST'

Perform a Shapiro-Wilk Normality Test

What does shapiro.test do?

shapiro.test tests the Null hypothesis that "the samples come from a Normal distribution" against the alternative hypothesis "the samples do not come from a Normal distribution".

How to perform shapiro.test in R?

The R help page for ?shapiro.test gives,

x - a numeric vector of data values. Missing values are allowed, 
    but the number of non-missing values must be between 3 and 5000.

That is, shapiro.test expects a numeric vector as input, that corresponds to the sample you would like to test and it is the only input required. Since you've a data.frame, you'll have to pass the desired column as input to the function as follows:

> shapiro.test(heisenberg$HWWIchg)
#   Shapiro-Wilk normality test

# data:  heisenberg$HWWIchg 
# W = 0.9001, p-value = 0.2528

Interpreting results from shapiro.test:

First, I strongly suggest you read this excellent answer from Ian Fellows on testing for normality.

As shown above, the shapiro.test tests the NULL hypothesis that the samples came from a Normal distribution. This means that if your p-value <= 0.05, then you would reject the NULL hypothesis that the samples came from a Normal distribution. As Ian Fellows nicely put it, you are testing against the assumption of Normality". In other words (correct me if I am wrong), it would be much better if one tests the NULL hypothesis that the samples do not come from a Normal distribution. Why? Because, rejecting a NULL hypothesis is not the same as accepting the alternative hypothesis.

In case of the null hypothesis of shapiro.test, a p-value <= 0.05 would reject the null hypothesis that the samples come from normal distribution. To put it loosely, there is a rare chance that the samples came from a normal distribution. The side-effect of this hypothesis testing is that this rare chance happens very rarely. To illustrate, take for example:

set.seed(450)
x <- runif(50, min=2, max=4)
shapiro.test(x)
#   Shapiro-Wilk normality test
# data:  runif(50, min = 2, max = 4) 
# W = 0.9601, p-value = 0.08995

So, this (particular) sample runif(50, min=2, max=4) comes from a normal distribution according to this test. What I am trying to say is that, there are many many cases under which the "extreme" requirements (p < 0.05) are not satisfied which leads to acceptance of "NULL hypothesis" most of the times, which might be misleading.

Another issue I'd like to quote here from @PaulHiemstra from under comments about the effects on large sample size:

An additional issue with the Shapiro-Wilk's test is that when you feed it more data, the chances of the null hypothesis being rejected becomes larger. So what happens is that for large amounts of data even very small deviations from normality can be detected, leading to rejection of the null hypothesis event though for practical purposes the data is more than normal enough.

Although he also points out that R's data size limit protects this a bit:

Luckily shapiro.test protects the user from the above described effect by limiting the data size to 5000.

If the NULL hypothesis were the opposite, meaning, the samples do not come from a normal distribution, and you get a p-value < 0.05, then you conclude that it is very rare that these samples do not come from a normal distribution (reject the NULL hypothesis). That loosely translates to: It is highly likely that the samples are normally distributed (although some statisticians may not like this way of interpreting). I believe this is what Ian Fellows also tried to explain in his post. Please correct me if I've gotten something wrong!

@PaulHiemstra also comments about practical situations (example regression) when one comes across this problem of testing for normality:

In practice, if an analysis assumes normality, e.g. lm, I would not do this Shapiro-Wilk's test, but do the analysis and look at diagnostic plots of the outcome of the analysis to judge whether any assumptions of the analysis where violated too much. For linear regression using lm this is done by looking at some of the diagnostic plots you get using plot(lm()). Statistics is not a series of steps that cough up a few numbers (hey p < 0.05!) but requires a lot of experience and skill in judging how to analysis your data correctly.

Here, I find the reply from Ian Fellows to Ben Bolker's comment under the same question already linked above equally (if not more) informative:

For linear regression,

  1. Don't worry much about normality. The CLT takes over quickly and if you have all but the smallest sample sizes and an even remotely reasonable looking histogram you are fine.

  2. Worry about unequal variances (heteroskedasticity). I worry about this to the point of (almost) using HCCM tests by default. A scale location plot will give some idea of whether this is broken, but not always. Also, there is no a priori reason to assume equal variances in most cases.

  3. Outliers. A cooks distance of > 1 is reasonable cause for concern.

Those are my thoughts (FWIW).

Hope this clears things up a bit.

how to get javaScript event source element?

You can pass this when you call the function

<button onclick="doSomething('param',this)" id="id_button">action</button>

<script>
    function doSomething(param,me){

    var source = me
    console.log(source);
}
</script>

string.split - by multiple character delimiter

Regex.Split("abc][rfd][5][,][.", @"\]\]");

How to install OpenSSL in windows 10?

I also wanted to create OPEN SSL for Windows 10. An easy way of getting it done without running into a risk of installing unknown software from 3rd party websites and risking entries of viruses, is by using the openssl.exe that comes inside your Git for Windows installation. In my case, I found the open SSL in the following location of Git for Windows Installation.

C:\Program Files\Git\usr\bin\openssl.exe

If you also want instructions on how to use OPENSSL to generate and use Certificates. Here is a write-up on my blog. The step by step instructions first explains how to use Microsoft Windows Default Tool and also OPEN SSL and explains the difference between them.

http://kaushikghosh12.blogspot.com/2016/08/self-signed-certificates-with-microsoft.html

How to retrieve the hash for the current commit in Git?

The most succinct way I know:

git show --pretty=%h 

If you want a specific number of digits of the hash you can add:

--abbrev=n

Check if table exists in SQL Server

IF OBJECT_ID('mytablename') IS NOT NULL 

How to fix an UnsatisfiedLinkError (Can't find dependent libraries) in a JNI project

installing Microsoft Visual C++ 2010 SP1 Redistributable Fixed it

SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable

For me the problem was that I haven't created any virtual devices after fresh installation of android studio. So, expo kept complaining vaguely about the sdk location while the main issue was the missing virtual devices. Hope this helps somebody in the future, had me searching for a couple of hours.

PS: here you can find out how to create one https://developer.android.com/studio/run/managing-avds

Create ArrayList from array

Given Object Array:

Element[] array = {new Element(1), new Element(2), new Element(3) , new Element(2)};

Convert Array to List:

    List<Element> list = Arrays.stream(array).collect(Collectors.toList());

Convert Array to ArrayList

    ArrayList<Element> arrayList = Arrays.stream(array)
                                       .collect(Collectors.toCollection(ArrayList::new));

Convert Array to LinkedList

    LinkedList<Element> linkedList = Arrays.stream(array)
                     .collect(Collectors.toCollection(LinkedList::new));

Print List:

    list.forEach(element -> {
        System.out.println(element.i);
    });

OUTPUT

1

2

3

How do you get centered content using Twitter Bootstrap?

Center-block is also an option not referred in above answers

    <div class="center-block" style="width:200px;background-color:#ccc;">...</div>

All the class center-block does is to tell the element to have a margin of 0 auto, the auto being the left/right margins. However, unless the class text-center or css text-align:center; is set on the parent, the element does not know the point to work out this auto calculation from, so it will not center itself as anticipated.

So text-center is a better option.

When should we use intern method of String on String literals

String literals and constants are interned by default. That is, "foo" == "foo" (declared by the String literals), but new String("foo") != new String("foo").

Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android

Run:

cordova platform update [email protected]

And make sure that Android Studio and Android Studio environment variable refrence to same location.

I fix this by copying Android Studio from:

D:\Program Files\Android

to

C:\Program Files\Android

List all indexes on ElasticSearch server?

I would also recommend doing /_cat/indices which gives a nice human readable list of your indexes.

When is the init() function run?

Take for example a framework or a library you're designing for other users, these users eventually will have a main function in their code in order to execute their app. If the user directly imports a sub-package of your library's project then the init of that sub-package will be called(once) first of all. The same for the root package of the library, etc...

There are many times when you may want a code block to be executed without the existence of a main func, directly or not.

If you, as the developer of the imaginary library, import your library's sub-package that has an init function, it will be called first and once, you don't have a main func but you need to make sure that some variables, or a table, will be initialized before the calls of other functions.

A good thing to remember and not to worry about, is that: the init always execute once per application.

init execution happens:

  1. right before the init function of the "caller" package,
  2. before the, optionally, main func,
  3. but after the package-level variables, var = [...] or cost = [...],

When you import a package it will run all of its init functions, by order.

I'll will give a very good example of an init function. It will add mime types to a standard go's library named mime and a package-level function will use the mime standard package directly to get the custom mime types that are already be initialized at its init function:

package mime

import (
    "mime"
    "path/filepath"
)

var types = map[string]string{
    ".3dm":       "x-world/x-3dmf",
    ".3dmf":      "x-world/x-3dmf",
    ".7z":        "application/x-7z-compressed",
    ".a":         "application/octet-stream",
    ".aab":       "application/x-authorware-bin",
    ".aam":       "application/x-authorware-map",
    ".aas":       "application/x-authorware-seg",
    ".abc":       "text/vndabc",
    ".ace":       "application/x-ace-compressed",
    ".acgi":      "text/html",
    ".afl":       "video/animaflex",
    ".ai":        "application/postscript",
    ".aif":       "audio/aiff",
    ".aifc":      "audio/aiff",
    ".aiff":      "audio/aiff",
    ".aim":       "application/x-aim",
    ".aip":       "text/x-audiosoft-intra",
    ".alz":       "application/x-alz-compressed",
    ".ani":       "application/x-navi-animation",
    ".aos":       "application/x-nokia-9000-communicator-add-on-software",
    ".aps":       "application/mime",
    ".apk":       "application/vnd.android.package-archive",
    ".arc":       "application/x-arc-compressed",
    ".arj":       "application/arj",
    ".art":       "image/x-jg",
    ".asf":       "video/x-ms-asf",
    ".asm":       "text/x-asm",
    ".asp":       "text/asp",
    ".asx":       "application/x-mplayer2",
    ".au":        "audio/basic",
    ".avi":       "video/x-msvideo",
    ".avs":       "video/avs-video",
    ".bcpio":     "application/x-bcpio",
    ".bin":       "application/mac-binary",
    ".bmp":       "image/bmp",
    ".boo":       "application/book",
    ".book":      "application/book",
    ".boz":       "application/x-bzip2",
    ".bsh":       "application/x-bsh",
    ".bz2":       "application/x-bzip2",
    ".bz":        "application/x-bzip",
    ".c++":       "text/plain",
    ".c":         "text/x-c",
    ".cab":       "application/vnd.ms-cab-compressed",
    ".cat":       "application/vndms-pkiseccat",
    ".cc":        "text/x-c",
    ".ccad":      "application/clariscad",
    ".cco":       "application/x-cocoa",
    ".cdf":       "application/cdf",
    ".cer":       "application/pkix-cert",
    ".cha":       "application/x-chat",
    ".chat":      "application/x-chat",
    ".chrt":      "application/vnd.kde.kchart",
    ".class":     "application/java",
    ".com":       "text/plain",
    ".conf":      "text/plain",
    ".cpio":      "application/x-cpio",
    ".cpp":       "text/x-c",
    ".cpt":       "application/mac-compactpro",
    ".crl":       "application/pkcs-crl",
    ".crt":       "application/pkix-cert",
    ".crx":       "application/x-chrome-extension",
    ".csh":       "text/x-scriptcsh",
    ".css":       "text/css",
    ".csv":       "text/csv",
    ".cxx":       "text/plain",
    ".dar":       "application/x-dar",
    ".dcr":       "application/x-director",
    ".deb":       "application/x-debian-package",
    ".deepv":     "application/x-deepv",
    ".def":       "text/plain",
    ".der":       "application/x-x509-ca-cert",
    ".dif":       "video/x-dv",
    ".dir":       "application/x-director",
    ".divx":      "video/divx",
    ".dl":        "video/dl",
    ".dmg":       "application/x-apple-diskimage",
    ".doc":       "application/msword",
    ".dot":       "application/msword",
    ".dp":        "application/commonground",
    ".drw":       "application/drafting",
    ".dump":      "application/octet-stream",
    ".dv":        "video/x-dv",
    ".dvi":       "application/x-dvi",
    ".dwf":       "drawing/x-dwf=(old)",
    ".dwg":       "application/acad",
    ".dxf":       "application/dxf",
    ".dxr":       "application/x-director",
    ".el":        "text/x-scriptelisp",
    ".elc":       "application/x-bytecodeelisp=(compiled=elisp)",
    ".eml":       "message/rfc822",
    ".env":       "application/x-envoy",
    ".eps":       "application/postscript",
    ".es":        "application/x-esrehber",
    ".etx":       "text/x-setext",
    ".evy":       "application/envoy",
    ".exe":       "application/octet-stream",
    ".f77":       "text/x-fortran",
    ".f90":       "text/x-fortran",
    ".f":         "text/x-fortran",
    ".fdf":       "application/vndfdf",
    ".fif":       "application/fractals",
    ".fli":       "video/fli",
    ".flo":       "image/florian",
    ".flv":       "video/x-flv",
    ".flx":       "text/vndfmiflexstor",
    ".fmf":       "video/x-atomic3d-feature",
    ".for":       "text/x-fortran",
    ".fpx":       "image/vndfpx",
    ".frl":       "application/freeloader",
    ".funk":      "audio/make",
    ".g3":        "image/g3fax",
    ".g":         "text/plain",
    ".gif":       "image/gif",
    ".gl":        "video/gl",
    ".gsd":       "audio/x-gsm",
    ".gsm":       "audio/x-gsm",
    ".gsp":       "application/x-gsp",
    ".gss":       "application/x-gss",
    ".gtar":      "application/x-gtar",
    ".gz":        "application/x-compressed",
    ".gzip":      "application/x-gzip",
    ".h":         "text/x-h",
    ".hdf":       "application/x-hdf",
    ".help":      "application/x-helpfile",
    ".hgl":       "application/vndhp-hpgl",
    ".hh":        "text/x-h",
    ".hlb":       "text/x-script",
    ".hlp":       "application/hlp",
    ".hpg":       "application/vndhp-hpgl",
    ".hpgl":      "application/vndhp-hpgl",
    ".hqx":       "application/binhex",
    ".hta":       "application/hta",
    ".htc":       "text/x-component",
    ".htm":       "text/html",
    ".html":      "text/html",
    ".htmls":     "text/html",
    ".htt":       "text/webviewhtml",
    ".htx":       "text/html",
    ".ice":       "x-conference/x-cooltalk",
    ".ico":       "image/x-icon",
    ".ics":       "text/calendar",
    ".icz":       "text/calendar",
    ".idc":       "text/plain",
    ".ief":       "image/ief",
    ".iefs":      "image/ief",
    ".iges":      "application/iges",
    ".igs":       "application/iges",
    ".ima":       "application/x-ima",
    ".imap":      "application/x-httpd-imap",
    ".inf":       "application/inf",
    ".ins":       "application/x-internett-signup",
    ".ip":        "application/x-ip2",
    ".isu":       "video/x-isvideo",
    ".it":        "audio/it",
    ".iv":        "application/x-inventor",
    ".ivr":       "i-world/i-vrml",
    ".ivy":       "application/x-livescreen",
    ".jam":       "audio/x-jam",
    ".jav":       "text/x-java-source",
    ".java":      "text/x-java-source",
    ".jcm":       "application/x-java-commerce",
    ".jfif-tbnl": "image/jpeg",
    ".jfif":      "image/jpeg",
    ".jnlp":      "application/x-java-jnlp-file",
    ".jpe":       "image/jpeg",
    ".jpeg":      "image/jpeg",
    ".jpg":       "image/jpeg",
    ".jps":       "image/x-jps",
    ".js":        "application/javascript",
    ".json":      "application/json",
    ".jut":       "image/jutvision",
    ".kar":       "audio/midi",
    ".karbon":    "application/vnd.kde.karbon",
    ".kfo":       "application/vnd.kde.kformula",
    ".flw":       "application/vnd.kde.kivio",
    ".kml":       "application/vnd.google-earth.kml+xml",
    ".kmz":       "application/vnd.google-earth.kmz",
    ".kon":       "application/vnd.kde.kontour",
    ".kpr":       "application/vnd.kde.kpresenter",
    ".kpt":       "application/vnd.kde.kpresenter",
    ".ksp":       "application/vnd.kde.kspread",
    ".kwd":       "application/vnd.kde.kword",
    ".kwt":       "application/vnd.kde.kword",
    ".ksh":       "text/x-scriptksh",
    ".la":        "audio/nspaudio",
    ".lam":       "audio/x-liveaudio",
    ".latex":     "application/x-latex",
    ".lha":       "application/lha",
    ".lhx":       "application/octet-stream",
    ".list":      "text/plain",
    ".lma":       "audio/nspaudio",
    ".log":       "text/plain",
    ".lsp":       "text/x-scriptlisp",
    ".lst":       "text/plain",
    ".lsx":       "text/x-la-asf",
    ".ltx":       "application/x-latex",
    ".lzh":       "application/octet-stream",
    ".lzx":       "application/lzx",
    ".m1v":       "video/mpeg",
    ".m2a":       "audio/mpeg",
    ".m2v":       "video/mpeg",
    ".m3u":       "audio/x-mpegurl",
    ".m":         "text/x-m",
    ".man":       "application/x-troff-man",
    ".manifest":  "text/cache-manifest",
    ".map":       "application/x-navimap",
    ".mar":       "text/plain",
    ".mbd":       "application/mbedlet",
    ".mc$":       "application/x-magic-cap-package-10",
    ".mcd":       "application/mcad",
    ".mcf":       "text/mcf",
    ".mcp":       "application/netmc",
    ".me":        "application/x-troff-me",
    ".mht":       "message/rfc822",
    ".mhtml":     "message/rfc822",
    ".mid":       "application/x-midi",
    ".midi":      "application/x-midi",
    ".mif":       "application/x-frame",
    ".mime":      "message/rfc822",
    ".mjf":       "audio/x-vndaudioexplosionmjuicemediafile",
    ".mjpg":      "video/x-motion-jpeg",
    ".mm":        "application/base64",
    ".mme":       "application/base64",
    ".mod":       "audio/mod",
    ".moov":      "video/quicktime",
    ".mov":       "video/quicktime",
    ".movie":     "video/x-sgi-movie",
    ".mp2":       "audio/mpeg",
    ".mp3":       "audio/mpeg3",
    ".mp4":       "video/mp4",
    ".mpa":       "audio/mpeg",
    ".mpc":       "application/x-project",
    ".mpe":       "video/mpeg",
    ".mpeg":      "video/mpeg",
    ".mpg":       "video/mpeg",
    ".mpga":      "audio/mpeg",
    ".mpp":       "application/vndms-project",
    ".mpt":       "application/x-project",
    ".mpv":       "application/x-project",
    ".mpx":       "application/x-project",
    ".mrc":       "application/marc",
    ".ms":        "application/x-troff-ms",
    ".mv":        "video/x-sgi-movie",
    ".my":        "audio/make",
    ".mzz":       "application/x-vndaudioexplosionmzz",
    ".nap":       "image/naplps",
    ".naplps":    "image/naplps",
    ".nc":        "application/x-netcdf",
    ".ncm":       "application/vndnokiaconfiguration-message",
    ".nif":       "image/x-niff",
    ".niff":      "image/x-niff",
    ".nix":       "application/x-mix-transfer",
    ".nsc":       "application/x-conference",
    ".nvd":       "application/x-navidoc",
    ".o":         "application/octet-stream",
    ".oda":       "application/oda",
    ".odb":       "application/vnd.oasis.opendocument.database",
    ".odc":       "application/vnd.oasis.opendocument.chart",
    ".odf":       "application/vnd.oasis.opendocument.formula",
    ".odg":       "application/vnd.oasis.opendocument.graphics",
    ".odi":       "application/vnd.oasis.opendocument.image",
    ".odm":       "application/vnd.oasis.opendocument.text-master",
    ".odp":       "application/vnd.oasis.opendocument.presentation",
    ".ods":       "application/vnd.oasis.opendocument.spreadsheet",
    ".odt":       "application/vnd.oasis.opendocument.text",
    ".oga":       "audio/ogg",
    ".ogg":       "audio/ogg",
    ".ogv":       "video/ogg",
    ".omc":       "application/x-omc",
    ".omcd":      "application/x-omcdatamaker",
    ".omcr":      "application/x-omcregerator",
    ".otc":       "application/vnd.oasis.opendocument.chart-template",
    ".otf":       "application/vnd.oasis.opendocument.formula-template",
    ".otg":       "application/vnd.oasis.opendocument.graphics-template",
    ".oth":       "application/vnd.oasis.opendocument.text-web",
    ".oti":       "application/vnd.oasis.opendocument.image-template",
    ".otm":       "application/vnd.oasis.opendocument.text-master",
    ".otp":       "application/vnd.oasis.opendocument.presentation-template",
    ".ots":       "application/vnd.oasis.opendocument.spreadsheet-template",
    ".ott":       "application/vnd.oasis.opendocument.text-template",
    ".p10":       "application/pkcs10",
    ".p12":       "application/pkcs-12",
    ".p7a":       "application/x-pkcs7-signature",
    ".p7c":       "application/pkcs7-mime",
    ".p7m":       "application/pkcs7-mime",
    ".p7r":       "application/x-pkcs7-certreqresp",
    ".p7s":       "application/pkcs7-signature",
    ".p":         "text/x-pascal",
    ".part":      "application/pro_eng",
    ".pas":       "text/pascal",
    ".pbm":       "image/x-portable-bitmap",
    ".pcl":       "application/vndhp-pcl",
    ".pct":       "image/x-pict",
    ".pcx":       "image/x-pcx",
    ".pdb":       "chemical/x-pdb",
    ".pdf":       "application/pdf",
    ".pfunk":     "audio/make",
    ".pgm":       "image/x-portable-graymap",
    ".pic":       "image/pict",
    ".pict":      "image/pict",
    ".pkg":       "application/x-newton-compatible-pkg",
    ".pko":       "application/vndms-pkipko",
    ".pl":        "text/x-scriptperl",
    ".plx":       "application/x-pixclscript",
    ".pm4":       "application/x-pagemaker",
    ".pm5":       "application/x-pagemaker",
    ".pm":        "text/x-scriptperl-module",
    ".png":       "image/png",
    ".pnm":       "application/x-portable-anymap",
    ".pot":       "application/mspowerpoint",
    ".pov":       "model/x-pov",
    ".ppa":       "application/vndms-powerpoint",
    ".ppm":       "image/x-portable-pixmap",
    ".pps":       "application/mspowerpoint",
    ".ppt":       "application/mspowerpoint",
    ".ppz":       "application/mspowerpoint",
    ".pre":       "application/x-freelance",
    ".prt":       "application/pro_eng",
    ".ps":        "application/postscript",
    ".psd":       "application/octet-stream",
    ".pvu":       "paleovu/x-pv",
    ".pwz":       "application/vndms-powerpoint",
    ".py":        "text/x-scriptphyton",
    ".pyc":       "application/x-bytecodepython",
    ".qcp":       "audio/vndqcelp",
    ".qd3":       "x-world/x-3dmf",
    ".qd3d":      "x-world/x-3dmf",
    ".qif":       "image/x-quicktime",
    ".qt":        "video/quicktime",
    ".qtc":       "video/x-qtc",
    ".qti":       "image/x-quicktime",
    ".qtif":      "image/x-quicktime",
    ".ra":        "audio/x-pn-realaudio",
    ".ram":       "audio/x-pn-realaudio",
    ".rar":       "application/x-rar-compressed",
    ".ras":       "application/x-cmu-raster",
    ".rast":      "image/cmu-raster",
    ".rexx":      "text/x-scriptrexx",
    ".rf":        "image/vndrn-realflash",
    ".rgb":       "image/x-rgb",
    ".rm":        "application/vndrn-realmedia",
    ".rmi":       "audio/mid",
    ".rmm":       "audio/x-pn-realaudio",
    ".rmp":       "audio/x-pn-realaudio",
    ".rng":       "application/ringing-tones",
    ".rnx":       "application/vndrn-realplayer",
    ".roff":      "application/x-troff",
    ".rp":        "image/vndrn-realpix",
    ".rpm":       "audio/x-pn-realaudio-plugin",
    ".rt":        "text/vndrn-realtext",
    ".rtf":       "text/richtext",
    ".rtx":       "text/richtext",
    ".rv":        "video/vndrn-realvideo",
    ".s":         "text/x-asm",
    ".s3m":       "audio/s3m",
    ".s7z":       "application/x-7z-compressed",
    ".saveme":    "application/octet-stream",
    ".sbk":       "application/x-tbook",
    ".scm":       "text/x-scriptscheme",
    ".sdml":      "text/plain",
    ".sdp":       "application/sdp",
    ".sdr":       "application/sounder",
    ".sea":       "application/sea",
    ".set":       "application/set",
    ".sgm":       "text/x-sgml",
    ".sgml":      "text/x-sgml",
    ".sh":        "text/x-scriptsh",
    ".shar":      "application/x-bsh",
    ".shtml":     "text/x-server-parsed-html",
    ".sid":       "audio/x-psid",
    ".skd":       "application/x-koan",
    ".skm":       "application/x-koan",
    ".skp":       "application/x-koan",
    ".skt":       "application/x-koan",
    ".sit":       "application/x-stuffit",
    ".sitx":      "application/x-stuffitx",
    ".sl":        "application/x-seelogo",
    ".smi":       "application/smil",
    ".smil":      "application/smil",
    ".snd":       "audio/basic",
    ".sol":       "application/solids",
    ".spc":       "text/x-speech",
    ".spl":       "application/futuresplash",
    ".spr":       "application/x-sprite",
    ".sprite":    "application/x-sprite",
    ".spx":       "audio/ogg",
    ".src":       "application/x-wais-source",
    ".ssi":       "text/x-server-parsed-html",
    ".ssm":       "application/streamingmedia",
    ".sst":       "application/vndms-pkicertstore",
    ".step":      "application/step",
    ".stl":       "application/sla",
    ".stp":       "application/step",
    ".sv4cpio":   "application/x-sv4cpio",
    ".sv4crc":    "application/x-sv4crc",
    ".svf":       "image/vnddwg",
    ".svg":       "image/svg+xml",
    ".svr":       "application/x-world",
    ".swf":       "application/x-shockwave-flash",
    ".t":         "application/x-troff",
    ".talk":      "text/x-speech",
    ".tar":       "application/x-tar",
    ".tbk":       "application/toolbook",
    ".tcl":       "text/x-scripttcl",
    ".tcsh":      "text/x-scripttcsh",
    ".tex":       "application/x-tex",
    ".texi":      "application/x-texinfo",
    ".texinfo":   "application/x-texinfo",
    ".text":      "text/plain",
    ".tgz":       "application/gnutar",
    ".tif":       "image/tiff",
    ".tiff":      "image/tiff",
    ".tr":        "application/x-troff",
    ".tsi":       "audio/tsp-audio",
    ".tsp":       "application/dsptype",
    ".tsv":       "text/tab-separated-values",
    ".turbot":    "image/florian",
    ".txt":       "text/plain",
    ".uil":       "text/x-uil",
    ".uni":       "text/uri-list",
    ".unis":      "text/uri-list",
    ".unv":       "application/i-deas",
    ".uri":       "text/uri-list",
    ".uris":      "text/uri-list",
    ".ustar":     "application/x-ustar",
    ".uu":        "text/x-uuencode",
    ".uue":       "text/x-uuencode",
    ".vcd":       "application/x-cdlink",
    ".vcf":       "text/x-vcard",
    ".vcard":     "text/x-vcard",
    ".vcs":       "text/x-vcalendar",
    ".vda":       "application/vda",
    ".vdo":       "video/vdo",
    ".vew":       "application/groupwise",
    ".viv":       "video/vivo",
    ".vivo":      "video/vivo",
    ".vmd":       "application/vocaltec-media-desc",
    ".vmf":       "application/vocaltec-media-file",
    ".voc":       "audio/voc",
    ".vos":       "video/vosaic",
    ".vox":       "audio/voxware",
    ".vqe":       "audio/x-twinvq-plugin",
    ".vqf":       "audio/x-twinvq",
    ".vql":       "audio/x-twinvq-plugin",
    ".vrml":      "application/x-vrml",
    ".vrt":       "x-world/x-vrt",
    ".vsd":       "application/x-visio",
    ".vst":       "application/x-visio",
    ".vsw":       "application/x-visio",
    ".w60":       "application/wordperfect60",
    ".w61":       "application/wordperfect61",
    ".w6w":       "application/msword",
    ".wav":       "audio/wav",
    ".wb1":       "application/x-qpro",
    ".wbmp":      "image/vnd.wap.wbmp",
    ".web":       "application/vndxara",
    ".wiz":       "application/msword",
    ".wk1":       "application/x-123",
    ".wmf":       "windows/metafile",
    ".wml":       "text/vnd.wap.wml",
    ".wmlc":      "application/vnd.wap.wmlc",
    ".wmls":      "text/vnd.wap.wmlscript",
    ".wmlsc":     "application/vnd.wap.wmlscriptc",
    ".word":      "application/msword",
    ".wp5":       "application/wordperfect",
    ".wp6":       "application/wordperfect",
    ".wp":        "application/wordperfect",
    ".wpd":       "application/wordperfect",
    ".wq1":       "application/x-lotus",
    ".wri":       "application/mswrite",
    ".wrl":       "application/x-world",
    ".wrz":       "model/vrml",
    ".wsc":       "text/scriplet",
    ".wsrc":      "application/x-wais-source",
    ".wtk":       "application/x-wintalk",
    ".x-png":     "image/png",
    ".xbm":       "image/x-xbitmap",
    ".xdr":       "video/x-amt-demorun",
    ".xgz":       "xgl/drawing",
    ".xif":       "image/vndxiff",
    ".xl":        "application/excel",
    ".xla":       "application/excel",
    ".xlb":       "application/excel",
    ".xlc":       "application/excel",
    ".xld":       "application/excel",
    ".xlk":       "application/excel",
    ".xll":       "application/excel",
    ".xlm":       "application/excel",
    ".xls":       "application/excel",
    ".xlt":       "application/excel",
    ".xlv":       "application/excel",
    ".xlw":       "application/excel",
    ".xm":        "audio/xm",
    ".xml":       "text/xml",
    ".xmz":       "xgl/movie",
    ".xpix":      "application/x-vndls-xpix",
    ".xpm":       "image/x-xpixmap",
    ".xsr":       "video/x-amt-showrun",
    ".xwd":       "image/x-xwd",
    ".xyz":       "chemical/x-pdb",
    ".z":         "application/x-compress",
    ".zip":       "application/zip",
    ".zoo":       "application/octet-stream",
    ".zsh":       "text/x-scriptzsh",
    ".docx":      "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    ".docm":      "application/vnd.ms-word.document.macroEnabled.12",
    ".dotx":      "application/vnd.openxmlformats-officedocument.wordprocessingml.template",
    ".dotm":      "application/vnd.ms-word.template.macroEnabled.12",
    ".xlsx":      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    ".xlsm":      "application/vnd.ms-excel.sheet.macroEnabled.12",
    ".xltx":      "application/vnd.openxmlformats-officedocument.spreadsheetml.template",
    ".xltm":      "application/vnd.ms-excel.template.macroEnabled.12",
    ".xlsb":      "application/vnd.ms-excel.sheet.binary.macroEnabled.12",
    ".xlam":      "application/vnd.ms-excel.addin.macroEnabled.12",
    ".pptx":      "application/vnd.openxmlformats-officedocument.presentationml.presentation",
    ".pptm":      "application/vnd.ms-powerpoint.presentation.macroEnabled.12",
    ".ppsx":      "application/vnd.openxmlformats-officedocument.presentationml.slideshow",
    ".ppsm":      "application/vnd.ms-powerpoint.slideshow.macroEnabled.12",
    ".potx":      "application/vnd.openxmlformats-officedocument.presentationml.template",
    ".potm":      "application/vnd.ms-powerpoint.template.macroEnabled.12",
    ".ppam":      "application/vnd.ms-powerpoint.addin.macroEnabled.12",
    ".sldx":      "application/vnd.openxmlformats-officedocument.presentationml.slide",
    ".sldm":      "application/vnd.ms-powerpoint.slide.macroEnabled.12",
    ".thmx":      "application/vnd.ms-officetheme",
    ".onetoc":    "application/onenote",
    ".onetoc2":   "application/onenote",
    ".onetmp":    "application/onenote",
    ".onepkg":    "application/onenote",
    ".xpi":       "application/x-xpinstall",
}

func init() {
    for ext, typ := range types {
        // skip errors
        mime.AddExtensionType(ext, typ)
    }
}

// typeByExtension returns the MIME type associated with the file extension ext.
// The extension ext should begin with a leading dot, as in ".html".
// When ext has no associated type, typeByExtension returns "".
//
// Extensions are looked up first case-sensitively, then case-insensitively.
//
// The built-in table is small but on unix it is augmented by the local
// system's mime.types file(s) if available under one or more of these
// names:
//
//   /etc/mime.types
//   /etc/apache2/mime.types
//   /etc/apache/mime.types
//
// On Windows, MIME types are extracted from the registry.
//
// Text types have the charset parameter set to "utf-8" by default.
func TypeByExtension(fullfilename string) string {
    ext := filepath.Ext(fullfilename)
    typ := mime.TypeByExtension(ext)

    // mime.TypeByExtension returns as text/plain; | charset=utf-8 the static .js (not always)
    if ext == ".js" && (typ == "text/plain" || typ == "text/plain; charset=utf-8") {

        if ext == ".js" {
            typ = "application/javascript"
        }
    }
    return typ
}

Hope that helped you and other users, don't hesitate to post again if you have more questions!

How to error handle 1004 Error with WorksheetFunction.VLookup?

Instead of WorksheetFunction.Vlookup, you can use Application.Vlookup. If you set a Variant equal to this it returns Error 2042 if no match is found. You can then test the variant - cellNum in this case - with IsError:

Sub test()
Dim ws As Worksheet: Set ws = Sheets("2012")
Dim rngLook As Range: Set rngLook = ws.Range("A:M")
Dim currName As String
Dim cellNum As Variant

'within a loop
currName = "Example"
cellNum = Application.VLookup(currName, rngLook, 13, False)
If IsError(cellNum) Then
    MsgBox "no match"
Else
    MsgBox cellNum
End If
End Sub

The Application versions of the VLOOKUP and MATCH functions allow you to test for errors without raising the error. If you use the WorksheetFunction version, you need convoluted error handling that re-routes your code to an error handler, returns to the next statement to evaluate, etc. With the Application functions, you can avoid that mess.

The above could be further simplified using the IIF function. This method is not always appropriate (e.g., if you have to do more/different procedure based on the If/Then) but in the case of this where you are simply trying to determinie what prompt to display in the MsgBox, it should work:

cellNum = Application.VLookup(currName, rngLook, 13, False)
MsgBox IIF(IsError(cellNum),"no match", cellNum)

Consider those methods instead of On Error ... statements. They are both easier to read and maintain -- few things are more confusing than trying to follow a bunch of GoTo and Resume statements.

How to scale images to screen size in Pygame

If you scale 1600x900 to 1280x720 you have

scale_x = 1280.0/1600
scale_y = 720.0/900

Then you can use it to find button size, and button position

button_width  = 300 * scale_x
button_height = 300 * scale_y

button_x = 1440 * scale_x
button_y = 860  * scale_y

If you scale 1280x720 to 1600x900 you have

scale_x = 1600.0/1280
scale_y = 900.0/720

and rest is the same.


I add .0 to value to make float - otherwise scale_x, scale_y will be rounded to integer - in this example to 0 (zero) (Python 2.x)

Remove git mapping in Visual Studio 2015

It just looks for the presence of the .git directory in the solution folder. Delete that folder, possibly hidden, and Visual Studio will no longer consider it a git project.

How to remove spaces from a string using JavaScript?

_x000D_
_x000D_
var a = b = " /var/www/site/Brand new   document.docx ";_x000D_
_x000D_
console.log( a.split(' ').join('') );_x000D_
console.log( b.replace( /\s/g, '') ); 
_x000D_
_x000D_
_x000D_

Two ways of doing this!

CSS Select box arrow style

Try to replace the

padding: 2px 30px 2px 2px;

with

padding: 2px 2px 2px 2px;

It should work.

pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available

In my case I was running into issues with my $PATH on Linux. This can also happen on MacOS.

Check to see if /usr/bin/pip3 install package_name_goes_here works for you. If so then run which pip3 this will tell you which is the first directory that pip3 is installed in.

If it is something like /usr/local/bin/pip3 which is different from /usr/bin/pip3 then you may need to adjust your $PATH.

Run echo $PATH and copy the result.

The PATH is simply a colon separated list of directories that contain directories. Bash will always return the first instance of the program that you are attempting to execute. Move all the system directories upfront. Here is a list of some of the system directories:

/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin

If that fails then verify you have openssl installed by running openssl version -a if not then install openssl.

node.js Error: connect ECONNREFUSED; response from server

just run the following command in the node project

npm install

its worked for me

What is the "continue" keyword and how does it work in Java?

Generally, I see continue (and break) as a warning that the code might use some refactoring, especially if the while or for loop declaration isn't immediately in sight. The same is true for return in the middle of a method, but for a slightly different reason.

As others have already said, continue moves along to the next iteration of the loop, while break moves out of the enclosing loop.

These can be maintenance timebombs because there is no immediate link between the continue/break and the loop it is continuing/breaking other than context; add an inner loop or move the "guts" of the loop into a separate method and you have a hidden effect of the continue/break failing.

IMHO, it's best to use them as a measure of last resort, and then to make sure their use is grouped together tightly at the start or end of the loop so that the next developer can see the "bounds" of the loop in one screen.

continue, break, and return (other than the One True Return at the end of your method) all fall into the general category of "hidden GOTOs". They place loop and function control in unexpected places, which then eventually causes bugs.

Passing Javascript variable to <a href >

Alternatively you could just use a document.write:

<script type="text\javascript">
var loc = "http://";
document.write('<a href="' + loc + '">Link text</a>');
</script>

how to generate public key from windows command prompt

Humm, what? ssh is not something built in to Windows like in most *nix cases.

You'd probably want to use Putty to begin with. And: http://kb.siteground.com/how_to_generate_an_ssh_key_on_windows_using_putty/

Download the Android SDK components for offline install

This has changed for android 4.4.2. .. you should look in the repository file and download https://dl-ssl.google.com/android/repository/repository-10.xml

  1. android-sdk_r20.0.1-windows.zip ( I think that is actually windows specific tools)
  2. android-19_r03.zip for all platform ( actual api) and store under platforms in #1

In manual install dir structure should look like

Now you have to..

  1. download win SDK helper ( avd/SDK magr): https://dl.google.com/android/android-sdk_r20.0.1-windows.zip
  2. actual sdk api https://dl-ssl.google.com/android/repository/android-20_r01.zip
  3. samples https://dl-ssl.google.com/android/repository/samples-19_r05.zip
  4. images : https://dl-ssl.google.com/android/repository/sys-img/x86/sys-img.xml e.g. https://dl-ssl.google.com/android/repository/sysimg_armv7a-18_r02.zip extract in : “Platforms > Android-4.4.2>"
  5. platform-tools: https://dl-ssl.google.com/android/repository/platform-tools_r19.0.1-windows.zip
  6. build-tools: create folder (build-tools at main sdk level) https://dl-ssl.google.com/android/repository/build-tools_r17-windows.zip
  7. copy aapt.exe, aidl.exe and dr.bat to platform-tools folder.
  8. you may download tools as well same way
  9. source: https://dl-ssl.google.com/android/repository/sources-19_r02.zip

At this point you should have a working android installation.

How to drop all stored procedures at once in SQL Server database?

I would prefer to do it this way:

  • first generate the list of stored procedures to drop by inspecting the system catalog view:

    SELECT 'DROP PROCEDURE [' + SCHEMA_NAME(p.schema_id) + '].[' + p.NAME + '];'
    FROM sys.procedures p 
    

    This generates a list of DROP PROCEDURE statements in your SSMS output window.

  • copy that list into a new query window, and possibly adapt it / change it and then execute it

No messy and slow cursors, gives you the ability to check and double-check your list of procedure to be dropped before you actually drop it

FailedPreconditionError: Attempting to use uninitialized in Tensorflow

Tensorflow 2.0 Compatible Answer: In Tensorflow Version >= 2.0, the command for Initializing all the Variables if we use Graph Mode, to fix the FailedPreconditionError is shown below:

tf.compat.v1.global_variables_initializer

This is just a shortcut for variables_initializer(global_variables())

It returns an Op that initializes global variables in the graph.

Difference between Iterator and Listiterator?

the following is that the difference between iterator and listIterator

iterator :

boolean hasNext();
E next();
void remove();

listIterator:

boolean hasNext();
E next();
boolean hasPrevious();
E previous();
int nextIndex();
int previousIndex();
void remove();
void set(E e);
void add(E e);

Clear Cache in Android Application programmatically

Kotlin has an one-liner

context.cacheDir.deleteRecursively()

Why should a Java class implement comparable?

OK, but why not just define a compareTo() method without implementing comparable interface. For example a class City defined by its name and temperature and

public int compareTo(City theOther)
{
    if (this.temperature < theOther.temperature)
        return -1;
    else if (this.temperature > theOther.temperature)
        return 1;
    else
        return 0;
}

Swift 3 - Comparing Date objects

I have tried this snippet (in Xcode 8 Beta 6), and it is working fine.

let date1 = Date()
let date2 = Date().addingTimeInterval(100)

if date1 == date2 { ... }
else if date1 > date2 { ... }
else if date1 < date2 { ... }

One command to create a directory and file inside it linux command

mkdir -p Python/Beginner/CH01 && touch $_/hello_world.py

Explanation: -p -> use -p if you wanna create parent and child directories $_ -> use it for current directory we work with it inline

How to decrypt a password from SQL server?

The SQL Server password hashing algorithm:

hashBytes = 0x0100 | fourByteSalt | SHA1(utf16EncodedPassword+fourByteSalt)

For example, to hash the password "correct horse battery staple". First we generate some random salt:

fourByteSalt = 0x9A664D79;

And then hash the password (encoded in UTF-16) along with the salt:

 SHA1("correct horse battery staple" + 0x9A66D79);
=SHA1(0x63006F007200720065006300740020006200610074007400650072007900200068006F00720073006500200073007400610070006C006500 0x9A66D79)
=0x6EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3

The value stored in the syslogins table is the concatenation of:

[header] + [salt] + [hash]
0x0100 9A664D79 6EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3

Which you can see in SQL Server:

SELECT 
   name, CAST(password AS varbinary(max)) AS PasswordHash
FROM sys.syslogins
WHERE name = 'sa'

name  PasswordHash
====  ======================================================
sa    0x01009A664D796EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3
  • Version header: 0100
  • Salt (four bytes): 9A664D79
  • Hash: 6EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3 (SHA-1 is 20 bytes; 160 bits)

Validation

You validate a password by performing the same hash:

  • grab the salt from the saved PasswordHash: 0x9A664D79

and perform the hash again:

SHA1("correct horse battery staple" + 0x9A66D79);

which will come out to the same hash, and you know the password is correct.

What once was good, but now is weak

The hashing algorithm introduced with SQL Server 7, in 1999, was good for 1999.

  • It is good that the password hash salted.
  • It is good to append the salt to the password, rather than prepend it.

But today it is out-dated. It only runs the hash once, where it should run it a few thousand times, in order to thwart brute-force attacks.

In fact, Microsoft's Baseline Security Analyzer will, as part of it's checks, attempt to bruteforce passwords. If it guesses any, it reports the passwords as weak. And it does get some.

Brute Forcing

To help you test some passwords:

DECLARE @hash varbinary(max)
SET @hash = 0x01009A664D796EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3
--Header: 0x0100
--Salt:   0x9A664D79
--Hash:   0x6EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3

DECLARE @password nvarchar(max)
SET @password = 'password'

SELECT
    @password AS CandidatePassword,
    @hash AS PasswordHash,

    --Header
    0x0100
    +
    --Salt
    CONVERT(VARBINARY(4), SUBSTRING(CONVERT(NVARCHAR(MAX), @hash), 2, 2))
    +
    --SHA1 of Password + Salt
    HASHBYTES('SHA1', @password + SUBSTRING(CONVERT(NVARCHAR(MAX), @hash), 2, 2))

SQL Server 2012 and SHA-512

Starting with SQL Server 2012, Microsoft switched to using SHA-2 512-bit:

hashBytes = 0x0200 | fourByteSalt | SHA512(utf16EncodedPassword+fourByteSalt)

Changing the version prefix to 0x0200:

SELECT 
   name, CAST(password AS varbinary(max)) AS PasswordHash
FROM sys.syslogins

name  PasswordHash
----  --------------------------------
xkcd  0x02006A80BA229556EB280AA7818FAF63A0DA8D6B7B120C6760F0EB0CB5BB320A961B04BD0836 0C0E8CC4C326220501147D6A9ABD2A006B33DEC99FCF1A822393FC66226B7D38
  • Version: 0200 (SHA-2 256-bit)
  • Salt: 6A80BA22
  • Hash (64 bytes): 9556EB280AA7818FAF63A0DA8D6B7B120C6760F0EB0CB5BB320A961B04BD0836 0C0E8CC4C326220501147D6A9ABD2A006B33DEC99FCF1A822393FC66226B7D38

This means we hash the UTF-16 encoded password, with the salt suffix:

  • SHA512("correct horse battery staple"+6A80BA22)
  • SHA512(63006f0072007200650063007400200068006f0072007300650020006200610074007400650072007900200073007400610070006c006500 + 6A80BA22)
  • 9556EB280AA7818FAF63A0DA8D6B7B120C6760F0EB0CB5BB320A961B04BD0836 0C0E8CC4C326220501147D6A9ABD2A006B33DEC99FCF1A822393FC66226B7D38

Top 1 with a left join

The key to debugging situations like these is to run the subquery/inline view on its' own to see what the output is:

  SELECT TOP 1 
         dm.marker_value, 
         dum.profile_id
    FROM DPS_USR_MARKERS dum (NOLOCK)
    JOIN DPS_MARKERS dm (NOLOCK) ON dm.marker_id= dum.marker_id 
                                AND dm.marker_key = 'moneyBackGuaranteeLength'
ORDER BY dm.creation_date

Running that, you would see that the profile_id value didn't match the u.id value of u162231993, which would explain why any mbg references would return null (thanks to the left join; you wouldn't get anything if it were an inner join).

You've coded yourself into a corner using TOP, because now you have to tweak the query if you want to run it for other users. A better approach would be:

   SELECT u.id, 
          x.marker_value 
     FROM DPS_USER u
LEFT JOIN (SELECT dum.profile_id,
                  dm.marker_value,
                  dm.creation_date
             FROM DPS_USR_MARKERS dum (NOLOCK)
             JOIN DPS_MARKERS dm (NOLOCK) ON dm.marker_id= dum.marker_id 
                                         AND dm.marker_key = 'moneyBackGuaranteeLength'
           ) x ON x.profile_id = u.id
     JOIN (SELECT dum.profile_id,
                  MAX(dm.creation_date) 'max_create_date'
             FROM DPS_USR_MARKERS dum (NOLOCK)
             JOIN DPS_MARKERS dm (NOLOCK) ON dm.marker_id= dum.marker_id 
                                         AND dm.marker_key = 'moneyBackGuaranteeLength'
         GROUP BY dum.profile_id) y ON y.profile_id = x.profile_id
                                   AND y.max_create_date = x.creation_date
    WHERE u.id = 'u162231993'

With that, you can change the id value in the where clause to check records for any user in the system.

Emulator: ERROR: x86 emulation currently requires hardware acceleration

Enable virtualization Technology

This is worked in my case

Restart Computer Continuously press Esc and then F10 to enter BIOS setup configuration Check Virtualization technology

My PC is HP Zbook 1. Boot the unit to BIOS (Reboot the unit and keep tapping on F10).

  1. Navigate to Advanced>Device or System Configuration> Click on the check box Virtualization Technology (VTx) and Virtualization Technology for Directed I/O (VTd)

  2. Save changes and Exit.

Why does DEBUG=False setting make my django Static Files Access fail?

If you still need to server static locally (e.g. for testing without debug) you can run devserver in insecure mode:

manage.py runserver --insecure

Efficiently replace all accented characters in a string?

Simply should be normalized chain and run a replacement codes:

var str = "Letras Á É Í Ó Ú Ñ - á é í ó ú ñ...";
console.log (str.normalize ("NFKD").replace (/[\u0300-\u036F]/g, ""));
// Letras A E I O U N - a e i o u n...

See normalize

Then you can use this function:

function noTilde (s) {
    if (s.normalize != undefined) {
        s = s.normalize ("NFKD");
    }
    return s.replace (/[\u0300-\u036F]/g, "");
}

angularjs to output plain text instead of html

You want to use the built-in browser HTML strip for that instead of applying yourself a regexp. It is more secure since the ever green browser does the work for you.

angular.module('myApp.filters', []).
  filter('htmlToPlaintext', function() {
    return function(text) {
      return stripHtml(text);
    };
  }
);

var stripHtml = (function () {
  var tmpEl = $document[0].createElement("DIV");
  function strip(html) {
    if (!html) {
      return "";
    }
    tmpEl.innerHTML = html;
    return tmpEl.textContent || tmpEl.innerText || "";
  }
  return strip;
}());

The reason for wrapping it in an self-executing function is for reusing the element creation.

Detecting Windows or Linux?

apache commons lang has a class SystemUtils.java you can use :

SystemUtils.IS_OS_LINUX
SystemUtils.IS_OS_WINDOWS

Batch file to copy directories recursively

Look into xcopy, which will recursively copy files and subdirectories.

There are examples, 2/3 down the page. Of particular use is:

To copy all the files and subdirectories (including any empty subdirectories) from drive A to drive B, type:

xcopy a: b: /s /e

Converting a list to a set changes element order

As denoted in other answers, sets are data structures (and mathematical concepts) that do not preserve the element order -

However, by using a combination of sets and dictionaries, it is possible that you can achieve wathever you want - try using these snippets:

# save the element order in a dict:
x_dict = dict(x,y for y, x in enumerate(my_list) )
x_set = set(my_list)
#perform desired set operations
...
#retrieve ordered list from the set:
new_list = [None] * len(new_set)
for element in new_set:
   new_list[x_dict[element]] = element

What is the convention for word separator in Java package names?

The official naming conventions aren't that strict, they don't even 'forbid' camel case notation except for prefix (com in your example).

But I personally would avoid upper case letters and hyphenations, even numbers. I'd choose com.stackoverflow.mypackage like Bragboy suggested too.

(hyphenations '-' are not legal in package names)

EDIT

Interesting - the language specification has something to say about naming conventions too.

In Chapter 7.7 Unique Package Names we see examples with package names that consist of upper case letters (so CamelCase notation would be OK) and they suggest to replace hyphonation by an underscore ("mary-lou" -> "mary_lou") and prefix java keywords with an underscore ("com.example.enum" -> "com.example._enum")

Some more examples for upper case letters in package names can be found in chapter 6.8.1 Package Names.

Unclosed Character Literal error

'' encloses single char, while "" encloses a String.

Change

y = 'hello';

-->

y = "hello";

Table and Index size in SQL Server

Here is more compact version of the most successful answer:

create table #tbl(
  name nvarchar(128),
  rows varchar(50),
  reserved varchar(50),
  data varchar(50),
  index_size varchar(50),
  unused varchar(50)
)

exec sp_msforeachtable 'insert into #tbl exec sp_spaceused [?]'

select * from #tbl
    order by convert(int, substring(data, 1, len(data)-3)) desc

drop table #tbl

Change the Blank Cells to "NA"

My function takes into account factor, character vector and potential attributes, if you use haven or foreign package to read external files. Also it allows matching different self-defined na.strings. To transform all columns, simply use lappy: df[] = lapply(df, blank2na, na.strings=c('','NA','na','N/A','n/a','NaN','nan'))

See more the comments:

#' Replaces blank-ish elements of a factor or character vector to NA
#' @description Replaces blank-ish elements of a factor or character vector to NA
#' @param x a vector of factor or character or any type
#' @param na.strings case sensitive strings that will be coverted to NA. The function will do a trimws(x,'both') before conversion. If NULL, do only trimws, no conversion to NA.
#' @return Returns a vector trimws (always for factor, character) and NA converted (if matching na.strings). Attributes will also be kept ('label','labels', 'value.labels').
#' @seealso \code{\link{ez.nan2na}}
#' @export
blank2na = function(x,na.strings=c('','.','NA','na','N/A','n/a','NaN','nan')) {
    if (is.factor(x)) {
        lab = attr(x, 'label', exact = T)
        labs1 <- attr(x, 'labels', exact = T)
        labs2 <- attr(x, 'value.labels', exact = T)

        # trimws will convert factor to character
        x = trimws(x,'both')
        if (! is.null(lab)) lab = trimws(lab,'both')
        if (! is.null(labs1)) labs1 = trimws(labs1,'both')
        if (! is.null(labs2)) labs2 = trimws(labs2,'both')

        if (!is.null(na.strings)) {
            # convert to NA
            x[x %in% na.strings] = NA
            # also remember to remove na.strings from value labels 
            labs1 = labs1[! labs1 %in% na.strings]
            labs2 = labs2[! labs2 %in% na.strings]
        }

        # the levels will be reset here
        x = factor(x)

        if (! is.null(lab)) attr(x, 'label') <- lab
        if (! is.null(labs1)) attr(x, 'labels') <- labs1
        if (! is.null(labs2)) attr(x, 'value.labels') <- labs2
    } else if (is.character(x)) {
        lab = attr(x, 'label', exact = T)
        labs1 <- attr(x, 'labels', exact = T)
        labs2 <- attr(x, 'value.labels', exact = T)

        # trimws will convert factor to character
        x = trimws(x,'both')
        if (! is.null(lab)) lab = trimws(lab,'both')
        if (! is.null(labs1)) labs1 = trimws(labs1,'both')
        if (! is.null(labs2)) labs2 = trimws(labs2,'both')

        if (!is.null(na.strings)) {
            # convert to NA
            x[x %in% na.strings] = NA
            # also remember to remove na.strings from value labels 
            labs1 = labs1[! labs1 %in% na.strings]
            labs2 = labs2[! labs2 %in% na.strings]
        }

        if (! is.null(lab)) attr(x, 'label') <- lab
        if (! is.null(labs1)) attr(x, 'labels') <- labs1
        if (! is.null(labs2)) attr(x, 'value.labels') <- labs2
    } else {
        x = x
    }
    return(x)
}

Insert into a MySQL table or update if exists

Any of these solution will work regarding your question:

INSERT IGNORE INTO table (id, name, age) VALUES (1, "A", 19);

or

INSERT INTO TABLE (id, name, age) VALUES(1, "A", 19) 
    ON DUPLICATE KEY UPDATE NAME = "A", AGE = 19;  

or

REPLACE INTO table (id, name, age) VALUES(1, "A", 19);

If you want to know in details regarding these statement visit this link

Getting absolute URLs using ASP.NET Core

After RC2 and 1.0 you no longer need to inject an IHttpContextAccessor to you extension class. It is immediately available in the IUrlHelper through the urlhelper.ActionContext.HttpContext.Request. You would then create an extension class following the same idea, but simpler since there will be no injection involved.

public static string AbsoluteAction(
    this IUrlHelper url,
    string actionName, 
    string controllerName, 
    object routeValues = null)
{
    string scheme = url.ActionContext.HttpContext.Request.Scheme;
    return url.Action(actionName, controllerName, routeValues, scheme);
}

Leaving the details on how to build it injecting the accesor in case they are useful to someone. You might also just be interested in the absolute url of the current request, in which case take a look at the end of the answer.


You could modify your extension class to use the IHttpContextAccessor interface to get the HttpContext. Once you have the context, then you can get the HttpRequest instance from HttpContext.Request and use its properties Scheme, Host, Protocol etc as in:

string scheme = HttpContextAccessor.HttpContext.Request.Scheme;

For example, you could require your class to be configured with an HttpContextAccessor:

public static class UrlHelperExtensions
{        
    private static IHttpContextAccessor HttpContextAccessor;
    public static void Configure(IHttpContextAccessor httpContextAccessor)
    {           
        HttpContextAccessor = httpContextAccessor;  
    }

    public static string AbsoluteAction(
        this IUrlHelper url,
        string actionName, 
        string controllerName, 
        object routeValues = null)
    {
        string scheme = HttpContextAccessor.HttpContext.Request.Scheme;
        return url.Action(actionName, controllerName, routeValues, scheme);
    }

    ....
}

Which is something you can do on your Startup class (Startup.cs file):

public void Configure(IApplicationBuilder app)
{
    ...

    var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
    UrlHelperExtensions.Configure(httpContextAccessor);

    ...
}

You could probably come up with different ways of getting the IHttpContextAccessor in your extension class, but if you want to keep your methods as extension methods in the end you will need to inject the IHttpContextAccessor into your static class. (Otherwise you will need the IHttpContext as an argument on each call)


Just getting the absoluteUri of the current request

If you just want to get the absolute uri of the current request, you can use the extension methods GetDisplayUrl or GetEncodedUrl from the UriHelper class. (Which is different from the UrLHelper)

GetDisplayUrl. Returns the combined components of the request URL in a fully un-escaped form (except for the QueryString) suitable only for display. This format should not be used in HTTP headers or other HTTP operations.

GetEncodedUrl. Returns the combined components of the request URL in a fully escaped form suitable for use in HTTP headers and other HTTP operations.

In order to use them:

  • Include the namespace Microsoft.AspNet.Http.Extensions.
  • Get the HttpContext instance. It is already available in some classes (like razor views), but in others you might need to inject an IHttpContextAccessor as explained above.
  • Then just use them as in this.Context.Request.GetDisplayUrl()

An alternative to those methods would be manually crafting yourself the absolute uri using the values in the HttpContext.Request object (Similar to what the RequireHttpsAttribute does):

var absoluteUri = string.Concat(
                        request.Scheme,
                        "://",
                        request.Host.ToUriComponent(),
                        request.PathBase.ToUriComponent(),
                        request.Path.ToUriComponent(),
                        request.QueryString.ToUriComponent());

Parsing date string in Go

For those of you out there that are encountering this, use the time.RFC3339 versus the string constant of "2006-01-02T15:04:05.000Z". And here is the reason why:

regDate := "2007-10-09T22:50:01.23Z"

layout1 := "2006-01-02T15:04:05.000Z"
t1, err := time.Parse(layout1, regDate)

if err != nil {
    fmt.Println("Static format doesn't work")
} else {
    fmt.Println(t1)
}

layout2 := time.RFC3339
t2, err := time.Parse(layout2, regDate)

if err != nil {
    fmt.Println("RFC format doesn't work") // You shouldn't see this at all
} else {
    fmt.Println(t2)
}

This will produce the following result:

Static format doesn't work
2007-10-09 22:50:01.23 +0000 UTC

Here is the Playground Link

What is "X-Content-Type-Options=nosniff"?

The X-Content-Type-Options response HTTP header is a marker used by the server to indicate that the MIME types advertised in the Content-Type headers should not be changed and be followed. This allows to opt-out of MIME type sniffing, or, in other words, it is a way to say that the webmasters knew what they were doing.

Syntax :

X-Content-Type-Options: nosniff

Directives :

nosniff Blocks a request if the requested type is 1. "style" and the MIME type is not "text/css", or 2. "script" and the MIME type is not a JavaScript MIME type.

Note: nosniff only applies to "script" and "style" types. Also applying nosniff to images turned out to be incompatible with existing web sites.

Specification :

https://fetch.spec.whatwg.org/#x-content-type-options-header

The character encoding of the plain text document was not declared - mootool script

In my case in ASP MVC it was a method in controller that was returning null to View because of a wrong if statement.

if (condition)
{
    return null;
}

Condition fixed and I returned View, Problem fixed. There was nothing with encoding but I don't know why that was my error.

return View(result); // result is View's model

Moment Js UTC to Local Time

I've created one function which converts all the timezones into local time.

Requirements:

1. npm i moment-timezone

function utcToLocal(utcdateTime, tz) {
    var zone = moment.tz(tz).format("Z") // Actual zone value e:g +5:30
    var zoneValue = zone.replace(/[^0-9: ]/g, "") // Zone value without + - chars
    var operator = zone && zone.split("") && zone.split("")[0] === "-" ? "-" : "+" // operator for addition subtraction
    var localDateTime
    var hours = zoneValue.split(":")[0]
    var minutes = zoneValue.split(":")[1]
    if (operator === "-") {
        localDateTime = moment(utcdateTime).subtract(hours, "hours").subtract(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
    } else if (operator) {
        localDateTime = moment(utcdateTime).add(hours, "hours").add(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
    } else {
        localDateTime = "Invalid Timezone Operator"
    }
    return localDateTime
}

utcToLocal("2019-11-14 07:15:37", "Asia/Kolkata")

//Returns "2019-11-14 12:45:37"

Twitter Bootstrap modal on mobile devices

Albeit this question is quite old, some people still may stumble upon it when looking for solution to improve UX of modals on mobile phones.

I've made a lib to improve Bootrsrap modals' behavior on phones.

Bootstrap 3: https://github.com/keaukraine/bootstrap-fs-modal

Bootstrap 4: https://github.com/keaukraine/bootstrap4-fs-modal

How to trap the backspace key using jQuery?

Working on the same idea as above , but generalizing a bit . Since the backspace should work fine on the input elements , but should not work if the focus is a paragraph or something , since it is there where the page tends to go back to the previous page in history .

$('html').on('keydown' , function(event) {

        if(! $(event.target).is('input')) {
            console.log(event.which);
           //event.preventDefault();
           if(event.which == 8) {
            //  alert('backspace pressed');
            return false;
         }
        }
});

returning false => both event.preventDefault and event.stopPropagation are in effect .

Authentication issue when debugging in VS2013 - iis express

As I was researching this I found my answer, but can't find the answer on the internet, so I thought I'd share this:

I fixed my issue by modifying my applicationhost.config file. My file was saved in the "\My Documents\IISExpress\config" folder.

It seems that VS2013 was ignoring my web.config file and applying different authentication methods.

I had to modify this portion of the file to look like the below. In truth, I only modified the anonymousAuthentication to be false and the windowsAuthentication mode to true.

<authentication>

  <anonymousAuthentication enabled="false" userName="" />

  <basicAuthentication enabled="false" />

  <clientCertificateMappingAuthentication enabled="false" />

  <digestAuthentication enabled="false" />

  <iisClientCertificateMappingAuthentication enabled="false">
  </iisClientCertificateMappingAuthentication>

  <windowsAuthentication enabled="true">
    <providers>
      <add value="Negotiate" />
      <add value="NTLM" />
    </providers>
  </windowsAuthentication>

</authentication>

Sleep function Visual Basic

Since you are asking about .NET, you should change the parameter from Long to Integer. .NET's Integer is 32-bit. (Classic VB's integer was only 16-bit.)

Declare Sub Sleep Lib "kernel32.dll" (ByVal Milliseconds As Integer)

Really though, the managed method isn't difficult...

System.Threading.Thread.CurrentThread.Sleep(5000)

Be careful when you do this. In a forms application, you block the message pump and what not, making your program to appear to have hanged. Rarely is sleep a good idea.

How do I automatically update a timestamp in PostgreSQL

Using 'now()' as default value automatically generates time-stamp.

Calling the base constructor in C#

If you need to call the base constructor but not right away because your new (derived) class needs to do some data manipulation, the best solution is to resort to factory method. What you need to do is to mark private your derived constructor, then make a static method in your class that will do all the necessary stuff and later call the constructor and return the object.

public class MyClass : BaseClass
{
    private MyClass(string someString) : base(someString)
    {
        //your code goes in here
    }

    public static MyClass FactoryMethod(string someString)
    {
        //whatever you want to do with your string before passing it in
        return new MyClass(someString);
    }
}

Android: How to rotate a bitmap on a center point

Look at the sample from Google called Lunar Lander, the ship image there is rotated dynamically.

Lunar Lander code sample

HTTP error 403 in Python 3 Web Scraping

Definitely it's blocking because of your use of urllib based on the user agent. This same thing is happening to me with OfferUp. You can create a new class called AppURLopener which overrides the user-agent with Mozilla.

import urllib.request

class AppURLopener(urllib.request.FancyURLopener):
    version = "Mozilla/5.0"

opener = AppURLopener()
response = opener.open('http://httpbin.org/user-agent')

Source

where is gacutil.exe?

On Windows 2012 R2, you can't install Visual Studio or SDK. You can use powershell to register assemblies into GAC. It didn't need any special installation for me.

Set-location "C:\Temp"
[System.Reflection.Assembly]::Load("System.EnterpriseServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
$publish = New-Object System.EnterpriseServices.Internal.Publish
$publish.GacInstall("C:\Temp\myGacLibrary.dll")

If you need to get the name and PublicKeyToken see this question.

Get real path from URI, Android KitKat new storage access framework

We need to do the following changes/fixes in our earlier onActivityResult()'s gallery picker code to run seamlessly on Android 4.4 (KitKat) and on all other earlier versions as well.

Uri selectedImgFileUri = data.getData();

if (selectedImgFileUri == null ) {

    // The user has not selected any photo
}

try {

   InputStream input = mActivity.getContentResolver().openInputStream(selectedImgFileUri);
   mSelectedPhotoBmp = BitmapFactory.decodeStream(input);
}
catch (Throwable tr) {

    // Show message to try again
}

DropdownList DataSource

Refer to example at this link. It may be help to you.

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.dropdownlist.aspx

void Page_Load(Object sender, EventArgs e)
  {

     // Load data for the DropDownList control only once, when the 
     // page is first loaded.
     if(!IsPostBack)
     {

        // Specify the data source and field names for the Text 
        // and Value properties of the items (ListItem objects) 
        // in the DropDownList control.
        ColorList.DataSource = CreateDataSource();
        ColorList.DataTextField = "ColorTextField";
        ColorList.DataValueField = "ColorValueField";

        // Bind the data to the control.
        ColorList.DataBind();

        // Set the default selected item, if desired.
        ColorList.SelectedIndex = 0;

     }

  }

void Selection_Change(Object sender, EventArgs e)
  {

     // Set the background color for days in the Calendar control
     // based on the value selected by the user from the 
     // DropDownList control.
     Calendar1.DayStyle.BackColor = 
         System.Drawing.Color.FromName(ColorList.SelectedItem.Value);

  }

How to prevent a double-click using jQuery?

My solution: https://gist.github.com/pangui/86b5e0610b53ddf28f94 It prevents double click but accepts more clicks after 1 second. Hope it helps.

Here is the code:

jQuery.fn.preventDoubleClick = function() {
  $(this).on('click', function(e){
    var $el = $(this);
    if($el.data('clicked')){
      // Previously clicked, stop actions
      e.preventDefault();
      e.stopPropagation();
    }else{
      // Mark to ignore next click
      $el.data('clicked', true);
      // Unmark after 1 second
      window.setTimeout(function(){
        $el.removeData('clicked');
      }, 1000)
    }
  });
  return this;
}; 

How do I get console input in javascript?

In plain JavaScript, simply use response = readline() after printing a prompt.

In Node.js, you'll need to use the readline module: const readline = require('readline')

Debugging with command-line parameters in Visual Studio

Even if you do start the executable outside Visual Studio, you can still use the "Attach" command to connect Visual Studio to your already-running executable. This can be useful e.g. when your application is run as a plug-in within another application.

How to check if an Object is a Collection Type in Java?

Update: there are two possible scenarios here:

  1. You are determining if an object is a collection;

  2. You are determining if a class is a collection.

The solutions are slightly different but the principles are the same. You also need to define what exactly constitutes a "collection". Implementing either Collection or Map will cover the Java Collections.

Solution 1:

public static boolean isCollection(Object ob) {
  return ob instanceof Collection || ob instanceof Map;
}

Solution 2:

public static boolean isClassCollection(Class c) {
  return Collection.class.isAssignableFrom(c) || Map.class.isAssignableFrom(c);
}

(1) can also be implemented in terms of (2):

public static boolean isCollection(Object ob) {
  return ob != null && isClassCollection(ob.getClass());
}

I don't think the efficiency of either method will be greatly different from the other.

How to download all dependencies and packages to directory

The aptitude --download-only ... approach only works if you have a debian distro with internet connection in your hands.

If you don't, I think it is better to run the following script on the disconnected debian machine:

apt-get --print-uris --yes install <my_package_name> | grep ^\' | cut -d\' -f2 >downloads.list

move the downloads.list file into a connected linux (or non linux) machine, and run:

wget --input-file myurilist

this downloads all your files into the current directory.After that you can copy them on an USB key and install in your disconnected debian machine.

credits: http://www.tuxradar.com/answers/517

PS I basically copied the blog post because it was not very readable, and in case the post will disappear.

how to change the default positioning of modal in bootstrap?

To change the Modal position in the viewport you can target the Modal div id, in this example this id is myModal3

    <div id="modal3" class="modal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h4 class="modal-title">Modal title</h4>
      </div>
      <div class="modal-body">
        <p>One fine body…</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>


#myModal3 {
top:5%;
right:50%;
outline: none;
overflow:hidden;
}

Best way to track onchange as-you-type in input type="text"?

To track each try this example and before that completely reduce cursor blink rate to zero.

_x000D_
_x000D_
<body>_x000D_
//try onkeydown,onkeyup,onkeypress_x000D_
<input type="text" onkeypress="myFunction(this.value)">_x000D_
<span> </span>_x000D_
<script>_x000D_
function myFunction(val) {_x000D_
//alert(val);_x000D_
var mySpan = document.getElementsByTagName("span")[0].innerHTML;_x000D_
mySpan += val+"<br>";_x000D_
document.getElementsByTagName("span")[0].innerHTML = mySpan;_x000D_
}_x000D_
</script>_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_

onblur : event generates on exit

onchange : event generates on exit if any changes made in inputtext

onkeydown: event generates on any key press (for key holding long times also)

onkeyup : event generates on any key release

onkeypress: same as onkeydown (or onkeyup) but won't react for ctrl,backsace,alt other

*.h or *.hpp for your class definitions

I prefer .hpp for C++ to make it clear to both editors and to other programmers that it is a C++ header rather than a C header file.

EXEC sp_executesql with multiple parameters

If one need to use the sp_executesql with OUTPUT variables:

EXEC sp_executesql @sql
                  ,N'@p0 INT'
                  ,N'@p1 INT OUTPUT'
                  ,N'@p2 VARCHAR(12) OUTPUT' 
                  ,@p0
                  ,@p1 OUTPUT
                  ,@p2 OUTPUT;

Convert nullable bool? to bool

bool? a = null;
bool b = Convert.toBoolean(a); 

Getting the index of the returned max or min item using max()/min() on a list

I think the answer above solves your problem but I thought I'd share a method that gives you the minimum and all the indices the minimum appears in.

minval = min(mylist)
ind = [i for i, v in enumerate(mylist) if v == minval]

This passes the list twice but is still quite fast. It is however slightly slower than finding the index of the first encounter of the minimum. So if you need just one of the minima, use Matt Anderson's solution, if you need them all, use this.

Expression ___ has changed after it was checked

I fixed this by adding ChangeDetectionStrategy from angular core.

import {  Component, ChangeDetectionStrategy } from '@angular/core';
@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  selector: 'page1',
  templateUrl: 'page1.html',
})

Why is it faster to check if dictionary contains the key, rather than catch the exception in case it doesn't?

On the one hand, throwing exceptions is inherently expensive, because the stack has to be unwound etc.
On the other hand, accessing a value in a dictionary by its key is cheap, because it's a fast, O(1) operation.

BTW: The correct way to do this is to use TryGetValue

obj item;
if(!dict.TryGetValue(name, out item))
    return null;
return item;

This accesses the dictionary only once instead of twice.
If you really want to just return null if the key doesn't exist, the above code can be simplified further:

obj item;
dict.TryGetValue(name, out item);
return item;

This works, because TryGetValue sets item to null if no key with name exists.

Throw HttpResponseException or return Request.CreateErrorResponse?

As far as I can tell, whether you throw an exception, or you return Request.CreateErrorResponse, the result is the same. If you look at the source code for System.Web.Http.dll, you will see as much. Take a look at this general summary, and a very similar solution that I have made: Web Api, HttpError, and the behavior of exceptions

How to decode JWT Token?

I found the solution, I just forgot to Cast the result:

var stream ="[encoded jwt]";  
var handler = new JwtSecurityTokenHandler();
var jsonToken = handler.ReadToken(stream);
var tokenS = handler.ReadToken(stream) as JwtSecurityToken;

I can get Claims using:

var jti = tokenS.Claims.First(claim => claim.Type == "jti").Value;

How to get the current user's Active Directory details in C#

If you're using .NET 3.5 SP1+ the better way to do this is to take a look at the

System.DirectoryServices.AccountManagement namespace.

It has methods to find people and you can pretty much pass in any username format you want and then returns back most of the basic information you would need. If you need help on loading the more complex objects and properties check out the source code for http://umanage.codeplex.com its got it all.

Brent

How to change letter spacing in a Textview?

check out android:textScaleX

Depending on how much spacing you need, this might help. That's the only thing remotely related to letter-spacing in the TextView.

Edit: please see @JerabekJakub's response below for an updated, better method to do this starting with api 21 (Lollipop)

How to handle the click event in Listview in android?

ListView has the Item click listener callback. You should set the onItemClickListener in the ListView. Callback contains AdapterView and position as parameter. Which can give you the ListEntry.

lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
                ListEntry entry= (ListEntry) parent.getAdapter().getItem(position);
                Intent intent = new Intent(MainActivity.this, SendMessage.class);
                String message = entry.getMessage();
                intent.putExtra(EXTRA_MESSAGE, message);
                startActivity(intent);
            }
        });