Programs & Examples On #Couchrest

Excel VBA - How to Redim a 2D array?

here is updated code of the redim preseve method with variabel declaration, hope @Control Freak is fine with it:)

Option explicit
'redim preserve both dimensions for a multidimension array *ONLY
Public Function ReDimPreserve(aArrayToPreserve As Variant, nNewFirstUBound As Variant, nNewLastUBound As Variant) As Variant
    Dim nFirst As Long
    Dim nLast As Long
    Dim nOldFirstUBound As Long
    Dim nOldLastUBound As Long

    ReDimPreserve = False
    'check if its in array first
    If IsArray(aArrayToPreserve) Then
        'create new array
        ReDim aPreservedArray(nNewFirstUBound, nNewLastUBound)
        'get old lBound/uBound
        nOldFirstUBound = UBound(aArrayToPreserve, 1)
        nOldLastUBound = UBound(aArrayToPreserve, 2)
        'loop through first
        For nFirst = LBound(aArrayToPreserve, 1) To nNewFirstUBound
            For nLast = LBound(aArrayToPreserve, 2) To nNewLastUBound
                'if its in range, then append to new array the same way
                If nOldFirstUBound >= nFirst And nOldLastUBound >= nLast Then
                    aPreservedArray(nFirst, nLast) = aArrayToPreserve(nFirst, nLast)
                End If
            Next
        Next
        'return the array redimmed
        If IsArray(aPreservedArray) Then ReDimPreserve = aPreservedArray
    End If
End Function

How to mkdir only if a directory does not already exist?

directory_name = "foo"

if [ -d $directory_name ]
then
    echo "Directory already exists"
else
    mkdir $directory_name
fi

Running Selenium WebDriver python bindings in chrome

There are 2 ways to run Selenium python tests in Google Chrome. I'm considering Windows (Windows 10 in my case):

Prerequisite: Download the latest Chrome Driver from: https://sites.google.com/a/chromium.org/chromedriver/downloads

Way 1:

i) Extract the downloaded zip file in a directory/location of your choice
ii) Set the executable path in your code as below:

self.driver = webdriver.Chrome(executable_path='D:\Selenium_RiponAlWasim\Drivers\chromedriver_win32\chromedriver.exe')

Way 2:

i) Simply paste the chromedriver.exe under /Python/Scripts/ (In my case the folder was: C:\Python36\Scripts)
ii) Now write the simple code as below:

self.driver = webdriver.Chrome()

MySQL Error: : 'Access denied for user 'root'@'localhost'

Although a old one, I was getting the same error while setting up the mysql-8 zip version. Finally, switched to installer version which worked seamlessly. During installation, there is a prompt to setup the root password. Once set, it works for sure.

enter image description here

How to remove first 10 characters from a string?

For:

var str = "hello world!";

To get the resulting string without the first 10 characters and an empty string if the string is less or equal in length to 10 you can use:

var result = str.Length <= 10 ? "" : str.Substring(10);

or

var result = str.Length <= 10 ? "" : str.Remove(0, 10);

First variant being preferred since it needs only one method parameter.

How to change the minSdkVersion of a project?

Set the min SDK version in your project's AndroidManifest.xml file and in the toolbar search for "Sync Projects with Gradle Files" icon. It works for me.

Also look for your project's build.gradle file and update the min sdk version.

How to run a python script from IDLE interactive shell?

On Windows environment, you can execute py file on Python3 shell command line with the following syntax:

exec(open('absolute path to file_name').read())

Below explains how to execute a simple helloworld.py file from python shell command line

File Location: C:/Users/testuser/testfolder/helloworld.py

File Content: print("hello world")

We can execute this file on Python3.7 Shell as below:

>>> import os
>>> abs_path = 'C://Users/testuser/testfolder'
>>> os.chdir(abs_path)
>>> os.getcwd()
'C:\\Users\\testuser\\testfolder'

>>> exec(open("helloworld.py").read())
hello world

>>> exec(open("C:\\Users\\testuser\\testfolder\\helloworld.py").read())
hello world

>>> os.path.abspath("helloworld.py")
'C:\\Users\\testuser\\testfolder\\helloworld.py'
>>> import helloworld
hello world

Where to find htdocs in XAMPP Mac

Make sure no other apache servers are running as it generates an error when you try to access it on the browser even with a different port. Go to Finder and below Device you will usually see the lampp icon. You can also open the htdocs from any of the ide or code editor by opening files or project once you locate the lampp icon. Make sure you mount the stack.

SQL "IF", "BEGIN", "END", "END IF"?

Based on your description of what you want to do, the code seems to be correct as it is. ENDIF isn't a valid SQL loop control keyword. Are you sure that the INSERTS are actually pulling data to put into @Classes? In fact, if it was bad it just wouldn't run.

What you might want to try is to put a few PRINT statements in there. Put a PRINT above each of the INSERTS just outputting some silly text to show that that line is executing. If you get both outputs, then your SELECT...INSERT... is suspect. You could also just do the SELECT in place of the PRINT (that is, without the INSERT) and see exactly what data is being pulled.

Install IPA with iTunes 12

iTunes 12.7 ( Xcode needed )

You cannot install a release ipa directly on your device. Ipa generated withAppStore Distribution Profile requires to be distributed from App Store or TestFlight. However, I found that app panel was removed even for installing ad hoc ipa from iTunes 12.7. I found a workaround to install ad-hoc apps which might help to them who cannot install even ad hoc ipa. Please follow the instructions below,

  1. Connect your device
  2. Open Xcode and go to Window -> Devices
  3. Select the connected device from left panel
  4. Brows the IPA from Installed Apps -> + button
  5. Wait few seconds and its done!

enter image description here

How to round up the result of integer division?

Found an elegant solution:

int pageCount = (records + recordsPerPage - 1) / recordsPerPage;

Source: Number Conversion, Roland Backhouse, 2001

Adding timestamp to a filename with mv in BASH

A single line method within bash works like this.

[some out put] >$(date "+%Y.%m.%d-%H.%M.%S").ver

will create a file with a timestamp name with ver extension. A working file listing snap shot to a date stamp file name as follows can show it working.

find . -type f -exec ls -la {} \; | cut -d ' ' -f 6- >$(date "+%Y.%m.%d-%H.%M.%S").ver

Of course

cat somefile.log > $(date "+%Y.%m.%d-%H.%M.%S").ver

or even simpler

ls > $(date "+%Y.%m.%d-%H.%M.%S").ver

Copy multiple files from one directory to another from Linux shell

Use wildcards:

cp /home/ankur/folder/* /home/ankur/dest

If you don't want to copy all the files, you can use braces to select files:

cp /home/ankur/folder/{file{1,2},xyz,abc} /home/ankur/dest

This will copy file1, file2, xyz, and abc.

You should read the sections of the bash man page on Brace Expansion and Pathname Expansion for all the ways you can simplify this.

Another thing you can do is cd /home/ankur/folder. Then you can type just the filenames rather than the full pathnames, and you can use filename completion by typing Tab.

Test if a string contains a word in PHP?

<?php
//  Use this function and Pass Mixed string and what you want to search in mixed string.
//  For Example :
    $mixedStr = "hello world. This is john duvey";
    $searchStr= "john";

    if(strpos($mixedStr,$searchStr)) {
      echo "Your string here";
    }else {
      echo "String not here";
    }

How to count the number of columns in a table using SQL?

Maybe something like this:

SELECT count(*) FROM user_tab_columns WHERE table_name = 'FOO'

this will count number of columns in a the table FOO

You can also just

select count(*) from all_tab_columns where owner='BAR' and table_name='FOO';

where the owner is schema and note that Table Names are upper case

Where do I find the bashrc file on Mac?

Open Terminal and execute commands given below.

cd /etc
subl bashrc

subl denotes Sublime editor. You can replace subl with vi to open bashrc file in default editor. This will workout only if you have bashrc file, created earlier.

Switch statement for string matching in JavaScript

You can't do it in a switch unless you're doing full string matching; that's doing substring matching. (This isn't quite true, as Sean points out in the comments. See note at the end.)

If you're happy that your regex at the top is stripping away everything that you don't want to compare in your match, you don't need a substring match, and could do:

switch (base_url_string) {
    case "xxx.local":
        // Blah
        break;
    case "xxx.dev.yyy.com":
        // Blah
        break;
}

...but again, that only works if that's the complete string you're matching. It would fail if base_url_string were, say, "yyy.xxx.local" whereas your current code would match that in the "xxx.local" branch.


Update: Okay, so technically you can use a switch for substring matching, but I wouldn't recommend it in most situations. Here's how (live example):

function test(str) {
    switch (true) {
      case /xyz/.test(str):
        display("• Matched 'xyz' test");
        break;
      case /test/.test(str):
        display("• Matched 'test' test");
        break;
      case /ing/.test(str):
        display("• Matched 'ing' test");
        break;
      default:
        display("• Didn't match any test");
        break;
    }
}

That works because of the way JavaScript switch statements work, in particular two key aspects: First, that the cases are considered in source text order, and second that the selector expressions (the bits after the keyword case) are expressions that are evaluated as that case is evaluated (not constants as in some other languages). So since our test expression is true, the first case expression that results in true will be the one that gets used.

How to enable CORS in AngularJs

I encountered a similar problem like this, problem was with the backend . I was using node server(Express). I had a get request from the frontend(angular) as shown below

   onGetUser(){
        return this.http.get("http://localhost:3000/user").pipe(map(
            (response:Response)=>{
                const user =response.json();
                return user;
            }
        )) 
    }

But it gave the following errorThe error

This is the backend code written using express without the headers

app.get('/user',async(req,res)=>{
     const user=await getuser();
     res.send(user);
 })

After adding a header to the method problem was solved

app.get('/user',async(req,res)=>{
    res.header("Access-Control-Allow-Origin", "*");
    const user=await getuser();
    res.send(user);
})

You can get more details about Enabling CORS on Node JS

JavaFX "Location is required." even though it is in the same package

I couldn't use

getClass().getResource("views/view.fxml")

because I put my controller class into "controllers" package, so here is my solution:

getClass().getResource("../views/view.fxml")

twig: IF with multiple conditions

If I recall correctly Twig doesn't support || and && operators, but requires or and and to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.

{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}

Expressions

Expressions can be used in {% blocks %} and ${ expressions }.

Operator    Description
==          Does the left expression equal the right expression?
+           Convert both arguments into a number and add them.
-           Convert both arguments into a number and substract them.
*           Convert both arguments into a number and multiply them.
/           Convert both arguments into a number and divide them.
%           Convert both arguments into a number and calculate the rest of the integer division.
~           Convert both arguments into a string and concatenate them.
or          True if the left or the right expression is true.
and         True if the left and the right expression is true.
not         Negate the expression.

For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %}

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

Vuejs and Vue.set(), update array

VueJS can't pickup your changes to the state if you manipulate arrays like this.

As explained in Common Beginner Gotchas, you should use array methods like push, splice or whatever and never modify the indexes like this a[2] = 2 nor the .length property of an array.

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  data: {_x000D_
    f: 'DD-MM-YYYY',_x000D_
    items: [_x000D_
      "10-03-2017",_x000D_
      "12-03-2017"_x000D_
    ]_x000D_
  },_x000D_
  methods: {_x000D_
_x000D_
    cha: function(index, item, what, count) {_x000D_
      console.log(item + " index > " + index);_x000D_
      val = moment(this.items[index], this.f).add(count, what).format(this.f);_x000D_
_x000D_
      this.items.$set(index, val)_x000D_
      console.log("arr length:  " + this.items.length);_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
ul {_x000D_
  list-style-type: none;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.11/vue.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>_x000D_
<div id="app">_x000D_
  <ul>_x000D_
    <li v-for="(index, item) in items">_x000D_
      <br><br>_x000D_
      <button v-on:click="cha(index, item, 'day', -1)">_x000D_
      - day</button> {{ item }}_x000D_
      <button v-on:click="cha(index, item, 'day', 1)">_x000D_
      + day</button>_x000D_
      <br><br>_x000D_
    </li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Remove Top Line of Text File with PowerShell

For smaller files you could use this:

& C:\windows\system32\more +1 oldfile.csv > newfile.csv | out-null

... but it's not very effective at processing my example file of 16MB. It doesn't seem to terminate and release the lock on newfile.csv.

What is the simplest way to get indented XML with line breaks from XmlDocument?

    public static string FormatXml(string xml)
    {
        try
        {
            var doc = XDocument.Parse(xml);
            return doc.ToString();
        }
        catch (Exception)
        {
            return xml;
        }
    }

Make an Android button change background on click through XML

In the latest version of the SDK, you would use the setBackgroundResource method.

public void onClick(View v) {
   if(v == ButtonName) {
     ButtonName.setBackgroundResource(R.drawable.ImageResource);
   }
}

Return multiple values from a function in swift

Return a tuple:

func getTime() -> (Int, Int, Int) {
    ...
    return ( hour, minute, second)
}

Then it's invoked as:

let (hour, minute, second) = getTime()

or:

let time = getTime()
println("hour: \(time.0)")

Inserting NOW() into Database with CodeIgniter's Active Record

aspirinemaga, just replace:

$this->db->set('time', 'NOW()', FALSE);
$this->db->insert('mytable', $data);

for it:

$this->db->set('time', 'NOW() + INTERVAL 1 DAY', FALSE);
$this->db->insert('mytable', $data);

Checking for directory and file write permissions in .NET

IMO, you need to work with such directories as usual, but instead of checking permissions before use, provide the correct way to handle UnauthorizedAccessException and react accordingly. This method is easier and much less error prone.

How can I ping a server port with PHP?

You don't need any exec or shell_exec hacks to do that, it is possible to do it in PHP. The book 'You want to do WHAT with PHP?' by Kevin Schroeder, show's how.

It uses sockets and the pack() function which lets you read and write binary protocols. What you need to do is to create an ICMP packet, which you can do by using the 'CCnnnA*' format to create your packet.

Android read text raw resource file

1.First create a Directory folder and name it raw inside the res folder 2.create a .txt file inside the raw directory folder you created earlier and give it any name eg.articles.txt.... 3.copy and paste the text you want inside the .txt file you created"articles.txt" 4.dont forget to include a textview in your main.xml MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gettingtoknowthe_os);

    TextView helloTxt = (TextView)findViewById(R.id.gettingtoknowos);
    helloTxt.setText(readTxt());

    ActionBar actionBar = getSupportActionBar();
    actionBar.hide();//to exclude the ActionBar
}

private String readTxt() {

    //getting the .txt file
    InputStream inputStream = getResources().openRawResource(R.raw.articles);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    try {
        int i = inputStream.read();
        while (i != -1) {
            byteArrayOutputStream.write(i);
            i = inputStream.read();
        }
        inputStream.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return byteArrayOutputStream.toString();
}

Hope it worked!

How to generate random number in Bash?

Random number between 0 and 9 inclusive.

echo $((RANDOM%10))

SQL Last 6 Months

In MySQL

where datetime_column > curdate() - interval (dayofmonth(curdate()) - 1) day - interval 6 month

SQLFiddle demo

In SQL Server

where datetime_column > dateadd(m, -6, getdate() - datepart(d, getdate()) + 1)

SQLFiddle demo

How to create a DataFrame from a text file in Spark

A txt File with PIPE (|) delimited file can be read as :


df = spark.read.option("sep", "|").option("header", "true").csv("s3://bucket_name/folder_path/file_name.txt")

Combine two OR-queries with AND in Mongoose

It's probably easiest to create your query object directly as:

  Test.find({
      $and: [
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ]
  }, function (err, results) {
      ...
  }

But you can also use the Query#and helper that's available in recent 3.x Mongoose releases:

  Test.find()
      .and([
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ])
      .exec(function (err, results) {
          ...
      });

How do I compare two string variables in an 'if' statement in Bash?

Bash 4+ examples. Note: not using quotes will cause issues when words contain spaces, etc. Always quote in Bash IMO.

Here are some examples Bash 4+:

Example 1, check for 'yes' in string (case insensitive):

if [[ "${str,,}" == *"yes"* ]] ;then

Example 2, check for 'yes' in string (case insensitive):

if [[ "$(echo "$str" | tr '[:upper:]' '[:lower:]')" == *"yes"* ]] ;then

Example 3, check for 'yes' in string (case sensitive):

 if [[ "${str}" == *"yes"* ]] ;then

Example 4, check for 'yes' in string (case sensitive):

 if [[ "${str}" =~ "yes" ]] ;then

Example 5, exact match (case sensitive):

 if [[ "${str}" == "yes" ]] ;then

Example 6, exact match (case insensitive):

 if [[ "${str,,}" == "yes" ]] ;then

Example 7, exact match:

 if [ "$a" = "$b" ] ;then

Greater than and less than in one statement

This is one ugly way to do this. I would just use a local variable.

EDIT: If size() > 0 as well.

if (orderBean.getFiles().size() + Integer.MIN_VALUE-1 < Integer.MIN_VALUE + 5-1)

How to find length of digits in an integer?

Without conversion to string

import math
digits = int(math.log10(n))+1

To also handle zero and negative numbers

import math
if n > 0:
    digits = int(math.log10(n))+1
elif n == 0:
    digits = 1
else:
    digits = int(math.log10(-n))+2 # +1 if you don't count the '-' 

You'd probably want to put that in a function :)

Here are some benchmarks. The len(str()) is already behind for even quite small numbers

timeit math.log10(2**8)
1000000 loops, best of 3: 746 ns per loop
timeit len(str(2**8))
1000000 loops, best of 3: 1.1 µs per loop

timeit math.log10(2**100)
1000000 loops, best of 3: 775 ns per loop
 timeit len(str(2**100))
100000 loops, best of 3: 3.2 µs per loop

timeit math.log10(2**10000)
1000000 loops, best of 3: 844 ns per loop
timeit len(str(2**10000))
100 loops, best of 3: 10.3 ms per loop

XPath to get all child nodes (elements, comments, and text) without parent

Use this XPath expression:

/*/*/X/node()

This selects any node (element, text node, comment or processing instruction) that is a child of any X element that is a grand-child of the top element of the XML document.

To verify what is selected, here is this XSLT transformation that outputs exactly the selected nodes:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes"/>
 <xsl:template match="/">
  <xsl:copy-of select="/*/*/X/node()"/>
 </xsl:template>
</xsl:stylesheet>

and it produces exactly the wanted, correct result:

   First Text Node #1            
    <y> Y can Have Child Nodes #                
        <child> deep to it </child>
    </y>            Second Text Node #2 
    <z />

Explanation:

  1. As defined in the W3 XPath 1.0 Spec, "child::node() selects all the children of the context node, whatever their node type." This means that any element, text-node, comment-node and processing-instruction node children are selected by this node-test.

  2. node() is an abbreviation of child::node() (because child:: is the primary axis and is used when no axis is explicitly specified).

Correct set of dependencies for using Jackson mapper

The package names in Jackson 2.x got changed to com.fasterxml1 from org.codehaus2. So if you just need ObjectMapper, I think Jackson 1.X can satisfy with your needs.

How can you create multiple cursors in Visual Studio Code

I had problem with ALT key, fix is to change alt+click as a Gnome hotkey which clobbers multi-cursor select in VSCode, to super+click by running:

gsettings set org.gnome.desktop.wm.preferences mouse-button-modifier "<Super>"   

Source: http://2buntu.com/articles/1529/visual-studio-code-comes-to-linux/

ES6 Map in Typescript

How do I declare an ES6 Map type in typescript?

You need to target --module es6. This is misfortunate and you can raise your concern here : https://github.com/Microsoft/TypeScript/issues/2953#issuecomment-98514111

Change image size via parent div

I'm not sure about what you mean by "I have no access to image" But if you have access to parent div you can do the following:

Firs give id or class to your div:

<div class="parent">
   <img src="http://someimage.jpg">
</div>

Than add this to your css:

.parent {
   width: 42px; /* I took the width from your post and placed it in css */
   height: 42px;
}

/* This will style any <img> element in .parent div */
.parent img {
   height: 100%;
   width: 100%;
}

Installing Apple's Network Link Conditioner Tool

It's in an additional download. Use this menu item:

Xcode > Open Developer Tool > More Developer Tools...

and get "Hardware IO Tools for Xcode".

For Xcode 8+, get "Additional Tools for Xcode [version]".

Double-click on a .prefPane file to install. If you already have an older .prefPane installed, you'll need to remove it from /Library/PreferencePanes.

The ResourceConfig instance does not contain any root resource classes

Another possible cause of this error is that you have forgotten to add the libraries that are already in the /WEBINF/lib folder to the build path (e.g. when importing a .war-file and not checking the libraries when asked in the wizard). Just happened to me.

How to save user input into a variable in html and js

First, make your markup more portable/reusable. I also set the button's type to 'button' instead of using the onsubmit attribute. You can toggle the type attribute to submit if the form needs to interact with a server.

<div class='wrapper'>
<form id='nameForm'>
<div class='form-uname'>
    <label id='nameLable' for='nameField'>Create a username:</label>
    <input id='nameField' type='text' maxlength='25'></input>
</div>
<div class='form-sub'>
    <button id='subButton' type='button'>Print your name!</button>
</div>
</form>

<div>
    <p id='result'></p></div>
</div>

Next write a general function for retrieving the username into a variable. It checks to make sure the variable holding the username has it least three characters in it. You can change this to whatever constant you want.

function getUserName() {
var nameField = document.getElementById('nameField').value;
var result = document.getElementById('result');

if (nameField.length < 3) {
    result.textContent = 'Username must contain at least 3 characters';
    //alert('Username must contain at least 3 characters');
} else {
    result.textContent = 'Your username is: ' + nameField;
    //alert(nameField);
}
}

Next, I created an event listener for the button. It's generally considered the bad practice to have inline js calls.

var subButton = document.getElementById('subButton');
subButton.addEventListener('click', getUserName, false); 

Here is a working and lightly styled demo:

CodePen demo of this answer.

Passing an array as parameter in JavaScript

Just remove the .value, like this:

function(arrayP){    
   for(var i = 0; i < arrayP.length; i++){
      alert(arrayP[i]);    //no .value here
   }
}

Sure you can pass an array, but to get the element at that position, use only arrayName[index], the .value would be getting the value property off an object at that position in the array - which for things like strings, numbers, etc doesn't exist. For example, "myString".value would also be undefined.

Paramiko's SSHClient with SFTP

If you have a SSHClient, you can also use open_sftp():

import paramiko


# lets say you have SSH client...
client = paramiko.SSHClient()

sftp = client.open_sftp()

# then you can use upload & download as shown above
...

Datatype for storing ip address in SQL Server

I usually use a plain old VARCHAR filtering for an IPAddress works fine.

If you want to filter on ranges of IP address I'd break it into four integers.

ORA-01652 Unable to extend temp segment by in tablespace

I found the solution to this. There is a temporary tablespace called TEMP which is used internally by database for operations like distinct, joins,etc. Since my query(which has 4 joins) fetches almost 50 million records the TEMP tablespace does not have that much space to occupy all data. Hence the query fails even though my tablespace has free space.So, after increasing the size of TEMP tablespace the issue was resolved. Hope this helps someone with the same issue. Thanks :)

Javascript Debugging line by line using Google Chrome

Assuming you're running on a Windows machine...

  1. Hit the F12 key
  2. Select the Scripts, or Sources, tab in the developer tools
  3. Click the little folder icon in the top level
  4. Select your JavaScript file
  5. Add a breakpoint by clicking on the line number on the left (adds a little blue marker)
  6. Execute your JavaScript

Then during execution debugging you can do a handful of stepping motions...

  • F8 Continue: Will continue until the next breakpoint
  • F10 Step over: Steps over next function call (won't enter the library)
  • F11 Step into: Steps into the next function call (will enter the library)
  • Shift + F11 Step out: Steps out of the current function

Update

After reading your updated post; to debug your code I would recommend temporarily using the jQuery Development Source Code. Although this doesn't directly solve your problem, it will allow you to debug more easily. For what you're trying to achieve I believe you'll need to step-in to the library, so hopefully the production code should help you decipher what's happening.

iOS: Multi-line UILabel in Auto Layout

Source: http://www.objc.io/issue-3/advanced-auto-layout-toolbox.html

Intrinsic Content Size of Multi-Line Text

The intrinsic content size of UILabel and NSTextField is ambiguous for multi-line text. The height of the text depends on the width of the lines, which is yet to be determined when solving the constraints. In order to solve this problem, both classes have a new property called preferredMaxLayoutWidth, which specifies the maximum line width for calculating the intrinsic content size.

Since we usually don’t know this value in advance, we need to take a two-step approach to get this right. First we let Auto Layout do its work, and then we use the resulting frame in the layout pass to update the preferred maximum width and trigger layout again.

- (void)layoutSubviews
{
    [super layoutSubviews];
    myLabel.preferredMaxLayoutWidth = myLabel.frame.size.width;
    [super layoutSubviews];
}

The first call to [super layoutSubviews] is necessary for the label to get its frame set, while the second call is necessary to update the layout after the change. If we omit the second call we get a NSInternalInconsistencyException error, because we’ve made changes in the layout pass which require updating the constraints, but we didn’t trigger layout again.

We can also do this in a label subclass itself:

@implementation MyLabel
- (void)layoutSubviews
{
    self.preferredMaxLayoutWidth = self.frame.size.width;
    [super layoutSubviews];
}
@end

In this case, we don’t need to call [super layoutSubviews] first, because when layoutSubviews gets called, we already have a frame on the label itself.

To make this adjustment from the view controller level, we hook into viewDidLayoutSubviews. At this point the frames of the first Auto Layout pass are already set and we can use them to set the preferred maximum width.

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    myLabel.preferredMaxLayoutWidth = myLabel.frame.size.width;
    [self.view layoutIfNeeded];
}

Lastly, make sure that you don’t have an explicit height constraint on the label that has a higher priority than the label’s content compression resistance priority. Otherwise it will trump the calculated height of the content. Make sure to check all the constraints that can affect label's height.

"Undefined reference to" template class constructor

This link explains where you're going wrong:

[35.12] Why can't I separate the definition of my templates class from its declaration and put it inside a .cpp file?

Place the definition of your constructors, destructors methods and whatnot in your header file, and that will correct the problem.

This offers another solution:

How can I avoid linker errors with my template functions?

However this requires you to anticipate how your template will be used and, as a general solution, is counter-intuitive. It does solve the corner case though where you develop a template to be used by some internal mechanism, and you want to police the manner in which it is used.

cast or convert a float to nvarchar?

You can also do something:

SELECT CAST(CAST(34512367.392 AS decimal(30,9)) AS NVARCHAR(100))

Output: 34512367.392000000

Passing parameters to a JQuery function

Using POST

function DoAction( id, name )
{
    $.ajax({
         type: "POST",
         url: "someurl.php",
         data: "id=" + id + "&name=" + name,
         success: function(msg){
                     alert( "Data Saved: " + msg );
                  }
    });
}

Using GET

function DoAction( id, name )
{
     $.ajax({
          type: "GET",
          url: "someurl.php",
          data: "id=" + id + "&name=" + name,
          success: function(msg){
                     alert( "Data Saved: " + msg );
                   }
     });
}

EDIT:

A, perhaps, better way to do this that would work (using GET) if javascript were not enabled would be to generate the URL for the href, then use a click handler to call that URL via ajax instead.

<a href="/someurl.php?id=1&name=Jose" class="ajax-link"> Click </a>
<a href="/someurl.php?id=2&name=Juan" class="ajax-link"> Click </a>
<a href="/someurl.php?id=3&name=Pedro" class="ajax-link"> Click </a>
...
<a href="/someurl.php?id=n&name=xxx" class="ajax-link"> Click </a>

<script type="text/javascript">
$(function() {
   $('.ajax-link').click( function() {
         $.get( $(this).attr('href'), function(msg) {
              alert( "Data Saved: " + msg );
         });
         return false; // don't follow the link!
   });
});
</script>

Cache an HTTP 'Get' service response in AngularJS?

As AngularJS factories are singletons, you can simply store the result of the http request and retrieve it next time your service is injected into something.

angular.module('myApp', ['ngResource']).factory('myService',
  function($resource) {
    var cache = false;
    return {
      query: function() {
        if(!cache) {
          cache = $resource('http://example.com/api').query();
        }
        return cache;
      }
    };
  }
);

Add leading zeroes to number in Java?

Since Java 1.5 you can use the String.format method. For example, to do the same thing as your example:

String format = String.format("%0%d", digits);
String result = String.format(format, num);
return result;

In this case, you're creating the format string using the width specified in digits, then applying it directly to the number. The format for this example is converted as follows:

%% --> %
0  --> 0
%d --> <value of digits>
d  --> d

So if digits is equal to 5, the format string becomes %05d which specifies an integer with a width of 5 printing leading zeroes. See the java docs for String.format for more information on the conversion specifiers.

codeigniter model error: Undefined property

You have to load the db library first. In autoload.php add :

$autoload['libraries'] = array('database');

Also, try renaming User model class for "User_model".

Easy way to use variables of enum types as string in C?

#define stringify( name ) # name

enum MyEnum {
    ENUMVAL1
};
...stuff...

stringify(EnumName::ENUMVAL1);  // Returns MyEnum::ENUMVAL1

Further discussion on this method

Preprocessor directive tricks for newcomers

What is the difference between using constructor vs getInitialState in React / React Native?

Constructor The constructor is a method that's automatically called during the creation of an object from a class. ... Simply put, the constructor aids in constructing things. In React, the constructor is no different. It can be used to bind event handlers to the component and/or initializing the local state of the component.Jan 23, 2019

getInitialState In ES6 classes, you can define the initial state by assigning this.state in the constructor:

Look at this example

var Counter = createReactClass({
  getInitialState: function() {
    return {count: this.props.initialCount};
  },
  // ...
});

With createReactClass(), you have to provide a separate getInitialState method that returns the initial state:

Android AudioRecord example

Here is an end to end solution I implemented for streaming Android microphone audio to a server for playback: Android AudioRecord to Server over UDP Playback Issues

AttributeError: Can only use .dt accessor with datetimelike values

First you need to define the format of date column.

df['Date'] = pd.to_datetime(df.Date, format='%Y-%m-%d %H:%M:%S')

For your case base format can be set to;

df['Date'] = pd.to_datetime(df.Date, format='%Y-%m-%d')

After that you can set/change your desired output as follows;

df['Date'] = df['Date'].dt.strftime('%Y-%m-%d')

Spring security CORS Filter

This solution unlock me after couple of hours of research :

In the configuration initialize the core() option

@Override
public void configure(HttpSecurity http) throws Exception {
http
    .cors()
    .and()
    .etc
}

Initialize your Credential, Origin, Header and Method as your wish in the corsFilter.

@Bean
public CorsFilter corsFilter() {
  UrlBasedCorsConfigurationSource source = new 
  UrlBasedCorsConfigurationSource();
  CorsConfiguration config = new CorsConfiguration();
  config.setAllowCredentials(true);
  config.addAllowedOrigin("*");
  config.addAllowedHeader("*");
  config.addAllowedMethod("*");
  source.registerCorsConfiguration("/**", config);
  return new CorsFilter(source);
}

I didn't need to use this class:

@Bean
public CorsConfigurationSource corsConfigurationSource() {
}

How can I find WPF controls by name or type?

You can use the VisualTreeHelper to find controls. Below is a method that uses the VisualTreeHelper to find a parent control of a specified type. You can use the VisualTreeHelper to find controls in other ways as well.

public static class UIHelper
{
   /// <summary>
   /// Finds a parent of a given item on the visual tree.
   /// </summary>
   /// <typeparam name="T">The type of the queried item.</typeparam>
   /// <param name="child">A direct or indirect child of the queried item.</param>
   /// <returns>The first parent item that matches the submitted type parameter. 
   /// If not matching item can be found, a null reference is being returned.</returns>
   public static T FindVisualParent<T>(DependencyObject child)
     where T : DependencyObject
   {
      // get parent item
      DependencyObject parentObject = VisualTreeHelper.GetParent(child);

      // we’ve reached the end of the tree
      if (parentObject == null) return null;

      // check if the parent matches the type we’re looking for
      T parent = parentObject as T;
      if (parent != null)
      {
         return parent;
      }
      else
      {
         // use recursion to proceed with next level
         return FindVisualParent<T>(parentObject);
      }
   }
}

Call it like this:

Window owner = UIHelper.FindVisualParent<Window>(myControl);

remove None value from a list without removing the 0 value

Iteration vs Space, usage could be an issue. In different situations profiling may show either to be "faster" and/or "less memory" intensive.

# first
>>> L = [0, 23, 234, 89, None, 0, 35, 9, ...]
>>> [x for x in L if x is not None]
[0, 23, 234, 89, 0, 35, 9, ...]

# second
>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> for i in range(L.count(None)): L.remove(None)
[0, 23, 234, 89, 0, 35, 9, ...]

The first approach (as also suggested by @jamylak, @Raymond Hettinger, and @Dipto) creates a duplicate list in memory, which could be costly of memory for a large list with few None entries.

The second approach goes through the list once, and then again each time until a None is reached. This could be less memory intensive, and the list will get smaller as it goes. The decrease in list size could have a speed up for lots of None entries in the front, but the worst case would be if lots of None entries were in the back.

The second approach would likely always be slower than the first approach. That does not make it an invalid consideration.

Parallelization and in-place techniques are other approaches, but each have their own complications in Python. Knowing the data and the runtime use-cases, as well profiling the program are where to start for intensive operations or large data.

Choosing either approach will probably not matter in common situations. It becomes more of a preference of notation. In fact, in those uncommon circumstances, numpy (example if L is numpy.array: L = L[L != numpy.array(None) (from here)) or cython may be worthwhile alternatives instead of attempting to micromanage Python optimizations.

Changing the URL in react-router v4 without using Redirect or Link

I'm using this to redirect with React Router v4:

this.props.history.push('/foo');

Hope it work for you ;)

How to build a Debian/Ubuntu package from source?

you can use the special package "checkinstall" for all packages which are not even in debian/ubuntu yet.

You can use "uupdate" (apt-get install devscripts) to build a package from source with existing debian sources:

Example for libdrm2:

apt-get build-dep libdrm2
apt-get source libdrm2
cd libdrm-2.3.1
uupdate ~/Downloads/libdrm-2.4.1.tar.gz
cd ../libdrm-2.4.1
dpkg-buildpackage -us -uc -nc

Java: how to import a jar file from command line

try

java -cp "your_jar.jar:lib/referenced_jar.jar" com.your.main.Main

If you are on windows, you should use ; instead of :

Git: Recover deleted (remote) branch

I think that you have a mismatched config for 'fetch' and 'push' so this has caused default fetch/push to not round trip properly. Fortunately you have fetched the branches that you subsequently deleted so you should be able to recreate them with an explicit push.

git push origin origin/contact_page:contact_page origin/new_pictures:new_pictures

Toggle show/hide on click with jQuery

$(document).ready( function(){
  $("button").click(function(){
    $("p").toggle(1000,'linear');
  });
});

Live Demo

Using Excel as front end to Access database (with VBA)

It Depends how much functionality you are expecting by Excel<->Acess solution. In many cases where you don't have budget to get a complete application solution, these little utilities does work. If the Scope of project is limited then I would go for this solution, because excel does give you flexibility to design spreadsheets as in accordance to your needs and then you may use those predesigned sheets for users to use. Designing a spreadsheet like form in Access is more time consuming and difficult and does requires some ActiveX. It object might not only handling data but presenting in spreadsheet like formates then this solution should works with limited scope.

Exception thrown inside catch block - will it be caught again?

As said above...
I would add that if you have trouble seeing what is going on, if you can't reproduce the issue in the debugger, you can add a trace before re-throwing the new exception (with the good old System.out.println at worse, with a good log system like log4j otherwise).

Make a directory and copy a file

You can use the shell for this purpose.

Set shl = CreateObject("WScript.Shell") 
shl.Run "cmd mkdir YourDir" & copy "

How do CORS and Access-Control-Allow-Headers work?

Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000 or Access-Control-Allow-Origin: * on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true on the POST response as well.

Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept to match the requested header.

Excel 2010 VBA Referencing Specific Cells in other worksheets

Sub Results2()

    Dim rCell As Range
    Dim shSource As Worksheet
    Dim shDest As Worksheet
    Dim lCnt As Long

    Set shSource = ThisWorkbook.Sheets("Sheet1")
    Set shDest = ThisWorkbook.Sheets("Sheet2")

    For Each rCell In shSource.Range("A1", shSource.Cells(shSource.Rows.Count, 1).End(xlUp)).Cells
        lCnt = lCnt + 1
        shDest.Range("A4").Offset(0, lCnt * 4).Formula = "=" & rCell.Address(False, False, , True) & "+" & rCell.Offset(0, 1).Address(False, False, , True)
    Next rCell

End Sub

This loops through column A of sheet1 and creates a formula in sheet2 for every cell. To find the last cell in Sheet1, I start at the bottom (shSource.Rows.Count) and .End(xlUp) to get the last cell in the column that's not blank.

To create the elements of the formula, I use the Address property of the cell on Sheet. I'm using three of the arguments to Address. The first two are RowAbsolute and ColumnAbsolute, both set to false. I don't care about the third argument, but I set the fourth argument (External) to True so that it includes the sheet name.

I prefer to go from Source to Destination rather than the other way. But that's just a personal preference. If you want to work from the destination,

Sub Results3()

    Dim i As Long, lCnt As Long
    Dim sh As Worksheet

    lCnt = Application.WorksheetFunction.CountA(ThisWorkbook.Sheets("Sheet1").Columns(1))
    Set sh = ThisWorkbook.Sheets("Sheet2")

    Const sSOURCE As String = "Sheet1!"

    For i = 1 To lCnt
        sh.Range("A1").Offset(0, 4 * (i - 1)).Formula = "=" & sSOURCE & "A" & i & " + " & sSOURCE & "B" & i
    Next i

End Sub

CSS rotation cross browser with jquery.animate()

Thanks yckart! Great contribution. I fleshed out your plugin a bit more. Added startAngle for full control and cross-browser css.

$.fn.animateRotate = function(startAngle, endAngle, duration, easing, complete){
    return this.each(function(){
        var elem = $(this);

        $({deg: startAngle}).animate({deg: endAngle}, {
            duration: duration,
            easing: easing,
            step: function(now){
                elem.css({
                  '-moz-transform':'rotate('+now+'deg)',
                  '-webkit-transform':'rotate('+now+'deg)',
                  '-o-transform':'rotate('+now+'deg)',
                  '-ms-transform':'rotate('+now+'deg)',
                  'transform':'rotate('+now+'deg)'
                });
            },
            complete: complete || $.noop
        });
    });
};

Random float number generation

In my opinion the above answer do give some 'random' float, but none of them is truly a random float (i.e. they miss a part of the float representation). Before I will rush into my implementation lets first have a look at the ANSI/IEEE standard format for floats:

|sign (1-bit)| e (8-bits) | f (23-bit) |

the number represented by this word is (-1 * sign) * 2^e * 1.f

note the the 'e' number is a biased (with a bias of 127) number thus ranging from -127 to 126. The most simple (and actually most random) function is to just write the data of a random int into a float, thus

int tmp = rand();
float f = (float)*((float*)&tmp);

note that if you do float f = (float)rand(); it will convert the integer into a float (thus 10 will become 10.0).

So now if you want to limit the maximum value you can do something like (not sure if this works)

int tmp = rand();
float f = *((float*)&tmp);
tmp = (unsigned int)f       // note float to int conversion!
tmp %= max_number;
f -= tmp;

but if you look at the structure of the float you can see that the maximum value of a float is (approx) 2^127 which is way larger as the maximum value of an int (2^32) thus ruling out a significant part of the numbers that can be represented by a float. This is my final implementation:

/**
 * Function generates a random float using the upper_bound float to determine 
 * the upper bound for the exponent and for the fractional part.
 * @param min_exp sets the minimum number (closest to 0) to 1 * e^min_exp (min -127)
 * @param max_exp sets the maximum number to 2 * e^max_exp (max 126)
 * @param sign_flag if sign_flag = 0 the random number is always positive, if 
 *              sign_flag = 1 then the sign bit is random as well
 * @return a random float
 */
float randf(int min_exp, int max_exp, char sign_flag) {
    assert(min_exp <= max_exp);

    int min_exp_mod = min_exp + 126;

    int sign_mod = sign_flag + 1;
    int frac_mod = (1 << 23);

    int s = rand() % sign_mod;  // note x % 1 = 0
    int e = (rand() % max_exp) + min_exp_mod;
    int f = rand() % frac_mod;

    int tmp = (s << 31) | (e << 23) | f;

    float r = (float)*((float*)(&tmp));

    /** uncomment if you want to see the structure of the float. */
//    printf("%x, %x, %x, %x, %f\n", (s << 31), (e << 23), f, tmp, r);

    return r;
}

using this function randf(0, 8, 0) will return a random number between 0.0 and 255.0

How to make two plots side-by-side using Python?

You can use - matplotlib.gridspec.GridSpec

Check - https://matplotlib.org/stable/api/_as_gen/matplotlib.gridspec.GridSpec.html

The below code displays a heatmap on right and an Image on left.

#Creating 1 row and 2 columns grid
gs = gridspec.GridSpec(1, 2) 
fig = plt.figure(figsize=(25,3))

#Using the 1st row and 1st column for plotting heatmap
ax=plt.subplot(gs[0,0])
ax=sns.heatmap([[1,23,5,8,5]],annot=True)

#Using the 1st row and 2nd column to show the image
ax1=plt.subplot(gs[0,1])
ax1.grid(False)
ax1.set_yticklabels([])
ax1.set_xticklabels([])

#The below lines are used to display the image on ax1
image = io.imread("https://images-na.ssl-images- amazon.com/images/I/51MvhqY1qdL._SL160_.jpg")

plt.imshow(image)
plt.show()

Output image

How to align input forms in HTML

A simple solution for you if you're new to HTML, is just to use a table to line everything up.

<form>
  <table>
    <tr>
      <td align="right">First Name:</td>
      <td align="left"><input type="text" name="first" /></td>
    </tr>
    <tr>
      <td align="right">Last Name:</td>
      <td align="left"><input type="text" name="last" /></td>
    </tr>
    <tr>
      <td align="right">Email:</td>
      <td align="left"><input type="text" name="email" /></td>
    </tr>
  </table>
</form>

Convert tabs to spaces in Notepad++

Follow this procedure to convert spaces to tabs or vice-versa:

Space - Tab

How do I check if a Sql server string is null or empty

[Column_name] > ' ' excludes Nulls and empty strings. There is a space between the single quotes.

URL Encoding using C#

I've been experimenting with the various methods .NET provide for URL encoding. Perhaps the following table will be useful (as output from a test app I wrote):

Unencoded UrlEncoded UrlEncodedUnicode UrlPathEncoded EscapedDataString EscapedUriString HtmlEncoded HtmlAttributeEncoded HexEscaped
A         A          A                 A              A                 A                A           A                    %41
B         B          B                 B              B                 B                B           B                    %42

a         a          a                 a              a                 a                a           a                    %61
b         b          b                 b              b                 b                b           b                    %62

0         0          0                 0              0                 0                0           0                    %30
1         1          1                 1              1                 1                1           1                    %31

[space]   +          +                 %20            %20               %20              [space]     [space]              %20
!         !          !                 !              !                 !                !           !                    %21
"         %22        %22               "              %22               %22              &quot;      &quot;               %22
#         %23        %23               #              %23               #                #           #                    %23
$         %24        %24               $              %24               $                $           $                    %24
%         %25        %25               %              %25               %25              %           %                    %25
&         %26        %26               &              %26               &                &amp;       &amp;                %26
'         %27        %27               '              '                 '                &#39;       &#39;                %27
(         (          (                 (              (                 (                (           (                    %28
)         )          )                 )              )                 )                )           )                    %29
*         *          *                 *              %2A               *                *           *                    %2A
+         %2b        %2b               +              %2B               +                +           +                    %2B
,         %2c        %2c               ,              %2C               ,                ,           ,                    %2C
-         -          -                 -              -                 -                -           -                    %2D
.         .          .                 .              .                 .                .           .                    %2E
/         %2f        %2f               /              %2F               /                /           /                    %2F
:         %3a        %3a               :              %3A               :                :           :                    %3A
;         %3b        %3b               ;              %3B               ;                ;           ;                    %3B
<         %3c        %3c               <              %3C               %3C              &lt;        &lt;                 %3C
=         %3d        %3d               =              %3D               =                =           =                    %3D
>         %3e        %3e               >              %3E               %3E              &gt;        >                    %3E
?         %3f        %3f               ?              %3F               ?                ?           ?                    %3F
@         %40        %40               @              %40               @                @           @                    %40
[         %5b        %5b               [              %5B               %5B              [           [                    %5B
\         %5c        %5c               \              %5C               %5C              \           \                    %5C
]         %5d        %5d               ]              %5D               %5D              ]           ]                    %5D
^         %5e        %5e               ^              %5E               %5E              ^           ^                    %5E
_         _          _                 _              _                 _                _           _                    %5F
`         %60        %60               `              %60               %60              `           `                    %60
{         %7b        %7b               {              %7B               %7B              {           {                    %7B
|         %7c        %7c               |              %7C               %7C              |           |                    %7C
}         %7d        %7d               }              %7D               %7D              }           }                    %7D
~         %7e        %7e               ~              ~                 ~                ~           ~                    %7E

A         %c4%80     %u0100            %c4%80         %C4%80            %C4%80           A           A                    [OoR]
a         %c4%81     %u0101            %c4%81         %C4%81            %C4%81           a           a                    [OoR]
E         %c4%92     %u0112            %c4%92         %C4%92            %C4%92           E           E                    [OoR]
e         %c4%93     %u0113            %c4%93         %C4%93            %C4%93           e           e                    [OoR]
I         %c4%aa     %u012a            %c4%aa         %C4%AA            %C4%AA           I           I                    [OoR]
i         %c4%ab     %u012b            %c4%ab         %C4%AB            %C4%AB           i           i                    [OoR]
O         %c5%8c     %u014c            %c5%8c         %C5%8C            %C5%8C           O           O                    [OoR]
o         %c5%8d     %u014d            %c5%8d         %C5%8D            %C5%8D           o           o                    [OoR]
U         %c5%aa     %u016a            %c5%aa         %C5%AA            %C5%AA           U           U                    [OoR]
u         %c5%ab     %u016b            %c5%ab         %C5%AB            %C5%AB           u           u                    [OoR]

The columns represent encodings as follows:

  • UrlEncoded: HttpUtility.UrlEncode

  • UrlEncodedUnicode: HttpUtility.UrlEncodeUnicode

  • UrlPathEncoded: HttpUtility.UrlPathEncode

  • EscapedDataString: Uri.EscapeDataString

  • EscapedUriString: Uri.EscapeUriString

  • HtmlEncoded: HttpUtility.HtmlEncode

  • HtmlAttributeEncoded: HttpUtility.HtmlAttributeEncode

  • HexEscaped: Uri.HexEscape

NOTES:

  1. HexEscape can only handle the first 255 characters. Therefore it throws an ArgumentOutOfRange exception for the Latin A-Extended characters (eg A).

  2. This table was generated in .NET 4.0 (see Levi Botelho's comment below that says the encoding in .NET 4.5 is slightly different).

EDIT:

I've added a second table with the encodings for .NET 4.5. See this answer: https://stackoverflow.com/a/21771206/216440

EDIT 2:

Since people seem to appreciate these tables, I thought you might like the source code that generates the table, so you can play around yourselves. It's a simple C# console application, which can target either .NET 4.0 or 4.5:

using System;
using System.Collections.Generic;
using System.Text;
// Need to add a Reference to the System.Web assembly.
using System.Web;

namespace UriEncodingDEMO2
{
    class Program
    {
        static void Main(string[] args)
        {
            EncodeStrings();

            Console.WriteLine();
            Console.WriteLine("Press any key to continue...");
            Console.Read();
        }

        public static void EncodeStrings()
        {
            string stringToEncode = "ABCD" + "abcd"
            + "0123" + " !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~" + "AaEeIiOoUu";

            // Need to set the console encoding to display non-ASCII characters correctly (eg the 
            //  Latin A-Extended characters such as AaEe...).
            Console.OutputEncoding = Encoding.UTF8;

            // Will also need to set the console font (in the console Properties dialog) to a font 
            //  that displays the extended character set correctly.
            // The following fonts all display the extended characters correctly:
            //  Consolas
            //  DejaVu Sana Mono
            //  Lucida Console

            // Also, in the console Properties, set the Screen Buffer Size and the Window Size 
            //  Width properties to at least 140 characters, to display the full width of the 
            //  table that is generated.

            Dictionary<string, Func<string, string>> columnDetails =
                new Dictionary<string, Func<string, string>>();
            columnDetails.Add("Unencoded", (unencodedString => unencodedString));
            columnDetails.Add("UrlEncoded",
                (unencodedString => HttpUtility.UrlEncode(unencodedString)));
            columnDetails.Add("UrlEncodedUnicode",
                (unencodedString => HttpUtility.UrlEncodeUnicode(unencodedString)));
            columnDetails.Add("UrlPathEncoded",
                (unencodedString => HttpUtility.UrlPathEncode(unencodedString)));
            columnDetails.Add("EscapedDataString",
                (unencodedString => Uri.EscapeDataString(unencodedString)));
            columnDetails.Add("EscapedUriString",
                (unencodedString => Uri.EscapeUriString(unencodedString)));
            columnDetails.Add("HtmlEncoded",
                (unencodedString => HttpUtility.HtmlEncode(unencodedString)));
            columnDetails.Add("HtmlAttributeEncoded",
                (unencodedString => HttpUtility.HtmlAttributeEncode(unencodedString)));
            columnDetails.Add("HexEscaped",
                (unencodedString
                    =>
                    {
                        // Uri.HexEscape can only handle the first 255 characters so for the 
                        //  Latin A-Extended characters, such as A, it will throw an 
                        //  ArgumentOutOfRange exception.                       
                        try
                        {
                            return Uri.HexEscape(unencodedString.ToCharArray()[0]);
                        }
                        catch
                        {
                            return "[OoR]";
                        }
                    }));

            char[] charactersToEncode = stringToEncode.ToCharArray();
            string[] stringCharactersToEncode = Array.ConvertAll<char, string>(charactersToEncode,
                (character => character.ToString()));
            DisplayCharacterTable<string>(stringCharactersToEncode, columnDetails);
        }

        private static void DisplayCharacterTable<TUnencoded>(TUnencoded[] unencodedArray,
            Dictionary<string, Func<TUnencoded, string>> mappings)
        {
            foreach (string key in mappings.Keys)
            {
                Console.Write(key.Replace(" ", "[space]") + " ");
            }
            Console.WriteLine();

            foreach (TUnencoded unencodedObject in unencodedArray)
            {
                string stringCharToEncode = unencodedObject.ToString();
                foreach (string columnHeader in mappings.Keys)
                {
                    int columnWidth = columnHeader.Length + 1;
                    Func<TUnencoded, string> encoder = mappings[columnHeader];
                    string encodedString = encoder(unencodedObject);

                    // ASSUMPTION: Column header will always be wider than encoded string.
                    Console.Write(encodedString.Replace(" ", "[space]").PadRight(columnWidth));
                }
                Console.WriteLine();
            }
        }
    }
}

Download text/csv content as files from server in Angular

Most of the references on the web about this issue point out to the fact that you cannot download files via ajax call 'out of the box'. I have seen (hackish) solutions that involve iframes and also solutions like @dcodesmith's that work and are perfectly viable.

Here's another solution I found that works in Angular and is very straighforward.

In the view, wrap the csv download button with <a> tag the following way :

<a target="_self" ng-href="{{csv_link}}">
  <button>download csv</button>
</a>

(Notice the target="_self there, it's crucial to disable Angular's routing inside the ng-app more about it here)

Inside youre controller you can define csv_link the following way :

$scope.csv_link = '/orders' + $window.location.search;

(the $window.location.search is optional and onlt if you want to pass additionaly search query to your server)

Now everytime you click the button, it should start downloading.

how to fix java.lang.IndexOutOfBoundsException

Use if(index.length() < 0) for Integer

or

Use if(index.equals(null) for String

Get first day of week in SQL Server

I found this simple and usefull. Works even if first day of week is Sunday or Monday.

DECLARE @BaseDate AS Date

SET @BaseDate = GETDATE()

DECLARE @FisrtDOW AS Date

SELECT @FirstDOW = DATEADD(d,DATEPART(WEEKDAY,@BaseDate) *-1 + 1, @BaseDate)

What is the purpose of flush() in Java streams?

When we give any command, the streams of that command are stored in the memory location called buffer(a temporary memory location) in our computer. When all the temporary memory location is full then we use flush(), which flushes all the streams of data and executes them completely and gives a new space to new streams in buffer temporary location. -Hope you will understand

How do I escape a string inside JavaScript code inside an onClick handler?

I have faced this problem as well. I made a script to convert single quotes into escaped double quotes that won't break the HTML.

function noQuote(text)
{
    var newtext = "";
    for (var i = 0; i < text.length; i++) {
        if (text[i] == "'") {
            newtext += "\"";
        }
        else {
            newtext += text[i];
        }
    }
    return newtext;
}

Check if passed argument is file or directory in Bash

That should work. I am not sure why it's failing. You're quoting your variables properly. What happens if you use this script with double [[ ]]?

if [[ -d $PASSED ]]; then
    echo "$PASSED is a directory"
elif [[ -f $PASSED ]]; then
    echo "$PASSED is a file"
else
    echo "$PASSED is not valid"
    exit 1
fi

Double square brackets is a bash extension to [ ]. It doesn't require variables to be quoted, not even if they contain spaces.

Also worth trying: -e to test if a path exists without testing what type of file it is.

Can I use a binary literal in C or C++?

template<unsigned long N>
struct bin {
    enum { value = (N%10)+2*bin<N/10>::value };
} ;

template<>
struct bin<0> {
    enum { value = 0 };
} ;

// ...
    std::cout << bin<1000>::value << '\n';

The leftmost digit of the literal still has to be 1, but nonetheless.

Failed to install android-sdk: "java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema"

For me i install java version 8 and just select the java version in "JDK location": enter image description here

Why doesn't importing java.util.* include Arrays and Lists?

Case 1 should have worked. I don't see anything wrong. There may be some other problems. I would suggest a clean build.

Problems using Maven and SSL behind proxy

Step 1: GET the contents of the Certificate of the website( you want to have it imported as a trusted root)

$ keytool -printcert -rfc -sslserver maven.2xoffice.com*

-----BEGIN CERTIFICATE-----
MIIFNTCCBB2gAwIBAgIHJ73QrVnyJjANBgkqhkiG9w0BAQsFADCBtDELMAkGA1UEBhMCVVMxEDAO
...
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIIE3jCCA8agAwIBAgICAwEwDQYJKoZIhvcNAQEFBQAwYzELMAkGA1UEBhMCVVMxITAfBgNVBAoT
...
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIIEADCCAuigAwIBAgIBADANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEhMB8GA1UEChMY
...
-----END CERTIFICATE-----
The -rfc option outputs the certificate chain in PEM-encoded format for easy import back into a keystore.

Step 2: Save the whole thing (including the BEGIN CERTIFICATE and END CERTIFICATE lines, which are significant in this case) as godaddyg2.pem and imported it into my trust store via:

Step 3: Import the certificate in the keystore( java trusted key store)

$ keytool -importcert -file ./godaddyg2.pem -keystore $JRE_LIB/lib/security/cacerts

How to create a dotted <hr/> tag?

hr {
    border: 1px dotted #ff0000;
    border-style: none none dotted; 
    color: #fff; 
    background-color: #fff;
}

Try this

Bluetooth pairing without user confirmation

BT version 2.0 or less - You should be able to pair/bond using a standard PIN code, entered programmatically e.g. 1234 or 0000. This is not very secure but many BT devices do this.

BT version 2.1 or greater - Mode 4 Secure Simple Pairing "just works" model can be used. It uses elliptical encryption (whatever that is) and is very secure but is open to Man In The Middle attacks. Compared to the old '0000' pin code approach it is light years ahead. This doesn't require any user input.

This is according to the Bluetooth specs but what you can use depends on what verson of the Bluetooth standard your stack supports and what API you have.

MVVM Passing EventArgs As Command Parameter

With Behaviors and Actions in Blend for Visual Studio 2013 you can use the InvokeCommandAction. I tried this with the Drop event and although no CommandParameter was specified in the XAML, to my surprise, the Execute Action parameter contained the DragEventArgs. I presume this would happen for other events but have not tested them.

Edit and Continue: "Changes are not allowed when..."

None of the above solutions worked for me(running on a 64x machine).

Finally I clicked on 'advanced compiler settings' and UNCHECKED 'enable optimizations' and I can now step through code and edit while debugging.

jQuery set radio button

Combining previous answers:

$('input[name="cols"]').filter("[value='Site']").click();

Class file for com.google.android.gms.internal.zzaja not found

As stated in the Google documentation, Add the latest version of the Google Service plugin (4.0.1 on 06/04/18). Hope this hepls!

buildscript {
    // ...
    dependencies {
        // ...
        classpath 'com.google.gms:google-services:4.0.1' // google-services plugin
    }
}
`

CSS: How to have position:absolute div inside a position:relative div not be cropped by an overflow:hidden on a container

A trick that works is to position box #2 with position: absolute instead of position: relative. We usually put a position: relative on an outer box (here box #2) when we want an inner box (here box #3) with position: absolute to be positioned relative to the outer box. But remember: for box #3 to be positioned relative to box #2, box #2 just need to be positioned. With this change, we get:

And here is the full code with this change:

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <style type="text/css">

            /* Positioning */
            #box1 { overflow: hidden }
            #box2 { position: absolute }
            #box3 { position: absolute; top: 10px }

            /* Styling */
            #box1 { background: #efe; padding: 5px; width: 125px }
            #box2 { background: #fee; padding: 2px; width: 100px; height: 100px }
            #box3 { background: #eef; padding: 2px; width: 75px; height: 150px }

        </style>
    </head>
    <body>
        <br/><br/><br/>
        <div id="box1">
            <div id="box2">
                <div id="box3"/>
            </div>
        </div>
    </body>
</html>

When to use MongoDB or other document oriented database systems?

Who needs distributed, sharded forums? Maybe Facebook, but unless you're creating a Facebook-competitor, just use Mysql, Postgres or whatever you are most comfortable with. If you want to try MongoDB, ok, but don't expect it to do magic for you. It'll have its quirks and general nastiness, just as everything else, as I'm sure you've already discovered if you really have been working on it already.

Sure, MongoDB may be hyped and seem easy on the surface, but you'll run into problems which more mature products have already overcome. Don't be lured so easily, but rather wait until "nosql" matures, or dies.

Personally, I think "nosql" will wither and die from fragmentation, as there are no set standards (almost by definition). So I will not personally bet on it for any long-term projects.

Only thing that can save "nosql" in my book, is if it can integrate into Ruby or similar languages seamlessly, and make the language "persistent", almost without any overhead in coding and design. That may come to pass, but I'll wait until then, not now, AND it needs to be more mature of course.

Btw, why are you creating a forum from scratch? There are tons of open source forums which can be tweaked to fit most requirements, unless you really are creating The Next Generation of Forums (which I doubt).

Node.js project naming conventions for files & folders

Based on 'Google JavaScript Style Guide'

File names must be all lowercase and may include underscores (_) or dashes (-), but no additional punctuation. Follow the convention that your project uses. Filenames’ extension must be .js.

Difference between InvariantCulture and Ordinal string comparison

Pointing to Best Practices for Using Strings in the .NET Framework:

  • Use StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase for comparisons as your safe default for culture-agnostic string matching.
  • Use comparisons with StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase for better performance.
  • Use the non-linguistic StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase values instead of string operations based on CultureInfo.InvariantCulture when the comparison is linguistically irrelevant (symbolic, for example).

And finally:

  • Do not use string operations based on StringComparison.InvariantCulture in most cases. One of the few exceptions is when you are persisting linguistically meaningful but culturally agnostic data.

How to programmatically empty browser cache?

You can now use Cache.delete()

Example:

let id = "your-cache-id";
// you can find the id by going to 
// application>storage>cache storage 
// (minus the page url at the end)
// in your chrome developer console 

caches.open(id)
.then(cache => cache.keys()
  .then(keys => {
    for (let key of keys) {
      cache.delete(key)
    }
  }));

Works on Chrome 40+, Firefox 39+, Opera 27+ and Edge.

Store select query's output in one array in postgres

I had exactly the same problem. Just one more working modification of the solution given by Denis (the type must be specified):

SELECT ARRAY(
SELECT column_name::text
FROM information_schema.columns
WHERE table_name='aean'
)

Java String - See if a string contains only numbers and not letters

It is a bad practice to involve any exception throwing/handling into such a typical scenario.

Therefore a parseInt() is not nice, but a regex is an elegant solution for this, but take care of the following:
-fractions
-negative numbers
-decimal separator might differ in contries (e.g. ',' or '.')
-sometimes it is allowed to have a so called thousand separator, like a space or a comma e.g. 12,324,1000.355

To handle all the necessary cases in your application you have to be careful, but this regex covers the typical scenarios (positive/negative and fractional, separated by a dot): ^[-+]?\d*.?\d+$
For testing, I recommend regexr.com.

Random color generator

Using ES6's Array.from() method, I created this solution:

function randomColor() {
  return "#"+ Array.from({length: 6},()=> Math.floor(Math.random()*16).toString(16)).join("");
}

The other implementations I've seen need to ensure that if the hexadecimal value has leading zeros, the number still contains six digits.

K._'s answer used ES6's padStart for this:

function randomColor() {
  return `#${Math.floor(Math.random() * 0x1000000).toString(16).padStart(6, 0)}`
}

The other good single-line solution I've seen is

function randomColor() {
  return '#'+ ('000000' + (Math.random()*0xFFFFFF<<0).toString(16)).slice(-6);
}

Catch an exception thrown by an async void method

The exception can be caught in the async function.

public async void Foo()
{
    try
    {
        var x = await DoSomethingAsync();
        /* Handle the result, but sometimes an exception might be thrown
           For example, DoSomethingAsync get's data from the network
           and the data is invalid... a ProtocolException might be thrown */
    }
    catch (ProtocolException ex)
    {
          /* The exception will be caught here */
    }
}

public void DoFoo()
{
    Foo();
}

How can I kill whatever process is using port 8080 so that I can vagrant up?

I needed to kill processes on different ports so I created a bash script:

killPort() {
  PID=$(echo $(lsof -n -i4TCP:$1) | awk 'NR==1{print $11}')
  kill -9 $PID
}

Just add that to your .bashrc and run it like this:

killPort 8080

You can pass whatever port number you wish

How to distinguish between left and right mouse click with jQuery

You can also bind to contextmenu and return false:

$('selector').bind('contextmenu', function(e){
    e.preventDefault();
    //code
    return false;
});

Demo: http://jsfiddle.net/maniator/WS9S2/

Or you can make a quick plugin that does the same:

(function( $ ) {
  $.fn.rightClick = function(method) {

    $(this).bind('contextmenu rightclick', function(e){
        e.preventDefault();
        method();
        return false;
    });

  };
})( jQuery );

Demo: http://jsfiddle.net/maniator/WS9S2/2/


Using .on(...) jQuery >= 1.7:

$(document).on("contextmenu", "selector", function(e){
    e.preventDefault();
    //code
    return false;
});  //does not have to use `document`, it could be any container element.

Demo: http://jsfiddle.net/maniator/WS9S2/283/

Precision String Format Specifier In Swift

I don't know about two decimal places, but here's how you can print floats with zero decimal places, so I'd imagine that can be 2 place, 3, places ... (Note: you must convert CGFloat to Double to pass to String(format:) or it will see a value of zero)

func logRect(r: CGRect, _ title: String = "") {
    println(String(format: "[ (%.0f, %.0f), (%.0f, %.0f) ] %@",
        Double(r.origin.x), Double(r.origin.y), Double(r.size.width), Double(r.size.height), title))
}

Check whether specific radio button is checked

I think you're using the wrong approach. You should set the value attribute of your input elements. Check the docs for .val() for examples of setting and returning the .val() of input elements.

ie.

<input type="radio" runat="server" name="testGroup" value="test2" />

return $('input:radio[name=testGroup]:checked').val() == 'test2';

Generate an HTML Response in a Java Servlet

You normally forward the request to a JSP for display. JSP is a view technology which provides a template to write plain vanilla HTML/CSS/JS in and provides ability to interact with backend Java code/variables with help of taglibs and EL. You can control the page flow with taglibs like JSTL. You can set any backend data as an attribute in any of the request, session or application scope and use EL (the ${} things) in JSP to access/display them. You can put JSP files in /WEB-INF folder to prevent users from directly accessing them without invoking the preprocessing servlet.

Kickoff example:

@WebServlet("/hello")
public class HelloWorldServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String message = "Hello World";
        request.setAttribute("message", message); // This will be available as ${message}
        request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
    }

}

And /WEB-INF/hello.jsp look like:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 2370960</title>
    </head>
    <body>
         <p>Message: ${message}</p>
    </body>
</html>

When opening http://localhost:8080/contextpath/hello this will show

Message: Hello World

in the browser.

This keeps the Java code free from HTML clutter and greatly improves maintainability. To learn and practice more with servlets, continue with below links.

Also browse the "Frequent" tab of all questions tagged [servlets] to find frequently asked questions.

Displaying better error message than "No JSON object could be decoded"

You could use cjson, that claims to be up to 250 times faster than pure-python implementations, given that you have "some long complicated JSON file" and you will probably need to run it several times (decoders fail and report the first error they encounter only).

Mockito How to mock only the call of a method of the superclass

Maybe the easiest option if inheritance makes sense is to create a new method (package private??) to call the super (lets call it superFindall), spy the real instance and then mock the superFindAll() method in the way you wanted to mock the parent class one. It's not the perfect solution in terms of coverage and visibility but it should do the job and it's easy to apply.

 public Childservice extends BaseService {
    public void save(){
        //some code
        superSave();
    }

    void superSave(){
        super.save();
    }
}

I want to add a JSONObject to a JSONArray and that JSONArray included in other JSONObject

JSONArray successObject=new JSONArray();
JSONObject dataObject=new JSONObject();
successObject.put(dataObject.toString());

This works for me.

Dynamically replace img src attribute with jQuery

You need to check out the attr method in the jQuery docs. You are misusing it. What you are doing within the if statements simply replaces all image tags src with the string specified in the 2nd parameter.

http://api.jquery.com/attr/

A better way to approach replacing a series of images source would be to loop through each and check it's source.

Example:

$('img').each(function () {
  var curSrc = $(this).attr('src');
  if ( curSrc === 'http://example.com/smith.gif' ) {
      $(this).attr('src', 'http://example.com/johnson.gif');
  }
  if ( curSrc === 'http://example.com/williams.gif' ) {
      $(this).attr('src', 'http://example.com/brown.gif');
  }
});

How to query a CLOB column in Oracle

This works

select DBMS_LOB.substr(myColumn, 3000) from myTable

Clear text input on click with AngularJS

In Your Controller

$scope.clearSearch = function() {
     $scope.searchAll = '';
}

font-family is inherit. How to find out the font-family in chrome developer pane?

I think op wants to know what the font that is used on a webpage is, and hoped that info might be findable in the 'inspect' pane.

Try adding the Whatfont Chrome extension.

Importing Excel into a DataTable Quickly

Caling .Value2 is an expensive operation because it's a COM-interop call. I would instead read the entire range into an array and then loop through the array:

object[,] data = Range.Value2;

// Create new Column in DataTable
for (int cCnt = 1; cCnt <= Range.Columns.Count; cCnt++)
{
    textBox3.Text = cCnt.ToString();

    var Column = new DataColumn();
    Column.DataType = System.Type.GetType("System.String");
    Column.ColumnName = cCnt.ToString();
    DT.Columns.Add(Column);

    // Create row for Data Table
    for (int rCnt = 1; rCnt <= Range.Rows.Count; rCnt++)
    {
        textBox2.Text = rCnt.ToString();

        string CellVal = String.Empty;
        try
        {
            cellVal = (string)(data[rCnt, cCnt]);
        }
        catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)
        {
            ConvertVal = (double)(data[rCnt, cCnt]);
            cellVal = ConvertVal.ToString();
        }

        DataRow Row;

        // Add to the DataTable
        if (cCnt == 1)
        {

            Row = DT.NewRow();
            Row[cCnt.ToString()] = cellVal;
            DT.Rows.Add(Row);
        }
        else
        {

            Row = DT.Rows[rCnt + 1];
            Row[cCnt.ToString()] = cellVal;

        }
    }
} 

"Parameter not valid" exception loading System.Drawing.Image

all the solutions given doesnt work.. dont concentrate only on the retrieving part. luk at the inserting of the image. i did the same mistake. I tuk an image from hard disk and saved it to database. The problem lies in the insert command. luk at my fault code..:

 public bool convertImage()
    {
        try
        {
            MemoryStream ms = new MemoryStream();
            pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
            photo = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(photo, 0, photo.Length);
            return true;
        }
        catch
        {
            MessageBox.Show("image can not be converted");
            return false;
        }
    }
    public void insertImage()
    {
       // SqlConnection con = new SqlConnection();
        try
        {
            cs.Close();
            cs.Open();
            da.UpdateCommand = new SqlCommand("UPDATE All_students SET disco = " +photo+" WHERE Reg_no = '" + Convert.ToString(textBox1.Text)+ "'", cs);
            da.UpdateCommand.ExecuteNonQuery();
            cs.Close();
            cs.Open();
            int i = da.UpdateCommand.ExecuteNonQuery();
            if (i > 0)
            {
                MessageBox.Show("Successfully Inserted...");
            }

        }
        catch
        {
            MessageBox.Show("Error in Connection");
        }
        cs.Close();
    }

The above code shows succesfully inserted... but actualy its saving the image in the form of wrong datatype.. whereas the datatype must bt "image".. so i improved the code..

  public bool convertImage()
    {
        try
        {
            MemoryStream ms = new MemoryStream();
            pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
            photo = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(photo, 0, photo.Length);
            return true;
        }
        catch
        {
            MessageBox.Show("image can not be converted");
            return false;
        }
    }
    public void insertImage()
    {
       // SqlConnection con = new SqlConnection();
        try
        {
            cs.Close();
            cs.Open();
            //THIS WHERE THE CODE MUST BE CHANGED>>>>>>>>>>>>>>

            da.UpdateCommand = new SqlCommand("UPDATE All_students SET disco = @img WHERE Reg_no = '" + Convert.ToString(textBox1.Text)+ "'", cs);
            da.UpdateCommand.Parameters.Add("@img", SqlDbType.Image);//CHANGED TO IMAGE DATATYPE...
            da.UpdateCommand.Parameters["@img"].Value = photo;
            da.UpdateCommand.ExecuteNonQuery();
            cs.Close();
            cs.Open();
            int i = da.UpdateCommand.ExecuteNonQuery();
            if (i > 0)
            {
                MessageBox.Show("Successfully Inserted...");
            }

        }
        catch
        {
            MessageBox.Show("Error in Connection");
        }
        cs.Close();
    }

100% gurantee that there will be no PARAMETER NOT VALID error in retrieving....SOLVED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Removing all empty elements from a hash / YAML?

Here is something I have:

# recursively remove empty keys (hashes), values (array), hashes and arrays from hash or array
def sanitize data
  case data
  when Array
    data.delete_if { |value| res = sanitize(value); res.blank? }
  when Hash
    data.delete_if { |_, value| res = sanitize(value); res.blank? }
  end
  data.blank? ? nil : data
end

How to do encryption using AES in Openssl

My suggestion is to run

openssl enc -aes-256-cbc -in plain.txt -out encrypted.bin

under debugger and see what exactly what it is doing. openssl.c is the only real tutorial/getting started/reference guide OpenSSL has. All other documentation is just an API reference.

U1: My guess is that you are not setting some other required options, like mode of operation (padding).

U2: this is probably a duplicate of this question: AES CTR 256 Encryption Mode of operation on OpenSSL and answers there will likely help.

Order discrete x scale by frequency/value

The best way for me was using vector with categories in order I need as limits parameter to scale_x_discrete. I think it is pretty simple and straightforward solution.

ggplot(mtcars, aes(factor(cyl))) + 
  geom_bar() + 
  scale_x_discrete(limits=c(8,4,6))

enter image description here

MySQL "between" clause not inclusive?

The field dob probably has a time component.

To truncate it out:

select * from person 
where CAST(dob AS DATE) between '2011-01-01' and '2011-01-31'

How can I convert a Unix timestamp to DateTime and vice versa?

Unix time conversion is new in .NET Framework 4.6.

You can now more easily convert date and time values to or from .NET Framework types and Unix time. This can be necessary, for example, when converting time values between a JavaScript client and .NET server. The following APIs have been added to the DateTimeOffset structure:

static DateTimeOffset FromUnixTimeSeconds(long seconds)
static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds)
long DateTimeOffset.ToUnixTimeSeconds()
long DateTimeOffset.ToUnixTimeMilliseconds()

How to upload folders on GitHub

This is Web GUI of a GitHub repository:

enter image description here

Drag and drop your folder to the above area. When you upload too much folder/files, GitHub will notice you:

Yowza, that’s a lot of files. Try again with fewer than 100 files.

enter image description here

and add commit message

enter image description here

And press button Commit changes is the last step.

UTF-8 output from PowerShell

Spent some time working on a solution to my issue and thought it may be of interest. I ran into a problem trying to automate code generation using PowerShell 3.0 on Windows 8. The target IDE was the Keil compiler using MDK-ARM Essential Toolchain 5.24.1. A bit different from OP, as I am using PowerShell natively during the pre-build step. When I tried to #include the generated file, I received the error

fatal error: UTF-16 (LE) byte order mark detected '..\GITVersion.h' but encoding is not supported

I solved the problem by changing the line that generated the output file from:

out-file -FilePath GITVersion.h -InputObject $result

to:

out-file -FilePath GITVersion.h -Encoding ascii -InputObject $result

What does '<?=' mean in PHP?

I hope it doesn't get deprecated. While writing <? blah code ?> is fairly unnecessary and confusable with XHTML, <?= isn't, for obvious reasons. Unfortunately I don't use it, because short_open_tag seems to be disabled more and more.

Update: I do use <?= again now, because it is enabled by default with PHP 5.4.0. See http://php.net/manual/en/language.basic-syntax.phptags.php

jQuery change input text value

Just adding to Jason's answer, the . selector is only for classes. If you want to select something other than the element, id, or class, you need to wrap it in square brackets.

e.g.

$('element[attr=val]')

How to start and stop android service from a adb shell?

If you want to run the script in adb shell, then I am trying to do the same, but with an application. I think you can use "am start" command

usage: am [subcommand] [options]

start an Activity: am start [-D] [-W] <INTENT>
    -D: enable debugging
    -W: wait for launch to complete

**start a Service: am startservice <INTENT>**

send a broadcast Intent: am broadcast <INTENT>

start an Instrumentation: am instrument [flags] <COMPONENT>
    -r: print raw results (otherwise decode REPORT_KEY_STREAMRESULT)
    -e <NAME> <VALUE>: set argument <NAME> to <VALUE>
    -p <FILE>: write profiling data to <FILE>
    -w: wait for instrumentation to finish before returning

start profiling: am profile <PROCESS> start <FILE>
stop profiling: am profile <PROCESS> stop

start monitoring: am monitor [--gdb <port>]
    --gdb: start gdbserv on the given port at crash/ANR

<INTENT> specifications include these flags:
    [-a <ACTION>] [-d <DATA_URI>] [-t <MIME_TYPE>]
    [-c <CATEGORY> [-c <CATEGORY>] ...]
    [-e|--es <EXTRA_KEY> <EXTRA_STRING_VALUE> ...]
    [--esn <EXTRA_KEY> ...]
    [--ez <EXTRA_KEY> <EXTRA_BOOLEAN_VALUE> ...]
    [-e|--ei <EXTRA_KEY> <EXTRA_INT_VALUE> ...]
    [-n <COMPONENT>] [-f <FLAGS>]
    [--grant-read-uri-permission] [--grant-write-uri-permission]
    [--debug-log-resolution]
    [--activity-brought-to-front] [--activity-clear-top]
    [--activity-clear-when-task-reset] [--activity-exclude-from-recents]
    [--activity-launched-from-history] [--activity-multiple-task]
    [--activity-no-animation] [--activity-no-history]
    [--activity-no-user-action] [--activity-previous-is-top]
    [--activity-reorder-to-front] [--activity-reset-task-if-needed]
    [--activity-single-top]
    [--receiver-registered-only] [--receiver-replace-pending]
    [<URI>]

Remove x-axis label/text in chart.js

For those whom this did not work, here is how I hid the labels on the X-axis-

options: {
    maintainAspectRatio: false,
    layout: {
      padding: {
        left: 1,
        right: 2,
        top: 2,
        bottom: 0,
      },
    },
    scales: {
      xAxes: [
        {
          time: {
            unit: 'Areas',
          },
          gridLines: {
            display: false,
            drawBorder: false,
          },
          ticks: {
            maxTicksLimit: 7,
            display: false, //this removed the labels on the x-axis
          },
          'dataset.maxBarThickness': 5,
        },
      ],

Python Selenium Chrome Webdriver

You need to specify the path where your chromedriver is located.

  1. Download chromedriver for your desired platform from here.

  2. Place chromedriver on your system path, or where your code is.

  3. If not using a system path, link your chromedriver.exe (For non-Windows users, it's just called chromedriver):

    browser = webdriver.Chrome(executable_path=r"C:\path\to\chromedriver.exe")
    

    (Set executable_path to the location where your chromedriver is located.)

    If you've placed chromedriver on your System Path, you can shortcut by just doing the following:

    browser = webdriver.Chrome()

  4. If you're running on a Unix-based operating system, you may need to update the permissions of chromedriver after downloading it in order to make it executable:

    chmod +x chromedriver

  5. That's all. If you're still experiencing issues, more info can be found on this other StackOverflow article: Can't use chrome driver for Selenium

div with dynamic min-height based on browser window height

As mentioned elsewhere, the CSS function calc() can work nicely here. It is now mostly supported. You could use like:

.container
{
    min-height: 70%;
    min-height: -webkit-calc(100% - 300px);
    min-height: -moz-calc(100% - 300px);
    min-height: calc(100% - 300px);
}

javac: file not found: first.java Usage: javac <options> <source files>

First set your path to C:/Program Files/Java/jdk1.8.0/bin in the environment variables. Say, your file is saved in the C: drive Now open the command prompt and move to the directory using c: javac Filename.java java Filename

Make sure you save the file name as .java.

If it is saved as a text file name then file not found error results as it cannot the text file.

The remote server returned an error: (407) Proxy Authentication Required

Thought of writing this answer as nothing worked from above & you don't want to specify proxy location.

If you're using httpClient then consider this.

HttpClientHandler handler = new HttpClientHandler();

IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = CredentialCache.DefaultCredentials;
handler.Proxy = proxy;

var client = new HttpClient(handler);
// your next steps...

And if you're using HttpWebRequest:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri + _endpoint);

IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = CredentialCache.DefaultCredentials;
request.Proxy = proxy;

Kind referencce: https://medium.com/@siriphonnot/the-remote-server-returned-an-error-407-proxy-authentication-required-86ae489e401b

How to stop asynctask thread in android?

I had a similar problem - essentially I was getting a NPE in an async task after the user had destroyed the fragment. After researching the problem on Stack Overflow, I adopted the following solution:

volatile boolean running;

public void onActivityCreated (Bundle savedInstanceState) {

    super.onActivityCreated(savedInstanceState);

    running=true;
    ...
    }


public void onDestroy() {
    super.onDestroy();

    running=false;
    ...
}

Then, I check "if running" periodically in my async code. I have stress tested this and I am now unable to "break" my activity. This works perfectly and has the advantage of being simpler than some of the solutions I have seen on SO.

How to generate a simple popup using jQuery

First the CSS - tweak this however you like:

a.selected {
  background-color:#1F75CC;
  color:white;
  z-index:100;
}

.messagepop {
  background-color:#FFFFFF;
  border:1px solid #999999;
  cursor:default;
  display:none;
  margin-top: 15px;
  position:absolute;
  text-align:left;
  width:394px;
  z-index:50;
  padding: 25px 25px 20px;
}

label {
  display: block;
  margin-bottom: 3px;
  padding-left: 15px;
  text-indent: -15px;
}

.messagepop p, .messagepop.div {
  border-bottom: 1px solid #EFEFEF;
  margin: 8px 0;
  padding-bottom: 8px;
}

And the JavaScript:

function deselect(e) {
  $('.pop').slideFadeToggle(function() {
    e.removeClass('selected');
  });    
}

$(function() {
  $('#contact').on('click', function() {
    if($(this).hasClass('selected')) {
      deselect($(this));               
    } else {
      $(this).addClass('selected');
      $('.pop').slideFadeToggle();
    }
    return false;
  });

  $('.close').on('click', function() {
    deselect($('#contact'));
    return false;
  });
});

$.fn.slideFadeToggle = function(easing, callback) {
  return this.animate({ opacity: 'toggle', height: 'toggle' }, 'fast', easing, callback);
};

And finally the html:

<div class="messagepop pop">
  <form method="post" id="new_message" action="/messages">
    <p><label for="email">Your email or name</label><input type="text" size="30" name="email" id="email" /></p>
    <p><label for="body">Message</label><textarea rows="6" name="body" id="body" cols="35"></textarea></p>
    <p><input type="submit" value="Send Message" name="commit" id="message_submit"/> or <a class="close" href="/">Cancel</a></p>
  </form>
</div>

<a href="/contact" id="contact">Contact Us</a>

Here is a jsfiddle demo and implementation.

Depending on the situation you may want to load the popup content via an ajax call. It's best to avoid this if possible as it may give the user a more significant delay before seeing the content. Here couple changes that you'll want to make if you take this approach.

HTML becomes:

<div>
    <div class="messagepop pop"></div> 
    <a href="/contact" id="contact">Contact Us</a>
</div>

And the general idea of the JavaScript becomes:

$("#contact").on('click', function() {
    if($(this).hasClass("selected")) {
        deselect();               
    } else {
        $(this).addClass("selected");
        $.get(this.href, function(data) {
            $(".pop").html(data).slideFadeToggle(function() { 
                $("input[type=text]:first").focus();
            });
        }
    }
    return false;
});

Appending a line break to an output file in a shell script

this also works, and prolly is more readable than the echo version:

printf "`date` User `whoami` started the script.\r\n" >> output.log

Linux command to list all available commands and aliases

Try this script:

#!/bin/bash
echo $PATH  | tr : '\n' | 
while read e; do 
    for i in $e/*; do
        if [[ -x "$i" && -f "$i" ]]; then     
            echo $i
        fi
    done
done

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

That's all fine and good -- but what if you want to select an existing element as the default? In my issue there is no "--select a value--" option.

Here's my code -- you could make it into a one liner if you didn't want to check for no results I suppose...

private void LoadCombo(ComboBox cb, string itemType, string defVal = "")
{
    cb.DisplayMember = "Name";
    cb.ValueMember = "ItemCode";
    cb.DataSource = db.Items.Where(q => q.ItemTypeId == itemType).ToList();

    if (!string.IsNullOrEmpty(defVal))
    {
        var i = ((List<GCC_Pricing.Models.Item>)cb.DataSource).FindIndex(q => q.ItemCode == defVal);
        if (i>=0) cb.SelectedIndex = i;
    }
}

String comparison in bash. [[: not found

I had this problem when installing Heroku Toolbelt

This is how I solved the problem

$ ls -l /bin/sh
lrwxrwxrwx 1 root root 4 ago 15  2012 /bin/sh -> dash

As you can see, /bin/sh is a link to "dash" (not bash), and [[ is bash syntactic sugarness. So I just replaced the link to /bin/bash. Careful using rm like this in your system!

$ sudo rm /bin/sh
$ sudo ln -s /bin/bash /bin/sh

Rails formatting date

Create an initializer for it:

# config/initializers/time_formats.rb

Add something like this to it:

Time::DATE_FORMATS[:custom_datetime] = "%d.%m.%Y"

And then use it the following way:

post.updated_at.to_s(:custom_datetime)

?? Your have to restart rails server for this to work.

Check the documentation for more information: http://api.rubyonrails.org/v5.1/classes/DateTime.html#method-i-to_formatted_s

Sql server - log is full due to ACTIVE_TRANSACTION

Restarting the SQL Server will clear up the log space used by your database. If this however is not an option, you can try the following:

* Issue a CHECKPOINT command to free up log space in the log file.

* Check the available log space with DBCC SQLPERF('logspace'). If only a small 
  percentage of your log file is actually been used, you can try a DBCC SHRINKFILE 
  command. This can however possibly introduce corruption in your database. 

* If you have another drive with space available you can try to add a file there in 
  order to get enough space to attempt to resolve the issue.

Hope this will help you in finding your solution.

Exit Shell Script Based on Process Exit Code

In Bash this is easy. Just tie them together with &&:

command1 && command2 && command3

You can also use the nested if construct:

if command1
   then
       if command2
           then
               do_something
           else
               exit
       fi
   else
       exit
fi

How do I convert date/time from 24-hour format to 12-hour AM/PM?

Use smaller h

// 24 hrs 
H:i 
// output 14:20

// 12 hrs 
h:i 
// output 2:20

Writing a Python list of lists to a csv file

Make sure to indicate lineterinator='\n' when create the writer; otherwise, an extra empty line might be written into file after each data line when data sources are from other csv file...

Here is my solution:

with open('csvfile', 'a') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter='    ',quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
for i in range(0, len(data)):
    spamwriter.writerow(data[i])

Remove columns from dataframe where ALL values are NA

From my experience of having trouble applying previous answers, I have found that I needed to modify their approach in order to achieve what the question here is:

How to get rid of columns where for ALL rows the value is NA?

First note that my solution will only work if you do not have duplicate columns (that issue is dealt with here (on stack overflow)

Second, it uses dplyr.

Instead of

df <- df %>% select_if(~all(!is.na(.)))

I find that what works is

df <- df %>% select_if(~!all(is.na(.)))

The point is that the "not" symbol "!" needs to be on the outside of the universal quantifier. I.e. the select_if operator acts on columns. In this case, it selects only those that do not satisfy the criterion

every element is equal to "NA"

Is it possible to sort a ES6 map object?

Convert Map to an array using Array.from, sort array, convert back to Map, e.g.

new Map(
  Array
    .from(eventsByDate)
    .sort((a, b) => {
      // a[0], b[0] is the key of the map
      return a[0] - b[0];
    })
)

Builder Pattern in Effective Java

You should make the Builder class as static and also you should make the fields final and have getters to get those values. Don't provide setters to those values. In this way your class will be perfectly immutable.

public class NutritionalFacts {
    private final int sodium;
    private final int fat;
    private final int carbo;

    public int getSodium(){
        return sodium;
    }

    public int getFat(){
        return fat;
    }

    public int getCarbo(){
        return carbo;
    }

    public static class Builder {
        private int sodium;
        private int fat;
        private int carbo;

        public Builder sodium(int s) {
            this.sodium = s;
            return this;
        }

        public Builder fat(int f) {
            this.fat = f;
            return this;
        }

        public Builder carbo(int c) {
            this.carbo = c;
            return this;
        }

        public NutritionalFacts build() {
            return new NutritionalFacts(this);
        }
    }

    private NutritionalFacts(Builder b) {
        this.sodium = b.sodium;
        this.fat = b.fat;
        this.carbo = b.carbo;
    }
}

And now you can set the properties as follows:

NutritionalFacts n = new NutritionalFacts.Builder().sodium(10).carbo(15).
fat(5).build();

How to export iTerm2 Profiles

If you have a look at Preferences -> General you will notice at the bottom of the panel, there is a setting Load preferences from a custom folder or URL:. There is a button next to it Save settings to Folder.

So all you need to do is save your settings first and load it after you reinstalled your OS.

If the Save settings to Folder is disabled, select a folder (e.g. empty) in the Load preferences from a custom folder or URL: text box.

In iTerm2 3.3 on OSX the sequence is: iTerm2 menu, Preferences, General tab, Preferences subtab

Get current URL with jQuery?

The following are examples of useful code snippets that can be used – some of the examples use standard JavaScript functions and are not specific to jQuery:

See 8 Useful jQuery Snippets For URL’s & Querystrings.

What is the time complexity of indexing, inserting and removing from common data structures?

I guess I will start you off with the time complexity of a linked list:

Indexing---->O(n)
Inserting / Deleting at end---->O(1) or O(n)
Inserting / Deleting in middle--->O(1) with iterator O(n) with out

The time complexity for the Inserting at the end depends if you have the location of the last node, if you do, it would be O(1) other wise you will have to search through the linked list and the time complexity would jump to O(n).

Check if date is in the past Javascript

_x000D_
_x000D_
$('#datepicker').datepicker().change(evt => {_x000D_
  var selectedDate = $('#datepicker').datepicker('getDate');_x000D_
  var now = new Date();_x000D_
  now.setHours(0,0,0,0);_x000D_
  if (selectedDate < now) {_x000D_
    console.log("Selected date is in the past");_x000D_
  } else {_x000D_
    console.log("Selected date is NOT in the past");_x000D_
  }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>_x000D_
<input type="text" id="datepicker" name="event_date" class="datepicker">
_x000D_
_x000D_
_x000D_

How do I deal with certificates using cURL while trying to access an HTTPS url?

For PHP code running on XAMPP on Windows I found I needed to edit php.ini to include the below

[curl]
; A default value for the CURLOPT_CAINFO option. This is required to be an
; absolute path.
curl.cainfo = curl-ca-bundle.crt

and then copy to a file https://curl.haxx.se/ca/cacert.pem and rename to curl-ca-bundle.crt and place it under \xampp path (I couldn't get curl.capath to work). I also found the CAbundle on the cURL site wasn't enough for the remote site I was connecting to, so used one that is listed with a pre-compiled Windows version of curl 7.47.1 at http://winampplugins.co.uk/curl/

The meaning of NoInitialContextException error

I solved the same problem by adding the following Jar libraries to my project:

  • appserv-rt.jar
  • javaee.jar

from the folder : C:\Program Files\glassfish-4.0\glassfish\lib

The links to these libraries were broken and Netbeans didn't found the right classes to use.

onClick function of an input type="button" not working

you could also try creating a button, this will work if you put it outside of the form;

<button onClick="moreFields(); return false;">Give me more fields!</button>

How do I resolve "Run-time error '429': ActiveX component can't create object"?

The file msrdo20.dll is missing from the installation.

According to the Support Statement for Visual Basic 6.0 on Windows Vista, Windows Server 2008 and Windows 7 this file should be distributed with the application.

I'm not sure why it isn't, but my solution is to place the file somewhere on the machine, and register it using regsvr32 in the command line, eg:

regsvr32 c:\windows\system32\msrdo20.dll

In an ideal world you would package this up with the redistributable.

How to create table using select query in SQL Server?

select <column list> into <dest. table> from <source table>;

You could do this way.

SELECT windows_release, windows_service_pack_level, 
       windows_sku, os_language_version
into   new_table_name
FROM   sys.dm_os_windows_info OPTION (RECOMPILE);

indexOf and lastIndexOf in PHP?

<?php
// sample array
$fruits3 = [
    "iron",
    1,
    "ascorbic",
    "potassium",
    "ascorbic",
    2,
    "2",
    "1",
];

// Let's say we are looking for the item "ascorbic", in the above array

//a PHP function matching indexOf() from JS
echo(array_search("ascorbic", $fruits3, true)); //returns "2"

// a PHP function matching lastIndexOf() from JS world
function lastIndexOf($needle, $arr)
{
    return array_search($needle, array_reverse($arr, true), true);
}

echo(lastIndexOf("ascorbic", $fruits3)); //returns "4"

// so these (above) are the two ways to run a function similar to indexOf and lastIndexOf()

What does ^M character mean in Vim?

Unix uses 0xA for a newline character. Windows uses a combination of two characters: 0xD 0xA. 0xD is the carriage return character. ^M happens to be the way vim displays 0xD (0x0D = 13, M is the 13th letter in the English alphabet).

You can remove all the ^M characters by running the following:

:%s/^M//g

Where ^M is entered by holding down Ctrl and typing v followed by m, and then releasing Ctrl. This is sometimes abbreviated as ^V^M, but note that you must enter it as described in the previous sentence, rather than typing it out literally.

This expression will replace all occurrences of ^M with the empty string (i.e. nothing). I use this to get rid of ^M in files copied from Windows to Unix (Solaris, Linux, OSX).

How to use jQuery in AngularJS

You have to do binding in a directive. Look at this:

angular.module('ng', []).
directive('sliderRange', function($parse, $timeout){
    return {
        restrict: 'A',
        replace: true,
        transclude: false,
        compile: function(element, attrs) {            
            var html = '<div class="slider-range"></div>';
            var slider = $(html);
            element.replaceWith(slider);
            var getterLeft = $parse(attrs.ngModelLeft), setterLeft = getterLeft.assign;
            var getterRight = $parse(attrs.ngModelRight), setterRight = getterRight.assign;

            return function (scope, slider, attrs, controller) {
                var vsLeft = getterLeft(scope), vsRight = getterRight(scope), f = vsLeft || 0, t = vsRight || 10;                        

                var processChange = function() {
                    var vs = slider.slider("values"), f = vs[0], t = vs[1];                                        
                    setterLeft(scope, f);
                    setterRight(scope, t);                    
                }                 
                slider.slider({
                    range: true,
                    min: 0,
                    max: 10,
                    step: 1,
                    change: function() { setTimeout(function () { scope.$apply(processChange); }, 1) }
                }).slider("values", [f, t]);                    
            };            
        }
    };
});

This shows you an example of a slider range, done with jQuery UI. Example usage:

<div slider-range ng-model-left="question.properties.range_from" ng-model-right="question.properties.range_to"></div>

How do I connect to my existing Git repository using Visual Studio Code?

  1. Open Vs Code
  2. Go to view
  3. Click on terminal to open a terminal in VS Code
  4. Copy the link for your existing repository from your GitHub page.
  5. Type “git clone” and paste the link in addition i.e “git clone https://github.com/...”
  6. This will open the repository in your Vs Code Editor.

Most common C# bitwise operations on enums

To test a bit you would do the following: (assuming flags is a 32 bit number)

Test Bit:

if((flags & 0x08) == 0x08)
(If bit 4 is set then its true) Toggle Back (1 - 0 or 0 - 1):
flags = flags ^ 0x08;
Reset Bit 4 to Zero:
flags = flags & 0xFFFFFF7F;

Mocking Extension Methods with Moq

I found that I had to discover the inside of the extension method I was trying to mock the input for, and mock what was going on inside the extension.

I viewed using an extension as adding code directly to your method. This meant I needed to mock what happens inside the extension rather than the extension itself.

open cv error: (-215) scn == 3 || scn == 4 in function cvtColor

Well I am having the same problem, but I am not taking input images instead getting video frames and the above solution did not work for that. The problem is in camera accessing, the camera of your laptop is still in use by your previous code, you need to simply RESTART you KERNEL and it will work.

How do I find out my root MySQL password?

Hmm Mysql 5.7.13 to reset all I did was:

$ sudo service mysql stop To stop mysql

$ mysqld_safe --skip-grant-tables & Start mysql

$ mysql -u root

Just like the correct answer. Then all I did was do what @eebbesen did.

mysql> SET PASSWORD FOR root@'localhost' = PASSWORD('NEW-password-HERE');

Hope it helps anyone out there :)

WITH (NOLOCK) vs SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

  • NOLOCK is local to the table (or views etc)
  • READ UNCOMMITTED is per session/connection

As for guidelines... a random search from StackOverflow and the electric interweb...

Force browser to download image files on click

Leeroy & Richard Parnaby-King:

UPDATE: As of spring 2018 this is no longer possible for cross-origin hrefs. So if you want to create on a domain other than imgur.com it will not work as intended. Chrome deprecations and removals announcement

function forceDownload(url, fileName){
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.responseType = "blob";
    xhr.onload = function(){
        var urlCreator = window.URL || window.webkitURL;
        var imageUrl = urlCreator.createObjectURL(this.response);
        var tag = document.createElement('a');
        tag.href = imageUrl;
        tag.download = fileName;
        document.body.appendChild(tag);
        tag.click();
        document.body.removeChild(tag);
    }
    xhr.send();
}

load jquery after the page is fully loaded

Include your scripts at the bottom of the page before closing body tag.

More info HERE.

What is a constant reference? (not a reference to a constant)

The statement icr=y; does not make the reference refer to y; it assigns the value of y to the variable that icr refers to, i.

References are inherently const, that is you can't change what they refer to. There are 'const references' which are really 'references to const', that is you can't change the value of the object they refer to. They are declared const int& or int const& rather than int& const though.

Set a button group's width to 100% and make buttons equal width?

Bootstrap 4 removed .btn-group-justified. As a replacement you can use <div class="btn-group d-flex" role="group"></div> as a wrapper around elements with .w-100.

Try this:

<div class="btn-group d-flex" role="group>
  <button type="button" class="btn btn-primary w-100">Submit</button>
  <button type="button" class="btn btn-primary w-100">Cancel</button>
</div>

What does @@variable mean in Ruby?

A variable prefixed with @ is an instance variable, while one prefixed with @@ is a class variable. Check out the following example; its output is in the comments at the end of the puts lines:

class Test
  @@shared = 1

  def value
    @@shared
  end

  def value=(value)
    @@shared = value
  end
end

class AnotherTest < Test; end

t = Test.new
puts "t.value is #{t.value}" # 1
t.value = 2
puts "t.value is #{t.value}" # 2

x = Test.new
puts "x.value is #{x.value}" # 2

a = AnotherTest.new
puts "a.value is #{a.value}" # 2
a.value = 3
puts "a.value is #{a.value}" # 3
puts "t.value is #{t.value}" # 3
puts "x.value is #{x.value}" # 3

You can see that @@shared is shared between the classes; setting the value in an instance of one changes the value for all other instances of that class and even child classes, where a variable named @shared, with one @, would not be.

[Update]

As Phrogz mentions in the comments, it's a common idiom in Ruby to track class-level data with an instance variable on the class itself. This can be a tricky subject to wrap your mind around, and there is plenty of additional reading on the subject, but think about it as modifying the Class class, but only the instance of the Class class you're working with. An example:

class Polygon
  class << self
    attr_accessor :sides
  end
end

class Triangle < Polygon
  @sides = 3
end

class Rectangle < Polygon
  @sides = 4
end

class Square < Rectangle
end

class Hexagon < Polygon
  @sides = 6
end

puts "Triangle.sides:  #{Triangle.sides.inspect}"  # 3
puts "Rectangle.sides: #{Rectangle.sides.inspect}" # 4
puts "Square.sides:    #{Square.sides.inspect}"    # nil
puts "Hexagon.sides:   #{Hexagon.sides.inspect}"   # 6

I included the Square example (which outputs nil) to demonstrate that this may not behave 100% as you expect; the article I linked above has plenty of additional information on the subject.

Also keep in mind that, as with most data, you should be extremely careful with class variables in a multithreaded environment, as per dmarkow's comment.

How do I increment a DOS variable in a FOR /F loop?

I would like to add that in case in you create local variables within the loop, they need to be expanded using the bang(!) notation as well. Extending the example at https://stackoverflow.com/a/2919699 above, if we want to create counter-based output filenames

set TEXT_T="myfile.txt"

set /a c=1

setlocal ENABLEDELAYEDEXPANSION

FOR /F "tokens=1 usebackq" %%i in (%TEXT_T%) do (
    set /a c=c+1
    set OUTPUT_FILE_NAME=output_!c!.txt
    echo Output file is !OUTPUT_FILE_NAME!
    echo %%i, !c!
)

endlocal

Why is the apt-get function not working in the terminal on Mac OS X v10.9 (Mavericks)?

Alternatively You can use the brew or curl command for installing things, wherever apt-get is mentioned with a URL...

For example,

curl -O http://www.magentocommerce.com/downloads/assets/1.8.1.0/magento-1.8.1.0.tar.gz

What exactly is an instance in Java?

basically object and instance are the two words used interchangeably. A class is template for an object and an object is an instance of a class.

How do I write a bash script to restart a process if it dies?

I'm not sure how portable it is across operating systems, but you might check if your system contains the 'run-one' command, i.e. "man run-one". Specifically, this set of commands includes 'run-one-constantly', which seems to be exactly what is needed.

From man page:

run-one-constantly COMMAND [ARGS]

Note: obviously this could be called from within your script, but also it removes the need for having a script at all.

How to browse for a file in java swing library?

The following example creates a file chooser and displays it as first an open-file dialog and then as a save-file dialog:

String filename = File.separator+"tmp";
JFileChooser fc = new JFileChooser(new File(filename));

// Show open dialog; this method does not return until the dialog is closed
fc.showOpenDialog(frame);
File selFile = fc.getSelectedFile();

// Show save dialog; this method does not return until the dialog is closed
fc.showSaveDialog(frame);
selFile = fc.getSelectedFile();

Here is a more elaborate example that creates two buttons that create and show file chooser dialogs.

// This action creates and shows a modal open-file dialog.
public class OpenFileAction extends AbstractAction {
    JFrame frame;
    JFileChooser chooser;

    OpenFileAction(JFrame frame, JFileChooser chooser) {
        super("Open...");
        this.chooser = chooser;
        this.frame = frame;
    }

    public void actionPerformed(ActionEvent evt) {
        // Show dialog; this method does not return until dialog is closed
        chooser.showOpenDialog(frame);

        // Get the selected file
        File file = chooser.getSelectedFile();
    }
};

// This action creates and shows a modal save-file dialog.
public class SaveFileAction extends AbstractAction {
    JFileChooser chooser;
    JFrame frame;

    SaveFileAction(JFrame frame, JFileChooser chooser) {
        super("Save As...");
        this.chooser = chooser;
        this.frame = frame;
    }

    public void actionPerformed(ActionEvent evt) {
        // Show dialog; this method does not return until dialog is closed
        chooser.showSaveDialog(frame);

        // Get the selected file
        File file = chooser.getSelectedFile();
    }
};

How to fix "unable to write 'random state' " in openssl

It may also be that you need to run the console as an administrator. On windows 7, hold ctrl+shift when you launch the console window.

How to use cookies in Python Requests

From the documentation:

  1. get cookie from response

    url = 'http://example.com/some/cookie/setting/url'
    r = requests.get(url)
    r.cookies
    

    {'example_cookie_name': 'example_cookie_value'}

  2. give cookie back to server on subsequent request

    url = 'http://httpbin.org/cookies'
    cookies = dict(cookies_are='working')
    r = requests.get(url, cookies=cookies)`
    

What is the difference between <p> and <div>?

All good answers, but there's one difference I haven't seen mentioned yet, and that's how browsers render them by default. The major web browsers will render a <p> tag with margin above and below the paragraph. A <div> tag will be rendered without any margin at all.

Simplest way to serve static data from outside the application server in a Java web application

You can do it by putting your images on a fixed path (for example: /var/images, or c:\images), add a setting in your application settings (represented in my example by the Settings.class), and load them like that, in a HttpServlet of yours:

String filename = Settings.getValue("images.path") + request.getParameter("imageName")
FileInputStream fis = new FileInputStream(filename);

int b = 0;
while ((b = fis.read()) != -1) {
        response.getOutputStream().write(b);
}

Or if you want to manipulate the image:

String filename = Settings.getValue("images.path") + request.getParameter("imageName")
File imageFile = new File(filename);
BufferedImage image = ImageIO.read(imageFile);
ImageIO.write(image, "image/png", response.getOutputStream());

then the html code would be <img src="imageServlet?imageName=myimage.png" />

Of course you should think of serving different content types - "image/jpeg", for example based on the file extension. Also you should provide some caching.

In addition you could use this servlet for quality rescaling of your images, by providing width and height parameters as arguments, and using image.getScaledInstance(w, h, Image.SCALE_SMOOTH), considering performance, of course.

'System.Net.Http.HttpContent' does not contain a definition for 'ReadAsAsync' and no extension method

or if you have VS 2012 you can goto the package manager console and type Install-Package Microsoft.AspNet.WebApi.Client

This would download the latest version of the package

How to get all the AD groups for a particular user?

The following example is from the Code Project article, (Almost) Everything In Active Directory via C#:

// userDn is a Distinguished Name such as:
// "LDAP://CN=Joe Smith,OU=Sales,OU=domain,OU=com"
public ArrayList Groups(string userDn, bool recursive)
{
    ArrayList groupMemberships = new ArrayList();
    return AttributeValuesMultiString("memberOf", userDn,
        groupMemberships, recursive);
}

public ArrayList AttributeValuesMultiString(string attributeName,
     string objectDn, ArrayList valuesCollection, bool recursive)
{
    DirectoryEntry ent = new DirectoryEntry(objectDn);
    PropertyValueCollection ValueCollection = ent.Properties[attributeName];
    IEnumerator en = ValueCollection.GetEnumerator();

    while (en.MoveNext())
    {
        if (en.Current != null)
        {
            if (!valuesCollection.Contains(en.Current.ToString()))
            {
                valuesCollection.Add(en.Current.ToString());
                if (recursive)
                {
                    AttributeValuesMultiString(attributeName, "LDAP://" +
                    en.Current.ToString(), valuesCollection, true);
                }
            }
        }
    }
    ent.Close();
    ent.Dispose();
    return valuesCollection;
}

Just call the Groups method with the Distinguished Name for the user, and pass in the bool flag to indicate if you want to include nested / child groups memberships in your resulting ArrayList:

ArrayList groups = Groups("LDAP://CN=Joe Smith,OU=Sales,OU=domain,OU=com", true);
foreach (string groupName in groups)
{
    Console.WriteLine(groupName);
}

If you need to do any serious level of Active Directory programming in .NET I highly recommend bookmarking & reviewing the Code Project article I mentioned above.

Execute CMD command from code

Argh :D not the fastest

Process.Start("notepad C:\test.txt");

Implementing two interfaces in a class with same method. Which interface method is overridden?

This was marked as a duplicate to this question https://stackoverflow.com/questions/24401064/understanding-and-solving-the-diamond-problems-in-java

You need Java 8 to get a multiple inheritance problem, but it is still not a diamon problem as such.

interface A {
    default void hi() { System.out.println("A"); }
}

interface B {
    default void hi() { System.out.println("B"); }
}

class AB implements A, B { // won't compile
}

new AB().hi(); // won't compile.

As JB Nizet comments you can fix this my overriding.

class AB implements A, B {
    public void hi() { A.super.hi(); }
}

However, you don't have a problem with

interface D extends A { }

interface E extends A { }

interface F extends A {
    default void hi() { System.out.println("F"); }
}

class DE implement D, E { }

new DE().hi(); // prints A

class DEF implement D, E, F { }

new DEF().hi(); // prints F as it is closer in the heirarchy than A.

how to use html2canvas and jspdf to export to pdf in a proper and simple way

This one shows how to print only selected element on the page with dpi/resolution adjustments

HTML:

<html>

  <body>
    <header>This is the header</header>
    <div id="content">
      This is the element you only want to capture
    </div>
    <button id="print">Download Pdf</button>
    <footer>This is the footer</footer>
  </body>

</html>

CSS:

body {
  background: beige;
}

header {
  background: red;
}

footer {
  background: blue;
}

#content {
  background: yellow;
  width: 70%;
  height: 100px;
  margin: 50px auto;
  border: 1px solid orange;
  padding: 20px;
}

JS:

$('#print').click(function() {

  var w = document.getElementById("content").offsetWidth;
  var h = document.getElementById("content").offsetHeight;
  html2canvas(document.getElementById("content"), {
    dpi: 300, // Set to 300 DPI
    scale: 3, // Adjusts your resolution
    onrendered: function(canvas) {
      var img = canvas.toDataURL("image/jpeg", 1);
      var doc = new jsPDF('L', 'px', [w, h]);
      doc.addImage(img, 'JPEG', 0, 0, w, h);
      doc.save('sample-file.pdf');
    }
  });
});

jsfiddle: https://jsfiddle.net/marksalvania/dum8bfco/

Add CSS class to a div in code behind

What if:

 <asp:Button ID="Button1" runat="server" CssClass="test1 test3 test-test" />

To add or remove a class, instead of overwriting all classes with

   BtnventCss.CssClass = "hom_but_a"

keep the HTML correct:

    string classname = "TestClass";

    // Add a class
    BtnventCss.CssClass = String.Join(" ", Button1
               .CssClass
               .Split(' ')
               .Except(new string[]{"",classname})
               .Concat(new string[]{classname})
               .ToArray()
       );

     // Remove a class
     BtnventCss.CssClass = String.Join(" ", Button1
               .CssClass
               .Split(' ')
               .Except(new string[]{"",classname})
               .ToArray()
       );

This assures

  • The original classnames remain.
  • There are no double classnames
  • There are no disturbing extra spaces

Especially when client-side development is using several classnames on one element.

In your example, use

   string classname = "TestClass";

    // Add a class
    Button1.Attributes.Add("class", String.Join(" ", Button1
               .Attributes["class"]
               .Split(' ')
               .Except(new string[]{"",classname})
               .Concat(new string[]{classname})
               .ToArray()
       ));

     // Remove a class
     Button1.Attributes.Add("class", String.Join(" ", Button1
               .Attributes["class"]
               .Split(' ')
               .Except(new string[]{"",classname})
               .ToArray()
       ));

You should wrap this in a method/property ;)

scrollable div inside container

The simplest way is as this example:

<div>
   <div style=' height:300px;'>
     SOME LOGO OR CONTENT HERE
   </div>
   <div style='overflow-x: hidden;overflow-y: scroll;'> 
      THIS IS SOME TEXT
   </DIV>

You can see the test cases on: https://www.w3schools.com/css/css_overflow.asp

Use cases for the 'setdefault' dict method

As Muhammad said, there are situations in which you only sometimes wish to set a default value. A great example of this is a data structure which is first populated, then queried.

Consider a trie. When adding a word, if a subnode is needed but not present, it must be created to extend the trie. When querying for the presence of a word, a missing subnode indicates that the word is not present and it should not be created.

A defaultdict cannot do this. Instead, a regular dict with the get and setdefault methods must be used.

JavaScript and Threads

With HTML5 specification you do not need to write too much JS for the same or find some hacks.

One of the feature introduced in HTML5 is Web Workers which is JavaScript running in the background,independently of other scripts, without affecting the performance of the page.

It is supported in almost all browsers :

Chrome - 4.0+

IE - 10.0+

Mozilla - 3.5+

Safari - 4.0+

Opera - 11.5+

Return file in ASP.Net Core Web API

If this is ASP.net-Core then you are mixing web API versions. Have the action return a derived IActionResult because in your current code the framework is treating HttpResponseMessage as a model.

[Route("api/[controller]")]
public class DownloadController : Controller {
    //GET api/download/12345abc
    [HttpGet("{id}"]
    public async Task<IActionResult> Download(string id) {
        Stream stream = await {{__get_stream_based_on_id_here__}}

        if(stream == null)
            return NotFound(); // returns a NotFoundResult with Status404NotFound response.

        return File(stream, "application/octet-stream"); // returns a FileStreamResult
    }    
}

Updating a dataframe column in spark

importing col, when from pyspark.sql.functions and updating fifth column to integer(0,1,2) based on the string(string a, string b, string c) into a new DataFrame.

from pyspark.sql.functions import col, when 

data_frame_temp = data_frame.withColumn("col_5",when(col("col_5") == "string a", 0).when(col("col_5") == "string b", 1).otherwise(2))

How do I check form validity with angularjs?

When you put <form> tag inside you ngApp, AngularJS automatically adds form controller (actually there is a directive, called form that add nessesary behaviour). The value of the name attribute will be bound in your scope; so something like <form name="yourformname">...</form> will satisfy:

A form is an instance of FormController. The form instance can optionally be published into the scope using the name attribute.

So to check form validity, you can check value of $scope.yourformname.$valid property of scope.

More information you can get at Developer's Guide section about forms.

Why is Visual Studio 2010 not able to find/open PDB files?

I had the same problem. Debugging does not work with the stuff that comes with the OpenCV executable. you have to build your own binarys.
Then enable Microsoft Symbol Servers in Debug->options and settings->debug->symbols

link_to method and click event in Rails

You can use link_to_function (removed in Rails 4.1):

link_to_function 'My link with obtrusive JavaScript', 'alert("Oh no!")'

Or, if you absolutely need to use link_to:

link_to 'Another link with obtrusive JavaScript', '#',
        :onclick => 'alert("Please no!")'

However, putting JavaScript right into your generated HTML is obtrusive, and is bad practice.

Instead, your Rails code should simply be something like this:

link_to 'Link with unobtrusive JavaScript',
        '/actual/url/in/case/javascript/is/broken',
        :id => 'my-link'

And assuming you're using the Prototype JS framework, JS like this in your application.js:

$('my-link').observe('click', function (event) {
  alert('Hooray!');
  event.stop(); // Prevent link from following through to its given href
});

Or if you're using jQuery:

$('#my-link').click(function (event) {
  alert('Hooray!');
  event.preventDefault(); // Prevent link from following its href
});

By using this third technique, you guarantee that the link will follow through to some other page—not just fail silently—if JavaScript is unavailable for the user. Remember, JS could be unavailable because the user has a poor internet connection (e.g., mobile device, public wifi), the user or user's sysadmin disabled it, or an unexpected JS error occurred (i.e., developer error).

XPath: difference between dot and text()

There is big difference between dot (".") and text() :-

  • The dot (".") in XPath is called the "context item expression" because it refers to the context item. This could be match with a node (such as an element, attribute, or text node) or an atomic value (such as a string, number, or boolean). While text() refers to match only element text which is in string form.

  • The dot (".") notation is the current node in the DOM. This is going to be an object of type Node while Using the XPath function text() to get the text for an element only gets the text up to the first inner element. If the text you are looking for is after the inner element you must use the current node to search for the string and not the XPath text() function.

For an example :-

<a href="something.html">
  <img src="filename.gif">
  link
</a>

Here if you want to find anchor a element by using text link, you need to use dot ("."). Because if you use //a[contains(.,'link')] it finds the anchor a element but if you use //a[contains(text(),'link')] the text() function does not seem to find it.

Hope it will help you..:)

center MessageBox in parent form

But why stop with MessageBox-specific implementation? Use the class below like this:

    private void OnFormClosing(object sender, FormClosingEventArgs e)
    {
        DialogResult dg;
        using (DialogCenteringService centeringService = new DialogCenteringService(this)) // center message box
        {
            dg = MessageBox.Show(this, "Are you sure?", "Confirm exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        }

        if (dg == DialogResult.No)
        {
            e.Cancel = true;
        }
    }

The code that you can use with anything that shows dialog windows, even if they're owned by another thread (our app has multiple UI threads):

(Here is the updated code which takes monitor working areas into account, so that the dialog isn't centered between two monitors or is partly off-screen. With it you'll need enum SetWindowPosFlags, which is below)

public class DialogCenteringService : IDisposable
{
    private readonly IWin32Window owner;
    private readonly HookProc hookProc;
    private readonly IntPtr hHook = IntPtr.Zero;

    public DialogCenteringService(IWin32Window owner)
    {
        if (owner == null) throw new ArgumentNullException("owner");

        this.owner = owner;
        hookProc = DialogHookProc;

        hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, hookProc, IntPtr.Zero, GetCurrentThreadId());
    }

    private IntPtr DialogHookProc(int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode < 0)
        {
            return CallNextHookEx(hHook, nCode, wParam, lParam);
        }

        CWPRETSTRUCT msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT));
        IntPtr hook = hHook;

        if (msg.message == (int)CbtHookAction.HCBT_ACTIVATE)
        {
            try
            {
                CenterWindow(msg.hwnd);
            }
            finally
            {
                UnhookWindowsHookEx(hHook);
            }
        }

        return CallNextHookEx(hook, nCode, wParam, lParam);
    }

    public void Dispose()
    {
        UnhookWindowsHookEx(hHook);
    }

    private void CenterWindow(IntPtr hChildWnd)
    {
        Rectangle recChild = new Rectangle(0, 0, 0, 0);
        bool success = GetWindowRect(hChildWnd, ref recChild);

        if (!success)
        {
            return;
        }

        int width = recChild.Width - recChild.X;
        int height = recChild.Height - recChild.Y;

        Rectangle recParent = new Rectangle(0, 0, 0, 0);
        success = GetWindowRect(owner.Handle, ref recParent);

        if (!success)
        {
            return;
        }

        Point ptCenter = new Point(0, 0);
        ptCenter.X = recParent.X + ((recParent.Width - recParent.X) / 2);
        ptCenter.Y = recParent.Y + ((recParent.Height - recParent.Y) / 2);


        Point ptStart = new Point(0, 0);
        ptStart.X = (ptCenter.X - (width / 2));
        ptStart.Y = (ptCenter.Y - (height / 2));

        //MoveWindow(hChildWnd, ptStart.X, ptStart.Y, width, height, false);
        Task.Factory.StartNew(() => SetWindowPos(hChildWnd, (IntPtr)0, ptStart.X, ptStart.Y, width, height, SetWindowPosFlags.SWP_ASYNCWINDOWPOS | SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_NOACTIVATE | SetWindowPosFlags.SWP_NOOWNERZORDER | SetWindowPosFlags.SWP_NOZORDER));
    }

    // some p/invoke

    // ReSharper disable InconsistentNaming
    public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);

    public delegate void TimerProc(IntPtr hWnd, uint uMsg, UIntPtr nIDEvent, uint dwTime);

    private const int WH_CALLWNDPROCRET = 12;

    // ReSharper disable EnumUnderlyingTypeIsInt
    private enum CbtHookAction : int
    // ReSharper restore EnumUnderlyingTypeIsInt
    {
        // ReSharper disable UnusedMember.Local
        HCBT_MOVESIZE = 0,
        HCBT_MINMAX = 1,
        HCBT_QS = 2,
        HCBT_CREATEWND = 3,
        HCBT_DESTROYWND = 4,
        HCBT_ACTIVATE = 5,
        HCBT_CLICKSKIPPED = 6,
        HCBT_KEYSKIPPED = 7,
        HCBT_SYSCOMMAND = 8,
        HCBT_SETFOCUS = 9
        // ReSharper restore UnusedMember.Local
    }

    [DllImport("kernel32.dll")]
    static extern int GetCurrentThreadId();

    [DllImport("user32.dll")]
    private static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle lpRect);

    [DllImport("user32.dll")]
    private static extern int MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, SetWindowPosFlags uFlags);

    [DllImport("User32.dll")]
    public static extern UIntPtr SetTimer(IntPtr hWnd, UIntPtr nIDEvent, uint uElapse, TimerProc lpTimerFunc);

    [DllImport("User32.dll")]
    public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);

    [DllImport("user32.dll")]
    public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);

    [DllImport("user32.dll")]
    public static extern int UnhookWindowsHookEx(IntPtr idHook);

    [DllImport("user32.dll")]
    public static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam);

    [DllImport("user32.dll")]
    public static extern int GetWindowTextLength(IntPtr hWnd);

    [DllImport("user32.dll")]
    public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength);

    [DllImport("user32.dll")]
    public static extern int EndDialog(IntPtr hDlg, IntPtr nResult);

    [StructLayout(LayoutKind.Sequential)]
    public struct CWPRETSTRUCT
    {
        public IntPtr lResult;
        public IntPtr lParam;
        public IntPtr wParam;
        public uint message;
        public IntPtr hwnd;
    };
    // ReSharper restore InconsistentNaming
}

[Flags]
public enum SetWindowPosFlags : uint
{
    // ReSharper disable InconsistentNaming

    /// <summary>
    ///     If the calling thread and the thread that owns the window are attached to different input queues, the system posts the request to the thread that owns the window. This prevents the calling thread from blocking its execution while other threads process the request.
    /// </summary>
    SWP_ASYNCWINDOWPOS = 0x4000,

    /// <summary>
    ///     Prevents generation of the WM_SYNCPAINT message.
    /// </summary>
    SWP_DEFERERASE = 0x2000,

    /// <summary>
    ///     Draws a frame (defined in the window's class description) around the window.
    /// </summary>
    SWP_DRAWFRAME = 0x0020,

    /// <summary>
    ///     Applies new frame styles set using the SetWindowLong function. Sends a WM_NCCALCSIZE message to the window, even if the window's size is not being changed. If this flag is not specified, WM_NCCALCSIZE is sent only when the window's size is being changed.
    /// </summary>
    SWP_FRAMECHANGED = 0x0020,

    /// <summary>
    ///     Hides the window.
    /// </summary>
    SWP_HIDEWINDOW = 0x0080,

    /// <summary>
    ///     Does not activate the window. If this flag is not set, the window is activated and moved to the top of either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter parameter).
    /// </summary>
    SWP_NOACTIVATE = 0x0010,

    /// <summary>
    ///     Discards the entire contents of the client area. If this flag is not specified, the valid contents of the client area are saved and copied back into the client area after the window is sized or repositioned.
    /// </summary>
    SWP_NOCOPYBITS = 0x0100,

    /// <summary>
    ///     Retains the current position (ignores X and Y parameters).
    /// </summary>
    SWP_NOMOVE = 0x0002,

    /// <summary>
    ///     Does not change the owner window's position in the Z order.
    /// </summary>
    SWP_NOOWNERZORDER = 0x0200,

    /// <summary>
    ///     Does not redraw changes. If this flag is set, no repainting of any kind occurs. This applies to the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent window uncovered as a result of the window being moved. When this flag is set, the application must explicitly invalidate or redraw any parts of the window and parent window that need redrawing.
    /// </summary>
    SWP_NOREDRAW = 0x0008,

    /// <summary>
    ///     Same as the SWP_NOOWNERZORDER flag.
    /// </summary>
    SWP_NOREPOSITION = 0x0200,

    /// <summary>
    ///     Prevents the window from receiving the WM_WINDOWPOSCHANGING message.
    /// </summary>
    SWP_NOSENDCHANGING = 0x0400,

    /// <summary>
    ///     Retains the current size (ignores the cx and cy parameters).
    /// </summary>
    SWP_NOSIZE = 0x0001,

    /// <summary>
    ///     Retains the current Z order (ignores the hWndInsertAfter parameter).
    /// </summary>
    SWP_NOZORDER = 0x0004,

    /// <summary>
    ///     Displays the window.
    /// </summary>
    SWP_SHOWWINDOW = 0x0040,

    // ReSharper restore InconsistentNaming
}

How to check whether a Button is clicked by using JavaScript

All the answers here discuss about onclick method, however you can also use addEventListener().

Syntax of addEventListener()

document.getElementById('button').addEventListener("click",{function defination});

The function defination above is known as anonymous function.

If you don't want to use anonymous functions you can also use function refrence.

function functionName(){
//function defination
}



document.getElementById('button').addEventListener("click",functionName);

You can check the detail differences between onclick() and addEventListener() in this answer here.