Programs & Examples On #Csb

0

Flutter: RenderBox was not laid out

Wrap your ListView in an Expanded widget

 Expanded(child:MyListView())

How to import js-modules into TypeScript file?

I'm currently taking some legacy codebases and introducing minimal TypeScript changes to see if it helps our team. Depending on how strict you want to be with TypeScript, this may or may not be an option for you.

The most helpful way for us to get started was to extend our tsconfig.json file with this property:

// tsconfig.json excerpt:

{
  ...
  "compilerOptions": {
    ...
    "allowJs": true,
    ...
  }
  ...
}

This change lets our JS files that have JSDoc type hints get compiled. Also our IDEs (JetBrains IDEs and VS Code) can provide code-completion and Intellisense.

References:

Move div to new line

What about something like this.

<div id="movie_item">
    <div class="movie_item_poster">
        <img src="..." style="max-width: 100%; max-height: 100%;">
    </div>

     <div id="movie_item_content">
        <div class="movie_item_content_year">year</div>
        <div class="movie_item_content_title">title</div>
        <div class="movie_item_content_plot">plot</div>
    </div>

    <div class="movie_item_toolbar">
        Lorem Ipsum...
    </div>
</div>

You don't have to float both movie_item_poster AND movie_item_content. Just float one of them...

#movie_item {
    position: relative;
    margin-top: 10px;
    height: 175px;
}

.movie_item_poster {
    float: left;
    height: 150px;
    width: 100px;
}

.movie_item_content {
    position: relative;
}

.movie_item_content_title {
}

.movie_item_content_year {
    float: right;
}

.movie_item_content_plot {
}

.movie_item_toolbar {
    clear: both;
    vertical-align: bottom;
    width: 100%;
    height: 25px;
}

Here it is as a JSFiddle.

Error LNK2019: Unresolved External Symbol in Visual Studio

When you have everything #included, an unresolved external symbol is often a missing * or & in the declaration or definition of a function.

How do I get row id of a row in sql server

SQL does not do that. The order of the tuples in the table are not ordered by insertion date. A lot of people include a column that stores that date of insertion in order to get around this issue.

How to convert image into byte array and byte array to base64 String in android?

here is another solution...

System.IO.Stream st = new System.IO.StreamReader (picturePath).BaseStream;
byte[] buffer = new byte[4096];

System.IO.MemoryStream m = new System.IO.MemoryStream ();
while (st.Read (buffer,0,buffer.Length) > 0) {
    m.Write (buffer, 0, buffer.Length);
}  
imgView.Tag = m.ToArray ();
st.Close ();
m.Close ();

hope it helps!

Java - Convert image to Base64

You can use the file Object to get the length of the file to initialize your array:

int length = Long.valueOf(file.length()).intValue();
byte[] byteArray = new byte[length];

Creating a UIImage from a UIColor to use as a background image for UIButton

Xamarin.iOS solution

 public UIImage CreateImageFromColor()
 {
     var imageSize = new CGSize(30, 30);
     var imageSizeRectF = new CGRect(0, 0, 30, 30);
     UIGraphics.BeginImageContextWithOptions(imageSize, false, 0);
     var context = UIGraphics.GetCurrentContext();
     var red = new CGColor(255, 0, 0);
     context.SetFillColor(red);
     context.FillRect(imageSizeRectF);
     var image = UIGraphics.GetImageFromCurrentImageContext();
     UIGraphics.EndImageContext();
     return image;
 }

How to capture UIView to UIImage without loss of quality on retina display

All Swift 3 answers did not worked for me so I have translated the most accepted answer:

extension UIImage {
    class func imageWithView(view: UIView) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0.0)
        view.layer.render(in: UIGraphicsGetCurrentContext()!)
        let img: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img!
    }
}

UIImage resize (Scale proportion)

I used this single line of code to create a new UIImage which is scaled. Set the scale and orientation params to achieve what you want. The first line of code just grabs the image.

    // grab the original image
    UIImage *originalImage = [UIImage imageNamed:@"myImage.png"];
    // scaling set to 2.0 makes the image 1/2 the size. 
    UIImage *scaledImage = 
                [UIImage imageWithCGImage:[originalImage CGImage] 
                              scale:(originalImage.scale * 2.0)
                                 orientation:(originalImage.imageOrientation)];

How to send HTML email using linux command line

I found a really easy solution: add to the mail command the modifier -aContent-Type:text/html.

In your case would be:

mail -aContent-Type:text/html -s "Built notification" [email protected] < /var/www/report.csv

How Do I Take a Screen Shot of a UIView?

-(UIImage *)convertViewToImage
{
    UIGraphicsBeginImageContext(self.bounds.size);
    [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

  return image;
}

how to convert object into string in php

Use the casting operator (string)$yourObject;

Symfony 2 EntityManager injection in service

Your class's constructor method should be called __construct(), not __constructor():

public function __construct(EntityManager $entityManager)
{
    $this->em = $entityManager;
}

openpyxl - adjust column width size

All the above answers are generating an issue which is that col[0].column is returning number while worksheet.column_dimensions[column] accepts only character such as 'A', 'B', 'C' in place of column. I've modified @Virako's code and it is working fine now.

import re
import openpyxl
..
for col in _ws.columns:
    max_lenght = 0
    print(col[0])
    col_name = re.findall('\w\d', str(col[0]))
    col_name = col_name[0]
    col_name = re.findall('\w', str(col_name))[0]
    print(col_name)
    for cell in col:
        try:
            if len(str(cell.value)) > max_lenght:
                max_lenght = len(cell.value)
        except:
            pass
    adjusted_width = (max_lenght+2)
    _ws.column_dimensions[col_name].width = adjusted_width

Xcode Product -> Archive disabled

If you are sure that you selected the Generic iOS device and still can't see the option, then you simply have to restart Xcode.

This was the missing solution for me as a cordova developer with Xcode 11.2

How can I represent a range in Java?

If you are checking against a lot of intervals, I suggest using an interval tree.

Remove empty array elements

foreach($linksArray as $key => $link) 
{ 
    if($link === '') 
    { 
        unset($linksArray[$key]); 
    } 
} 
print_r($linksArray); 

Can I find events bound on an element with jQuery?

While this isn't exactly specific to jQuery selectors/objects, in FireFox Quantum 58.x, you can find event handlers on an element using the Dev tools:

  1. Right-click the element
  2. In the context menu, Click 'Inspect Element'
  3. If there is an 'ev' icon next to the element (yellow box), click on 'ev' icon
  4. Displays all events for that element and event handler

FF Quantum Dev Tools

How to include clean target in Makefile?

By the way it is written, clean rule is invoked only if it is explicitly called:

make clean

I think it is better, than make clean every time. If you want to do this by your way, try this:

CXX = g++ -O2 -Wall

all: clean code1 code2

code1: code1.cc utilities.cc
   $(CXX) $^ -o $@

code2: code2.cc utilities.cc
   $(CXX) $^ -o $@

clean: 
    rm ...
    echo Clean done

Why can't I define a static method in a Java interface?

Interfaces just provide a list of things a class will provide, not an actual implementation of those things, which is what your static item is.

If you want statics, use an abstract class and inherit it, otherwise, remove the static.

Hope that helps!

How to send a compressed archive that contains executables so that Google's attachment filter won't reject it

tar -cvzf filename.tar.gz directory_to_compress/

Most tar commands have a z option to create a gziped version.

Though seems to me the question is how to circumvent Google. I'm not sure if renaming your output file would fool Google, but you could try. I.e.,

tar -cvzf filename.bla directory_to_compress/

and then send the filename.bla - contents will would be a zipped tar, so at the other end it could be retrieved as usual.

How to replace local branch with remote branch entirely in Git?

As provided in chosen explanation, git reset is good. But nowadays we often use sub-modules: repositories inside repositories. For example, you if you use ZF3 and jQuery in your project you most probably want them to be cloned from their original repositories. In such case git reset is not enough. We need to update submodules to that exact version that are defined in our repository:

git checkout master
git fetch origin master
git reset --hard origin/master
git pull

git submodule foreach git submodule update

git status

it is the same as you will come (cd) recursively to the working directory of each sub-module and will run:

git submodule update

And it's very different from

git checkout master
git pull

because sub-modules point not to branch but to the commit.

In that cases when you manually checkout some branch for 1 or more submodules you can run

git submodule foreach git pull

Parse JSON from JQuery.ajax success data

input type Button

<input type="button" Id="update" value="Update">

I've successfully posted a form with AJAX in perl. After posting the form, controller returns a JSON response as below

$(function() {

    $('#Search').click(function() {
        var query = $('#query').val();
        var update = $('#update').val();

        $.ajax({
            type: 'POST',
            url: '/Products/Search/',
            data: {
                'insert': update,
                'query': address,
            },
            success: function(res) {
                $('#ProductList').empty('');
                console.log(res);
                json = JSON.parse(res);
                for (var i in json) {
                    var row = $('<tr>');
                    row.append($('<td id=' + json[i].Id + '>').html(json[i].Id));
                    row.append($('<td id=' + json[i].Name + '>').html(json[i].Name));
                    $('</tr>');
                    $('#ProductList').append(row);
                }
            },
            error: function() {
                alert("did not work");
                location.reload(true);
            }
        });
    });
});

How to model type-safe enum types?

There are many ways of doing.

1) Use symbols. It won't give you any type safety, though, aside from not accepting non-symbols where a symbol is expected. I'm only mentioning it here for completeness. Here's an example of usage:

def update(what: Symbol, where: Int, newValue: Array[Int]): MatrixInt =
  what match {
    case 'row => replaceRow(where, newValue)
    case 'col | 'column => replaceCol(where, newValue)
    case _ => throw new IllegalArgumentException
  }

// At REPL:   
scala> val a = unitMatrixInt(3)
a: teste7.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 0 0 1 /

scala> a('row, 1) = a.row(0)
res41: teste7.MatrixInt =
/ 1 0 0 \
| 1 0 0 |
\ 0 0 1 /

scala> a('column, 2) = a.row(0)
res42: teste7.MatrixInt =
/ 1 0 1 \
| 0 1 0 |
\ 0 0 0 /

2) Using class Enumeration:

object Dimension extends Enumeration {
  type Dimension = Value
  val Row, Column = Value
}

or, if you need to serialize or display it:

object Dimension extends Enumeration("Row", "Column") {
  type Dimension = Value
  val Row, Column = Value
}

This can be used like this:

def update(what: Dimension, where: Int, newValue: Array[Int]): MatrixInt =
  what match {
    case Row => replaceRow(where, newValue)
    case Column => replaceCol(where, newValue)
  }

// At REPL:
scala> a(Row, 2) = a.row(1)
<console>:13: error: not found: value Row
       a(Row, 2) = a.row(1)
         ^

scala> a(Dimension.Row, 2) = a.row(1)
res1: teste.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 0 1 0 /

scala> import Dimension._
import Dimension._

scala> a(Row, 2) = a.row(1)
res2: teste.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 0 1 0 /

Unfortunately, it doesn't ensure that all matches are accounted for. If I forgot to put Row or Column in the match, the Scala compiler wouldn't have warned me. So it gives me some type safety, but not as much as can be gained.

3) Case objects:

sealed abstract class Dimension
case object Row extends Dimension
case object Column extends Dimension

Now, if I leave out a case on a match, the compiler will warn me:

MatrixInt.scala:70: warning: match is not exhaustive!
missing combination         Column

    what match {
    ^
one warning found

It's used pretty much the same way, and doesn't even need an import:

scala> val a = unitMatrixInt(3)
a: teste3.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 0 0 1 /

scala> a(Row,2) = a.row(0)
res15: teste3.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 1 0 0 /

You might wonder, then, why ever use an Enumeration instead of case objects. As a matter of fact, case objects do have advantages many times, such as here. The Enumeration class, though, has many Collection methods, such as elements (iterator on Scala 2.8), which returns an Iterator, map, flatMap, filter, etc.

This answer is essentially a selected parts from this article in my blog.

onclick on a image to navigate to another page using Javascript

You can define a a click function and then set the onclick attribute for the element.

function imageClick(url) {
    window.location = url;
}

<img src="../images/bottle.jpg" alt="bottle" class="thumbnails" onclick="imageClick('../images/bottle.html')" />

This approach lets you get rid of the surrounding <a> element. If you want to keep it, then define the onclick attribute on <a> instead of on <img>.

How to return a part of an array in Ruby?

another way is to use the range method

foo = [1,2,3,4,5,6]
bar = [10,20,30,40,50,60]
a = foo[0...3]
b = bar[3...6]

print a + b 
=> [1, 2, 3, 40, 50 , 60]

Why should we include ttf, eot, woff, svg,... in a font-face

Woff is a compressed (zipped) form of the TrueType - OpenType font. It is small and can be delivered over the network like a graphic file. Most importantly, this way the font is preserved completely including rendering rule tables that very few people care about because they use only Latin script.

Take a look at [dead URL removed]. The font you see is an experimental web delivered smartfont (woff) that has thousands of combined characters making complex shapes. The underlying text is simple Latin code of romanized Singhala. (Copy and paste to Notepad and see).

Only woff can do this because nobody has this font and yet it is seen anywhere (Mac, Win, Linux and even on smartphones by all browsers except by IE. IE does not have full support for Open Types).

How do I revert all local changes in Git managed project to previous state?

I met a similar problem. The solution is to use git log to look up which version of the local commit is different from the remote. (E.g. the version is 3c74a11530697214cbcc4b7b98bf7a65952a34ec).

Then use git reset --hard 3c74a11530697214cbcc4b7b98bf7a65952a34ec to revert the change.

jQuery UI Datepicker - Multiple Date Selections

When you modifiy it a little, it works regardless which dateFormat you have set.

$("#datepicker").datepicker({
                        dateFormat: "@", // Unix timestamp
                        onSelect: function(dateText, inst){
                            addOrRemoveDate(dateText);
                        },
                        beforeShowDay: function(date){
                            var gotDate = $.inArray($.datepicker.formatDate($(this).datepicker('option', 'dateFormat'), date), dates);
                            if (gotDate >= 0) {
                                return [false,"ui-state-highlight", "Event Name"];
                            }
                            return [true, ""];
                        }
                    });     

Copy rows from one Datatable to another DataTable?

 private void CopyDataTable(DataTable table){
     // Create an object variable for the copy.
     DataTable copyDataTable;
     copyDataTable = table.Copy();
     // Insert code to work with the copy.
 }

How to pass prepareForSegue: an object

I came across this question when I was trying to learn how to pass data from one View Controller to another. I need something visual to help me learn though, so this answer is a supplement to the others already here. It is a little more general than the original question but it can be adapted to work.

This basic example works like this:

enter image description here

The idea is to pass a string from the text field in the First View Controller to the label in the Second View Controller.

First View Controller

import UIKit

class FirstViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!

    // This function is called before the segue
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        // get a reference to the second view controller
        let secondViewController = segue.destinationViewController as! SecondViewController

        // set a variable in the second view controller with the String to pass
        secondViewController.receivedString = textField.text!
    }

}

Second View Controller

import UIKit

class SecondViewController: UIViewController {

    @IBOutlet weak var label: UILabel!

    // This variable will hold the data being passed from the First View Controller
    var receivedString = ""

    override func viewDidLoad() {
        super.viewDidLoad()

        // Used the text from the First View Controller to set the label
        label.text = receivedString
    }

}

Remember to

  • Make the segue by control clicking on the button and draging it over to the Second View Controller.
  • Hook up the outlets for the UITextField and the UILabel.
  • Set the first and second View Controllers to the appropriate Swift files in IB.

Source

How to send data through segue (swift) (YouTube tutorial)

See also

View Controllers: Passing data forward and passing data back (fuller answer)

Start a fragment via Intent within a Fragment

Try this it may help you:

private void changeFragment(Fragment targetFragment){

    getSupportFragmentManager()
         .beginTransaction()
         .replace(R.id.main_fragment, targetFragment, "fragment")
         .setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
         .commit();

}

Jenkins fails when running "service start jenkins"

Similar problem on Ubuntu 16.04.

Setting up jenkins (2.72) ...
Job for jenkins.service failed because the control process exited with error code. See "systemctl status jenkins.service" and "journalctl -xe" for details.
invoke-rc.d: initscript jenkins, action "start" failed.
? jenkins.service - LSB: Start Jenkins at boot time
Loaded: loaded (/etc/init.d/jenkins; bad; vendor preset: enabled)
Active: failed (Result: exit-code) since Tue 2017-08-01 05:39:06 UTC; 7ms ago
Docs: man:systemd-sysv-generator(8)
Process: 3700 ExecStart=/etc/init.d/jenkins start (code=exited, status=1/FAILURE)

Aug 01 05:39:06 ip-0 systemd[1]: Starting LSB: Start Jenkins ....
Aug 01 05:39:06 ip-0 jenkins[3700]: ERROR: No Java executable ...
Aug 01 05:39:06 ip-0 jenkins[3700]: If you actually have java ...
Aug 01 05:39:06 ip-0 systemd[1]: jenkins.service: Control pro...1
Aug 01 05:39:06 ip-0 systemd[1]: Failed to start LSB: Start J....
Aug 01 05:39:06 ip-0 systemd[1]: jenkins.service: Unit entere....
Aug 01 05:39:06 ip-0 systemd[1]: jenkins.service: Failed with....

To fix the issue manually install Java Runtime Environment:

JDK version 9:

sudo apt install openjdk-9-jre

JDK version 8:

sudo apt install openjdk-8-jre

Open Jenkins configuration file:

sudo vi /etc/init.d/jenkins

Finally, append path to the new java executable (line 16):

PATH=/bin:/usr/bin:/sbin:/usr/sbin:/usr/lib/jvm/java-8-openjdk-amd64/bin/

Convert PEM traditional private key to PKCS8 private key

Try using following command. I haven't tried it but I think it should work.

openssl pkcs8 -topk8 -inform PEM -outform DER -in filename -out filename -nocrypt

Installing lxml module in python

Just do:

sudo apt-get install python-lxml

For Python 2 (e.g., required by Inkscape):

sudo apt-get install python2-lxml

If you are planning to install from source, then albertov's answer will help. But unless there is a reason, don't, just install it from the repository.

React Js: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

It may come when the API(you are consuming) is not sending the corresponding JSON. You may experience the response as 404 page or something like HTML/XML response.

How can I check if a directory exists in a Bash shell script?

The ls command in conjunction with -l (long listing) option returns attributes information about files and directories.
In particular the first character of ls -l output it is usually a d or a - (dash). In case of a d the one listed is a directory for sure.

The following command in just one line will tell you if the given ISDIR variable contains a path to a directory or not:

[[ $(ls -ld "$ISDIR" | cut -c1) == 'd' ]] &&
    echo "YES, $ISDIR is a directory." || 
    echo "Sorry, $ISDIR is not a directory"

Practical usage:

    [claudio@nowhere ~]$ ISDIR="$HOME/Music" 
    [claudio@nowhere ~]$ ls -ld "$ISDIR"
    drwxr-xr-x. 2 claudio claudio 4096 Aug 23 00:02 /home/claudio/Music
    [claudio@nowhere ~]$ [[ $(ls -ld "$ISDIR" | cut -c1) == 'd' ]] && 
        echo "YES, $ISDIR is a directory." ||
        echo "Sorry, $ISDIR is not a directory"
    YES, /home/claudio/Music is a directory.

    [claudio@nowhere ~]$ touch "empty file.txt"
    [claudio@nowhere ~]$ ISDIR="$HOME/empty file.txt" 
    [claudio@nowhere ~]$ [[ $(ls -ld "$ISDIR" | cut -c1) == 'd' ]] && 
        echo "YES, $ISDIR is a directory." || 
        echo "Sorry, $ISDIR is not a directoy"
    Sorry, /home/claudio/empty file.txt is not a directory

What causes signal 'SIGILL'?

Make sure that all functions with non-void return type have a return statement.

While some compilers automatically provide a default return value, others will send a SIGILL or SIGTRAP at runtime when trying to leave a function without a return value.

SMTP connect() failed PHPmailer - PHP

I fixed it ...

https://github.com/PHPMailer/PHPMailer/tree/5.2-stable

_x000D_
_x000D_
<?php_x000D_
require 'PHPMailerAutoload.php';_x000D_
_x000D_
$mail = new PHPMailer;_x000D_
_x000D_
//$mail->SMTPDebug = 3;                               // Enable verbose debug output_x000D_
_x000D_
$mail->isSMTP();                                      // Set mailer to use SMTP_x000D_
$mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers_x000D_
$mail->SMTPAuth = true;                               // Enable SMTP authentication_x000D_
$mail->Username = '[email protected]';                 // SMTP username_x000D_
$mail->Password = 'pass';                           // SMTP password_x000D_
//$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted_x000D_
$mail->Port = 25;                                    // TCP port to connect to_x000D_
_x000D_
$mail->setFrom('[email protected]', 'Mailer');_x000D_
$mail->addAddress('[email protected]', 'User');     // Add a recipient_x000D_
_x000D_
$mail->isHTML(true);                                  // Set email format to HTML_x000D_
_x000D_
$mail->Subject = 'Here is the subject';_x000D_
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';_x000D_
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';_x000D_
_x000D_
if(!$mail->send()) {_x000D_
    echo 'Message could not be sent.';_x000D_
    echo 'Mailer Error: ' . $mail->ErrorInfo;_x000D_
} else {_x000D_
    echo 'Message has been sent';_x000D_
}
_x000D_
_x000D_
_x000D_

Turn on access and enjoy..! That is on Gmail account setting.

Turn On access

SQL Server insert if not exists best practice

You will need to join the tables together and get a list of unique competitors that don't already exist in Competitors.

This will insert unique records.

INSERT Competitors (cName) 
SELECT DISTINCT Name
FROM CompResults cr LEFT JOIN Competitors c ON cr.Name = c.cName
WHERE c.Name IS NULL

There may come a time when this insert needs to be done quickly without being able to wait for the selection of unique names. In that case, you could insert the unique names into a temporary table, and then use that temporary table to insert into your real table. This works well because all the processing happens at the time you are inserting into a temporary table, so it doesn't affect your real table. Then when you have all the processing finished, you do a quick insert into the real table. I might even wrap the last part, where you insert into the real table, inside a transaction.

Sql query to insert datetime in SQL Server

you need to add it like

insert into table1(date1) values('12-mar-2013');

Unable to auto-detect email address

Just type like "correct" case

"wrong"

git config --global mike.email "[email protected]"
git config --global mike.name  "mike"

"correct"

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

user.name is your account name in git-hub user.email is your email when you sign in git-hub.

How to avoid Sql Query Timeout

Your query is probably fine. "The semaphore timeout period has expired" is a Network error, not a SQL Server timeout.

There is apparently some sort of network problem between you and the SQL Server.

edit: However, apparently the query runs for 15-20 min before giving the network error. That is a very long time, so perhaps the network error could be related to the long execution time. Optimization of the underlying View might help.

If [MyTable] in your example is a View, can you post the View Definition so that we can have a go at optimizing it?

Passing parameters to addTarget:action:forControlEvents

If you just want to change the text for the leftBarButtonItem shown by the navigation controller together with the new view, you may change the title of the current view just before calling pushViewController to the wanted text and restore it in the viewHasDisappered callback for future showings of the current view.

This approach keeps the functionality (popViewController) and the appearance of the shown arrow intact.

It works for us at least with iOS 12, built with Xcode 10.1 ...

How to create an empty file with Ansible?

Changed if file not exists. Create empty file.

- name: create fake 'nologin' shell
  file:
    path: /etc/nologin
    state: touch
  register: p
  changed_when: p.diff.before.state == "absent"

How to Deserialize JSON data?

Step 1: Go to json.org to find the JSON library for whatever technology you're using to call this web service. Download and link to that library.

Step 2: Let's say you're using Java. You would use JSONArray like this:

JSONArray myArray=new JSONArray(queryResponse);
for (int i=0;i<myArray.length;i++){
    JSONArray myInteriorArray=myArray.getJSONArray(i);
    if (i==0) {
        //this is the first one and is special because it holds the name of the query.
    }else{
        //do your stuff
        String stateCode=myInteriorArray.getString(0);
        String stateName=myInteriorArray.getString(1);
    }
}

How to change the buttons text using javascript

You can toggle filterstatus value like this

filterstatus ^= 1;

So your function looks like

function showFilterItem(objButton) {
if (filterstatus == 0) {
    $find('<%=FileAdminRadGrid.ClientID %>').get_masterTableView().showFilterItem();
    objButton.value = "Hide Filter";
}
else {
    $find('<%=FileAdminRadGrid.ClientID %>').get_masterTableView().hideFilterItem();
    objButton.value = "Show filter";
}
  filterstatus ^= 1;    
}

How to read a text file?

It depends on what you are trying to do.

file, err := os.Open("file.txt")
fmt.print(file)

The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File), not file-content. To obtain file-content, you may READ from a file-descriptor.


To read all file content(in bytes) to memory, ioutil.ReadAll

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "log"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


  b, err := ioutil.ReadAll(file)
  fmt.Print(b)
}

But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read from *os.File

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


    buf := make([]byte, 32*1024) // define your buffer size here.

    for {
        n, err := file.Read(buf)

        if n > 0 {
            fmt.Print(buf[:n]) // your read buffer.
        }

        if err == io.EOF {
            break
        }
        if err != nil {
            log.Printf("read %d bytes: %v", n, err)
            break
        }
    }

}

Otherwise, you could also use the standard util package: bufio, try Scanner. A Scanner reads your file in tokens: separator.

By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).

package main

import (
    "fmt"
    "os"
    "log"
    "bufio"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()

    scanner := bufio.NewScanner(file)

    for scanner.Scan() {             // internally, it advances token based on sperator
        fmt.Println(scanner.Text())  // token in unicode-char
        fmt.Println(scanner.Bytes()) // token in bytes

    }
}

Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.

How do I copy a string to the clipboard?

you can try this:

command = 'echo content |clip'
subprocess.check_call(command, shell=True)

Create a <ul> and fill it based on a passed array

You may also consider the following solution:

let sum = options.set0.concat(options.set1);
const codeHTML = '<ol>' + sum.reduce((html, item) => {
    return html + "<li>" + item + "</li>";
        }, "") + '</ol>';
document.querySelector("#list").innerHTML = codeHTML;

Merge, update, and pull Git branches without using checkouts

Another, admittedly pretty brute way is to just re-create the branch:

git fetch remote
git branch -f localbranch remote/remotebranch

This throws away the local outdated branch and re-creates one with the same name, so use with care ...

How to check if a query string value is present via JavaScript?

one more variant, but almost the same as Gumbos solution:

var isDebug = function(){
    return window.location.href.search("[?&]debug=") != -1;
};

Grouping switch statement cases together?

gcc has a so-called "case range" extension:

http://gcc.gnu.org/onlinedocs/gcc-4.2.4/gcc/Case-Ranges.html#Case-Ranges

I used to use this when I was only using gcc. Not much to say about it really -- it does sort of what you want, though only for ranges of values.

The biggest problem with this is that only gcc supports it; this may or may not be a problem for you.

(I suspect that for your example an if statement would be a more natural fit.)

shared global variables in C

If you're sharing code between C and C++, remember to add the following to the shared.hfile:

#ifdef __cplusplus
extern "C" {
#endif

extern int my_global;
/* other extern declarations ... */

#ifdef __cplusplus
}
#endif

How to open mail app from Swift

Updated answer from Stephen Groom for Swift 3

let email = "[email protected]"
let url = URL(string: "mailto:\(email)")
UIApplication.shared.openURL(url!)

Add a column to a table, if it does not already exist

Another alternative. I prefer this approach because it is less writing but the two accomplish the same thing.

IF COLUMNPROPERTY(OBJECT_ID('dbo.Person'), 'ColumnName', 'ColumnId') IS NULL
BEGIN
    ALTER TABLE Person 
    ADD ColumnName VARCHAR(MAX) NOT NULL
END

I also noticed yours is looking for where table does exist that is obviously just this

 if COLUMNPROPERTY( OBJECT_ID('dbo.Person'),'ColumnName','ColumnId') is not null

Delete specific line from a text file?

No rocket scien code require .Hope this simple and short code will help.

List linesList = File.ReadAllLines("myFile.txt").ToList();            
linesList.RemoveAt(0);
File.WriteAllLines("myFile.txt"), linesList.ToArray());

OR use this

public void DeleteLinesFromFile(string strLineToDelete)
    {
        string strFilePath = "Provide the path of the text file";
        string strSearchText = strLineToDelete;
        string strOldText;
        string n = "";
        StreamReader sr = File.OpenText(strFilePath);
        while ((strOldText = sr.ReadLine()) != null)
        {
            if (!strOldText.Contains(strSearchText))
            {
                n += strOldText + Environment.NewLine;
            }
        }
        sr.Close();
        File.WriteAllText(strFilePath, n);
    }

How to get current user who's accessing an ASP.NET application?

The best practice is to check the Identity.IsAuthenticated Property first and then get the usr.UserName like this:

string userName = string.Empty;

if (System.Web.HttpContext.Current != null && 
    System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
    System.Web.Security.MembershipUser usr = Membership.GetUser();
    if (usr != null)
    {  
        userName = usr.UserName;
    }
}

What is difference between XML Schema and DTD?

DTD indicates the syntax of the XML element

XML Schemas are Microsoft's alternative to DTD for validating XML

Load dimension value from res/values/dimension.xml from source code

For those who just need to save some int value in the resources, you can do the following.

integers.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="default_value">100</integer>
</resources> 

Code

int defaultValue = getResources().getInteger(R.integer.default_value);

Getting file size in Python?

os.path.getsize(path)

Return the size, in bytes, of path. Raise os.error if the file does not exist or is inaccessible.

How to set MouseOver event/trigger for border in XAML?

Yes, this is confusing...

According to this blog post, it looks like this is an omission from WPF.

To make it work you need to use a style:

    <Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
        <Border.Style>
            <Style>
                <Setter Property="Border.Background" Value="Blue"/>
                <Style.Triggers>
                    <Trigger Property="Border.IsMouseOver" Value="True">
                        <Setter Property="Border.Background" Value="Green" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Border.Style>
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
    </Border>

I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.

Don't understand why UnboundLocalError occurs (closure)

To answer the question in your subject line,* yes, there are closures in Python, except they only apply inside a function, and also (in Python 2.x) they are read-only; you can't re-bind the name to a different object (though if the object is mutable, you can modify its contents). In Python 3.x, you can use the nonlocal keyword to modify a closure variable.

def incrementer():
    counter = 0
    def increment():
        nonlocal counter
        counter += 1
        return counter
    return increment

increment = incrementer()

increment()   # 1
increment()   # 2

* The question origially asked about closures in Python.

Excel plot time series frequency with continuous xaxis

You can get good Time Series graphs in Excel, the way you want, but you have to work with a few quirks.

  1. Be sure to select "Scatter Graph" (with a line option). This is needed if you have non-uniform time stamps, and will scale the X-axis accordingly.

  2. In your data, you need to add a column with the mid-point. Here's what I did with your sample data. (This trick ensures that the data gets plotted at the mid-point, like you desire.) enter image description here

  3. You can format the x-axis options with this menu. (Chart->Design->Layout) enter image description here

  4. Select "Axes" and go to Primary Horizontal Axis, and then select "More Primary Horizontal Axis Options"

  5. Set up the options you wish. (Fix the starting and ending points.) enter image description here

  6. And you will get a graph such as the one below. enter image description here

You can then tweak many of the options, label the axes better etc, but this should get you started.

Hope this helps you move forward.

Best way to get all selected checkboxes VALUES in jQuery

You want the :checkbox:checked selector and map to create an array of the values:

var checkedValues = $('input:checkbox:checked').map(function() {
    return this.value;
}).get();

If your checkboxes have a shared class it would be faster to use that instead, eg. $('.mycheckboxes:checked'), or for a common name $('input[name="Foo"]:checked')

- Update -

If you don't need IE support then you can now make the map() call more succinct by using an arrow function:

var checkedValues = $('input:checkbox:checked').map((i, el) => el.value).get();

Replace transparency in PNG images with white background

It appears that your command is correct so the problem might be due to missing support for PNG (). You can check with convert -list configure or just try the following:

sudo yum install libpng libpng-devel

How to go from one page to another page using javascript?

Easier method is window.location.href = "http://example.com/new_url";

But what if you want to check if username and password whether empty or not using JavaScript and send it to the php to check whether user in the database. You can do this easily following this code.

html form -

<form name="myForm" onsubmit="return validateForm()" method="POST" action="login.php" >         
    <input type="text" name="username" id="username" />
    <input type="password" name="password" id="password" />
    <input type="submit" name="submitBt"value="LogIn" />
</form>

javascript validation-

function validateForm(){
    var uname = document.forms["myForm"]["username"].value;
    var pass = document.forms["myForm"]["password"].value;

    if((!isEmpty(uname, "Log In")) && (!isEmpty(pass, "Password"))){

        return true;
    }else{
        return false;
    }
}

function isEmpty(elemValue, field){
    if((elemValue == "") || (elemValue == null)){
        alert("you can not have "+field+" field empty");
        return true;
    }else{
        return false;
    }
}

check if user in the database using php

<?php
    $con = mysqli_connect("localhost","root","1234","users");

    if(mysqli_connect_errno()){
        echo "Couldn't connect ".mysqli_connect_error();
    }else{
        //echo "connection successful <br />";
    }

    $uname_tb = $_POST['username'];
    $pass_tb = $_POST['password'];

    $query ="SELECT * FROM user";
    $result = mysqli_query($con,$query);

    while($row = mysqli_fetch_array($result)){
        if(($row['username'] == $uname_tb) && ($row['password'] == $pass_tb)){
            echo "Login Successful";
            header('Location: dashbord.php');
            exit();
        }else{
            echo "You are not in our database".mysqli_connect_error();
        }
    }
    mysqli_close($con);
?>

How can I disable ReSharper in Visual Studio and enable it again?

You need to goto Tools-->Options--->Select Resharper--->Click on suspend now,to disable it

Print line numbers starting at zero using awk

NR starts at 1, so use

awk '{print NR-1 "," $0}'

What are all the uses of an underscore in Scala?

Besides the usages that JAiro mentioned, I like this one:

def getConnectionProps = {
    ( Config.getHost, Config.getPort, Config.getSommElse, Config.getSommElsePartTwo )
}

If someone needs all connection properties, he can do:

val ( host, port, sommEsle, someElsePartTwo ) = getConnectionProps

If you need just a host and a port, you can do:

val ( host, port, _, _ ) = getConnectionProps

How do I disable "missing docstring" warnings at a file-level in Pylint?

I think the fix is relative easy without disabling this feature.

def kos_root():
    """Return the pathname of the KOS root directory."""
    global _kos_root
    if _kos_root: return _kos_root

All you need to do is add the triple double quotes string in every function.

How to select a div element in the code-behind page?

You have make div as server control using following code,

<div class="tab-pane active" id="portlet_tab1" runat="server">

then this div will be accessible in code behind.

How to enable Auto Logon User Authentication for Google Chrome

If you add your site to "Local Intranet" in

Chrome > Options > Under the Hood > Change Proxy Settings > Security (tab) > Local Intranet/Sites > Advanced.

Add you site URL here and it will work.

Update for New Version of Chrome

Chrome > Settings > Advanced > System > Open Proxy Settings > Security (tab) > Local Intranet > Sites (button) > Advanced.

How do I find the current executable filename?

If you want the executable:

System.Reflection.Assembly.GetEntryAssembly().Location

If you want the assembly that's consuming your library (which could be the same assembly as above, if your code is called directly from a class within your executable):

System.Reflection.Assembly.GetCallingAssembly().Location

If you'd like just the filename and not the path, use:

Path.GetFileName(System.Reflection.Assembly.GetEntryAssembly().Location)

Why is nginx responding to any domain name?

You should have a default server for catch-all, you can return 404 or better to not respond at all (will save some bandwidth) by returning 444 which is nginx specific HTTP response that simply close the connection and return nothing

server {
    listen       80  default_server;
    server_name  _; # some invalid name that won't match anything
    return       444;
}

How can I simulate an anchor click via jquery?

I've recently found how to trigger mouse click event via jQuery.

    <script type="text/javascript">
    var a = $('.path > .to > .element > a')[0];
    var e = document.createEvent('MouseEvents');
    e.initEvent( 'click', true, true );
    a.dispatchEvent(e);
    </script>

Can overridden methods differ in return type?

Yes it may differ but there are some limitations.

Before Java 5.0, when you override a method, both parameters and return type must match exactly. Java 5.0 it introduces a new facility called covariant return type. You can override a method with the same signature but return a subclass of the object returned.

In another words, a method in a subclass can return an object whose type is a subclass of the type returned by the method with the same signature in the superclass.

Query comparing dates in SQL

Instead of '2013-04-12' whose meaning depends on the local culture, use '20130412' which is recognized as the culture invariant format.

If you want to compare with December 4th, you should write '20131204'. If you want to compare with April 12th, you should write '20130412'.

The article Write International Transact-SQL Statements from SQL Server's documentation explains how to write statements that are culture invariant:

Applications that use other APIs, or Transact-SQL scripts, stored procedures, and triggers, should use the unseparated numeric strings. For example, yyyymmdd as 19980924.

EDIT

Since you are using ADO, the best option is to parameterize the query and pass the date value as a date parameter. This way you avoid the format issue entirely and gain the performance benefits of parameterized queries as well.

UPDATE

To use the the the ISO 8601 format in a literal, all elements must be specified. To quote from the ISO 8601 section of datetime's documentation

To use the ISO 8601 format, you must specify each element in the format. This also includes the T, the colons (:), and the period (.) that are shown in the format.

... the fraction of second component is optional. The time component is specified in the 24-hour format.

How do you Change a Package's Log Level using Log4j?

I encountered the exact same problem today, Ryan.

In my src (or your root) directory, my log4j.properties file now has the following addition

# https://issues.apache.org/jira/browse/AXIS2-4363
log4j.category.org.apache.axiom=WARN

Thanks for the heads up as to how to do this, Benjamin.

What is the difference between DBMS and RDBMS?

DBMS: is a software system that allows Defining, Creation, Querying, Update, and Administration of data stored in data files.

Features:

  • Normal book keeping system, Flat files, MS Excel, FoxPRO, XML, etc.
  • Less or No provision for: Constraints, Security, ACID rules, users, etc.

RDBMS: is a DBMS that is based on Relational model that stores data in tabular form.

  • SQL Server, Sybase, Oracle, MySQL, IBM DB2, MS Access, etc.

Features:

  • Database, with Tables having relations maintained by FK
  • DDL, DML
  • Data Integrity & ACID rules
  • Multiple User Access
  • Backup & Restore
  • Database Administration

Drop rows containing empty cells from a pandas DataFrame

value_counts omits NaN by default so you're most likely dealing with "".

So you can just filter them out like

filter = df["Tenant"] != ""
dfNew = df[filter]

Email validation using jQuery

<script type="text/javascript">
    $(document).ready(function() {
      $('.form_error').hide();
      $('#submit').click(function(){
           var name = $('#name').val();
           var email = $('#email').val();
           var phone = $('#phone').val();
           var message = $('#message').val();
           if(name== ''){
              $('#name').next().show();
              return false;
            }
            if(email== ''){
               $('#email').next().show();
               return false;
            }
            if(IsEmail(email)==false){
                $('#invalid_email').show();
                return false;
            }

            if(phone== ''){
                $('#phone').next().show();
                return false;
            }
            if(message== ''){
                $('#message').next().show();
                return false;
            }
            //ajax call php page
            $.post("send.php", $("#contactform").serialize(),  function(response) {
            $('#contactform').fadeOut('slow',function(){
                $('#success').html(response);
                $('#success').fadeIn('slow');
               });
             });
             return false;
          });
      });
      function IsEmail(email) {
        var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if(!regex.test(email)) {
           return false;
        }else{
           return true;
        }
      }
  </script>

<form action="" method="post" id="contactform">
                            <table class="contact-table">
                              <tr>
                                <td><label for="name">Name :</label></td>
                                <td class="name"> <input name="name" id="name" type="text" placeholder="Please enter your name" class="contact-input"><span class="form_error">Please enter your name</span></td>
                              </tr>
                              <tr>
                                <td><label for="email">Email :</label></td>
                                <td class="email"><input name="email" id="email" type="text" placeholder="Please enter your email" class="contact-input"><span class="form_error">Please enter your email</span>
                                  <span class="form_error" id="invalid_email">This email is not valid</span></td>
                              </tr>
                              <tr>
                                <td><label for="phone">Phone :</label></td>
                                <td class="phone"><input name="phone" id="phone" type="text" placeholder="Please enter your phone" class="contact-input"><span class="form_error">Please enter your phone</span></td>
                              </tr>
                              <tr>
                                <td><label for="message">Message :</label></td>
                                <td class="message"><textarea name="message" id="message" class="contact-input"></textarea><span class="form_error">Please enter your message</span></td>
                              </tr>
                              <tr>
                                <td></td>
                                <td>
                                  <input type="submit" class="contactform-buttons" id="submit"value="Send" />
                                  <input type="reset" class="contactform-buttons" id="" value="Clear" />
                                </td>
                              </tr>
                            </table>
     </form>
     <div id="success" style="color:red;"></div>

CSS customized scroll bar in div

Like many people, I was looking for something that was:

  • Consistently styled and functional across most modern browsers
  • Not some ridiculous 3000-line bloated jQuery extension cr*p

...But alas - nothing!

Well if a job's worth doing... I was able to get something up and running in about 30 mins. Disclaimer: there's quite a few known (and probably a few as yet unknown) problems with it, but it makes me wonder what on Earth the other 2920 lines of JS are there for in many offerings!

_x000D_
_x000D_
(window => {

  let initCoords;

  const coords_update = e => {
    if (initCoords) {
      const elem = initCoords.bar.closest('.scrollr');
      const eSuffix = initCoords.axis.toUpperCase();
      const sSuffix = initCoords.axis == 'x' ? 'Left' : 'Top';
      const dSuffix = initCoords.axis == 'x' ? 'Width' : 'Height';
      const max = elem['scroll' + dSuffix] - elem['client' + dSuffix];
      const room = elem['client' + dSuffix] - initCoords.bar['client' + dSuffix];
      const delta = e['page' + eSuffix] - initCoords.abs;
      const abs = initCoords.p0 + delta;
      elem['scroll' + sSuffix] = max * abs / room;
    }
  };

  const scrollr_resize = elem => {
    const xBar = elem.querySelector('.track.x .bar');
    const yBar = elem.querySelector('.track.y .bar');
    const xRel = elem.clientWidth / elem.scrollWidth;
    const yRel = elem.clientHeight / elem.scrollHeight;
    xBar.style.width = (100 * xRel).toFixed(2) + '%';
    yBar.style.height = (100 * yRel).toFixed(2) + '%';
  };

  const scrollr_init = elem => {
    const xTrack = document.createElement('span');
    const yTrack = document.createElement('span');
    const xBar = document.createElement('span');
    const yBar = document.createElement('span');
    xTrack.className = 'track x';
    yTrack.className = 'track y';
    xBar.className = 'bar';
    yBar.className = 'bar';
    xTrack.appendChild(xBar);
    yTrack.appendChild(yBar);
    elem.appendChild(xTrack);
    elem.appendChild(yTrack);
    elem.addEventListener('wheel', scrollr_OnWheel);
    elem.addEventListener('scroll', scrollr_OnScroll);
    xTrack.addEventListener('wheel', xTrack_OnWheel);
    xTrack.addEventListener('click', xTrack_OnClick);
    xTrack.addEventListener('mouseover', () => xTrack.classList.add('active'));
    xTrack.addEventListener('mouseout', () => {
      if (!initCoords) xTrack.classList.remove('active');
    });
    yTrack.addEventListener('click', yTrack_OnClick);
    yTrack.addEventListener('mouseover', () => yTrack.classList.add('active'));
    yTrack.addEventListener('mouseout', () => {
      if (!initCoords) yTrack.classList.remove('active');
    });
    xBar.addEventListener('click', bar_OnClick);
    xBar.addEventListener('mousedown', xBar_OnMouseDown);
    yBar.addEventListener('click', bar_OnClick);
    yBar.addEventListener('mousedown', yBar_OnMouseDown);

    scrollr_resize(elem);
  };

  window.addEventListener('load', e => {
    const scrollrz = Array.from(document.querySelectorAll('.scrollr'));
    scrollrz.forEach(scrollr_init);
  });

  window.addEventListener('resize', e => {
    const scrollrz = Array.from(document.querySelectorAll('.scrollr'));
    scrollrz.forEach(scrollr_resize);
  });

  window.addEventListener('mousemove', coords_update);
  window.addEventListener('mouseup', e => {
    initCoords = null;
    Array.from(document.querySelectorAll('.track.active'))
      .forEach(elem => elem.classList.remove('active'));
  });

  function xBar_OnMouseDown(e) {
    const p0 = this.offsetLeft;
    initCoords = {
      axis: 'x',
      abs: e.pageX,
      bar: this,
      p0
    };
  }

  function yBar_OnMouseDown(e) {
    const p0 = this.offsetTop;
    initCoords = {
      axis: 'y',
      abs: e.pageY,
      bar: this,
      p0
    };
  }

  function bar_OnClick(e) {
    e.stopPropagation();
  }

  function xTrack_OnClick(e) {
    const elem = this.closest('.scrollr');
    const xBar = this.querySelector('.bar');
    let unit = elem.clientWidth - 30;
    if (e.offsetX <= xBar.offsetLeft) unit *= -1;
    elem.scrollLeft += unit;
  }

  function yTrack_OnClick(e) {
    const elem = this.closest('.scrollr');
    const yBar = this.querySelector('.bar');
    let unit = elem.clientHeight - 30;
    if (e.offsetY <= yBar.offsetTop) unit *= -1;
    elem.scrollTop += unit;
  }

  function xTrack_OnWheel(e) {
    e.stopPropagation();
    const elem = this.closest('.scrollr');
    const left0 = elem.scrollLeft;
    const delta = e.deltaY !== 0 ? e.deltaY : e.deltaX;
    elem.scrollLeft += delta;
    const moved = left0 !== elem.scrollLeft;
    if (moved) e.preventDefault();
  }

  function scrollr_OnWheel(e) {
    const left0 = this.scrollLeft;
    const top0 = this.scrollTop;
    this.scrollLeft += e.deltaX;
    this.scrollTop += e.deltaY;
    const moved = left0 !== this.scrollLeft || top0 !== this.scrollTop;
    if (moved) e.preventDefault();
  }

  function scrollr_OnScroll(e) {
    const xTrack = this.querySelector('.track.x');
    const yTrack = this.querySelector('.track.y');
    const xBar = xTrack.querySelector('.bar');
    const yBar = yTrack.querySelector('.bar');

    const xMax = this.scrollWidth - this.clientWidth;
    const yMax = this.scrollHeight - this.clientHeight;
    const xFrac = this.scrollLeft / xMax;
    const yFrac = this.scrollTop / yMax;
    const xAbs = xFrac * (this.clientWidth - xBar.clientWidth);
    const yAbs = yFrac * (this.clientHeight - yBar.clientHeight);

    xTrack.style.left = this.scrollLeft + 'px';
    xTrack.style.bottom = -this.scrollTop + 'px';
    xBar.style.left = xAbs + 'px';

    yTrack.style.top = this.scrollTop + 'px';
    yTrack.style.right = -this.scrollLeft + 'px';
    yBar.style.top = yAbs + 'px';
  };

})(window);
_x000D_
.scrollr {
  overflow: hidden;
  position: relative;
}

.track {
  position: absolute;
  cursor: pointer;
  transition: background-color .3s;
  user-select: none;
}

.track.x {
  left: 0;
  bottom: 0;
  width: 100%;
  height: 10px;
}

.track.y {
  top: 0;
  right: 0;
  height: 100%;
  width: 10px;
}

.bar {
  position: absolute;
  background-color: yellow;
  transition: background-color .3s, opacity .3s, width .3s, height .3s, margin .3s;
  display: block;
  width: 100%;
  height: 100%;
  opacity: .7;
}

.track.x .bar {
  min-width: 25px;
  height: 3px;
  margin: 5px 0 2px 0;
}

.track.y .bar {
  min-height: 25px;
  width: 3px;
  margin: 0 2px 0 5px;
}

.track.active {
  background-color: #ccc;
}

.track.active .bar {
  background-color: #999;
  margin: 0;
  opacity: 1;
}

.track.x.active .bar {
  height: 10px;
}

.track.y.active .bar {
  width: 10px;
}


/* Custom client stuff */

.content {
  background: red;
}

.content p {
  width: 450px;
  margin: 0;
}

.scrollr {
  max-width: 350px;
  max-height: 150px;
}
_x000D_
<div class="scrollr content">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc diam magna, molestie sit amet auctor nec, dictum quis mi. Duis pellentesque lacinia pretium. Donec pulvinar, risus sit amet dapibus mattis, eros urna bibendum elit, vel mollis sapien arcu
    vitae mi. Fusce vulputate vestibulum metus dapibus eleifend. Quisque ut dictum orci. Nunc bibendum, sapien ac condimentum placerat, arcu orci mollis nunc, vitae sollicitudin arcu nulla quis enim. Praesent non tellus vitae quam tempor maximus vel sed
    dolor. Donec id ante ultricies, iaculis sem ut, sollicitudin enim. Quisque id mauris est. Maecenas viverra urna vitae velit semper, vel ultricies augue feugiat. Pellentesque in libero porttitor, lacinia metus in, maximus nisi. Phasellus commodo ligula
    vel arcu iaculis hendrerit vitae vel diam. Sed sed lorem maximus, vestibulum leo ut, posuere libero. Donec arcu dui, euismod id aliquet sed, porttitor vitae elit.</p>
  <p>Sed aliquam eget justo sit amet dictum. Suspendisse potenti. In placerat orci quis vehicula vehicula. Proin tempor laoreet suscipit. Proin non nulla lacinia est ullamcorper maximus et a sem. Nulla at lacus rhoncus, malesuada ante in, imperdiet sem.
    Mauris convallis tristique metus in iaculis. Nulla laoreet ligula non interdum tincidunt. Morbi sed venenatis arcu, sed gravida est. Fusce malesuada ullamcorper lacus, in vulputate risus finibus non.</p>
  <p>Suspendisse sapien leo, auctor non ex vitae, volutpat laoreet tortor. Suspendisse sodales libero velit, sed pulvinar lectus feugiat vel. Sed erat eros, porttitor id enim nec, ornare hendrerit nibh. Phasellus at nisi lectus. Cras semper lobortis condimentum.
    Etiam nunc felis, vehicula vitae tincidunt pellentesque, pretium sit amet dui. Duis aliquet ultrices lacus eget efficitur. Ut imperdiet velit sed enim laoreet, sed semper libero hendrerit. Donec malesuada auctor sollicitudin.</p>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc diam magna, molestie sit amet auctor nec, dictum quis mi. Duis pellentesque lacinia pretium. Donec pulvinar, risus sit amet dapibus mattis, eros urna bibendum elit, vel mollis sapien arcu
    vitae mi. Fusce vulputate vestibulum metus dapibus eleifend. Quisque ut dictum orci. Nunc bibendum, sapien ac condimentum placerat, arcu orci mollis nunc, vitae sollicitudin arcu nulla quis enim. Praesent non tellus vitae quam tempor maximus vel sed
    dolor. Donec id ante ultricies, iaculis sem ut, sollicitudin enim. Quisque id mauris est. Maecenas viverra urna vitae velit semper, vel ultricies augue feugiat. Pellentesque in libero porttitor, lacinia metus in, maximus nisi. Phasellus commodo ligula
    vel arcu iaculis hendrerit vitae vel diam. Sed sed lorem maximus, vestibulum leo ut, posuere libero. Donec arcu dui, euismod id aliquet sed, porttitor vitae elit.</p>
  <p>Sed aliquam eget justo sit amet dictum. Suspendisse potenti. In placerat orci quis vehicula vehicula. Proin tempor laoreet suscipit. Proin non nulla lacinia est ullamcorper maximus et a sem. Nulla at lacus rhoncus, malesuada ante in, imperdiet sem.
    Mauris convallis tristique metus in iaculis. Nulla laoreet ligula non interdum tincidunt. Morbi sed venenatis arcu, sed gravida est. Fusce malesuada ullamcorper lacus, in vulputate risus finibus non.</p>
  <p>Suspendisse sapien leo, auctor non ex vitae, volutpat laoreet tortor. Suspendisse sodales libero velit, sed pulvinar lectus feugiat vel. Sed erat eros, porttitor id enim nec, ornare hendrerit nibh. Phasellus at nisi lectus. Cras semper lobortis condimentum.
    Etiam nunc felis, vehicula vitae tincidunt pellentesque, pretium sit amet dui. Duis aliquet ultrices lacus eget efficitur. Ut imperdiet velit sed enim laoreet, sed semper libero hendrerit. Donec malesuada auctor sollicitudin.</p>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc diam magna, molestie sit amet auctor nec, dictum quis mi. Duis pellentesque lacinia pretium. Donec pulvinar, risus sit amet dapibus mattis, eros urna bibendum elit, vel mollis sapien arcu
    vitae mi. Fusce vulputate vestibulum metus dapibus eleifend. Quisque ut dictum orci. Nunc bibendum, sapien ac condimentum placerat, arcu orci mollis nunc, vitae sollicitudin arcu nulla quis enim. Praesent non tellus vitae quam tempor maximus vel sed
    dolor. Donec id ante ultricies, iaculis sem ut, sollicitudin enim. Quisque id mauris est. Maecenas viverra urna vitae velit semper, vel ultricies augue feugiat. Pellentesque in libero porttitor, lacinia metus in, maximus nisi. Phasellus commodo ligula
    vel arcu iaculis hendrerit vitae vel diam. Sed sed lorem maximus, vestibulum leo ut, posuere libero. Donec arcu dui, euismod id aliquet sed, porttitor vitae elit.</p>
  <p>Sed aliquam eget justo sit amet dictum. Suspendisse potenti. In placerat orci quis vehicula vehicula. Proin tempor laoreet suscipit. Proin non nulla lacinia est ullamcorper maximus et a sem. Nulla at lacus rhoncus, malesuada ante in, imperdiet sem.
    Mauris convallis tristique metus in iaculis. Nulla laoreet ligula non interdum tincidunt. Morbi sed venenatis arcu, sed gravida est. Fusce malesuada ullamcorper lacus, in vulputate risus finibus non.</p>
  <p>Suspendisse sapien leo, auctor non ex vitae, volutpat laoreet tortor. Suspendisse sodales libero velit, sed pulvinar lectus feugiat vel. Sed erat eros, porttitor id enim nec, ornare hendrerit nibh. Phasellus at nisi lectus. Cras semper lobortis condimentum.
    Etiam nunc felis, vehicula vitae tincidunt pellentesque, pretium sit amet dui. Duis aliquet ultrices lacus eget efficitur. Ut imperdiet velit sed enim laoreet, sed semper libero hendrerit. Donec malesuada auctor sollicitudin.</p>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc diam magna, molestie sit amet auctor nec, dictum quis mi. Duis pellentesque lacinia pretium. Donec pulvinar, risus sit amet dapibus mattis, eros urna bibendum elit, vel mollis sapien arcu
    vitae mi. Fusce vulputate vestibulum metus dapibus eleifend. Quisque ut dictum orci. Nunc bibendum, sapien ac condimentum placerat, arcu orci mollis nunc, vitae sollicitudin arcu nulla quis enim. Praesent non tellus vitae quam tempor maximus vel sed
    dolor. Donec id ante ultricies, iaculis sem ut, sollicitudin enim. Quisque id mauris est. Maecenas viverra urna vitae velit semper, vel ultricies augue feugiat. Pellentesque in libero porttitor, lacinia metus in, maximus nisi. Phasellus commodo ligula
    vel arcu iaculis hendrerit vitae vel diam. Sed sed lorem maximus, vestibulum leo ut, posuere libero. Donec arcu dui, euismod id aliquet sed, porttitor vitae elit.</p>
  <p>Sed aliquam eget justo sit amet dictum. Suspendisse potenti. In placerat orci quis vehicula vehicula. Proin tempor laoreet suscipit. Proin non nulla lacinia est ullamcorper maximus et a sem. Nulla at lacus rhoncus, malesuada ante in, imperdiet sem.
    Mauris convallis tristique metus in iaculis. Nulla laoreet ligula non interdum tincidunt. Morbi sed venenatis arcu, sed gravida est. Fusce malesuada ullamcorper lacus, in vulputate risus finibus non.</p>
  <p>Suspendisse sapien leo, auctor non ex vitae, volutpat laoreet tortor. Suspendisse sodales libero velit, sed pulvinar lectus feugiat vel. Sed erat eros, porttitor id enim nec, ornare hendrerit nibh. Phasellus at nisi lectus. Cras semper lobortis condimentum.
    Etiam nunc felis, vehicula vitae tincidunt pellentesque, pretium sit amet dui. Duis aliquet ultrices lacus eget efficitur. Ut imperdiet velit sed enim laoreet, sed semper libero hendrerit. Donec malesuada auctor sollicitudin.</p>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc diam magna, molestie sit amet auctor nec, dictum quis mi. Duis pellentesque lacinia pretium. Donec pulvinar, risus sit amet dapibus mattis, eros urna bibendum elit, vel mollis sapien arcu
    vitae mi. Fusce vulputate vestibulum metus dapibus eleifend. Quisque ut dictum orci. Nunc bibendum, sapien ac condimentum placerat, arcu orci mollis nunc, vitae sollicitudin arcu nulla quis enim. Praesent non tellus vitae quam tempor maximus vel sed
    dolor. Donec id ante ultricies, iaculis sem ut, sollicitudin enim. Quisque id mauris est. Maecenas viverra urna vitae velit semper, vel ultricies augue feugiat. Pellentesque in libero porttitor, lacinia metus in, maximus nisi. Phasellus commodo ligula
    vel arcu iaculis hendrerit vitae vel diam. Sed sed lorem maximus, vestibulum leo ut, posuere libero. Donec arcu dui, euismod id aliquet sed, porttitor vitae elit.</p>
  <p>Sed aliquam eget justo sit amet dictum. Suspendisse potenti. In placerat orci quis vehicula vehicula. Proin tempor laoreet suscipit. Proin non nulla lacinia est ullamcorper maximus et a sem. Nulla at lacus rhoncus, malesuada ante in, imperdiet sem.
    Mauris convallis tristique metus in iaculis. Nulla laoreet ligula non interdum tincidunt. Morbi sed venenatis arcu, sed gravida est. Fusce malesuada ullamcorper lacus, in vulputate risus finibus non.</p>
  <p>Suspendisse sapien leo, auctor non ex vitae, volutpat laoreet tortor. Suspendisse sodales libero velit, sed pulvinar lectus feugiat vel. Sed erat eros, porttitor id enim nec, ornare hendrerit nibh. Phasellus at nisi lectus. Cras semper lobortis condimentum.
    Etiam nunc felis, vehicula vitae tincidunt pellentesque, pretium sit amet dui. Duis aliquet ultrices lacus eget efficitur. Ut imperdiet velit sed enim laoreet, sed semper libero hendrerit. Donec malesuada auctor sollicitudin.</p>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc diam magna, molestie sit amet auctor nec, dictum quis mi. Duis pellentesque lacinia pretium. Donec pulvinar, risus sit amet dapibus mattis, eros urna bibendum elit, vel mollis sapien arcu
    vitae mi. Fusce vulputate vestibulum metus dapibus eleifend. Quisque ut dictum orci. Nunc bibendum, sapien ac condimentum placerat, arcu orci mollis nunc, vitae sollicitudin arcu nulla quis enim. Praesent non tellus vitae quam tempor maximus vel sed
    dolor. Donec id ante ultricies, iaculis sem ut, sollicitudin enim. Quisque id mauris est. Maecenas viverra urna vitae velit semper, vel ultricies augue feugiat. Pellentesque in libero porttitor, lacinia metus in, maximus nisi. Phasellus commodo ligula
    vel arcu iaculis hendrerit vitae vel diam. Sed sed lorem maximus, vestibulum leo ut, posuere libero. Donec arcu dui, euismod id aliquet sed, porttitor vitae elit.</p>
  <p>Sed aliquam eget justo sit amet dictum. Suspendisse potenti. In placerat orci quis vehicula vehicula. Proin tempor laoreet suscipit. Proin non nulla lacinia est ullamcorper maximus et a sem. Nulla at lacus rhoncus, malesuada ante in, imperdiet sem.
    Mauris convallis tristique metus in iaculis. Nulla laoreet ligula non interdum tincidunt. Morbi sed venenatis arcu, sed gravida est. Fusce malesuada ullamcorper lacus, in vulputate risus finibus non.</p>
  <p>Suspendisse sapien leo, auctor non ex vitae, volutpat laoreet tortor. Suspendisse sodales libero velit, sed pulvinar lectus feugiat vel. Sed erat eros, porttitor id enim nec, ornare hendrerit nibh. Phasellus at nisi lectus. Cras semper lobortis condimentum.
    Etiam nunc felis, vehicula vitae tincidunt pellentesque, pretium sit amet dui. Duis aliquet ultrices lacus eget efficitur. Ut imperdiet velit sed enim laoreet, sed semper libero hendrerit. Donec malesuada auctor sollicitudin.</p>
</div>
_x000D_
_x000D_
_x000D_

batch script - read line by line

Try this:

@echo off
for /f "tokens=*" %%a in (input.txt) do (
  echo line=%%a
)
pause

because of the tokens=* everything is captured into %a

edit: to reply to your comment, you would have to do that this way:

@echo off
for /f "tokens=*" %%a in (input.txt) do call :processline %%a

pause
goto :eof

:processline
echo line=%*

goto :eof

:eof

Because of the spaces, you can't use %1, because that would only contain the part until the first space. And because the line contains quotes, you can also not use :processline "%%a" in combination with %~1. So you need to use %* which gets %1 %2 %3 ..., so the whole line.

How do you get a timestamp in JavaScript?

_x000D_
_x000D_
// The Current Unix Timestamp_x000D_
// 1443534720 seconds since Jan 01 1970. (UTC)_x000D_
_x000D_
// seconds_x000D_
console.log(Math.floor(new Date().valueOf() / 1000)); // 1443534720_x000D_
console.log(Math.floor(Date.now() / 1000)); // 1443534720_x000D_
console.log(Math.floor(new Date().getTime() / 1000)); // 1443534720_x000D_
_x000D_
// milliseconds_x000D_
console.log(Math.floor(new Date().valueOf())); // 1443534720087_x000D_
console.log(Math.floor(Date.now())); // 1443534720087_x000D_
console.log(Math.floor(new Date().getTime())); // 1443534720087_x000D_
_x000D_
// jQuery_x000D_
// seconds_x000D_
console.log(Math.floor($.now() / 1000)); // 1443534720_x000D_
// milliseconds_x000D_
console.log($.now()); // 1443534720087
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

HTML span align center not working?

A div is a block element, and will span the width of the container unless a width is set. A span is an inline element, and will have the width of the text inside it. Currently, you are trying to set align as a CSS property. Align is an attribute.

<span align="center" style="border:1px solid red;">
    This is some text in a div element!
</span>

However, the align attribute is deprecated. You should use the CSS text-align property on the container.

<div style="text-align: center;">
    <span style="border:1px solid red;">
        This is some text in a div element!
    </span>
</div>

Forward declaring an enum in C++

Just noting that the reason actually is that the size of the enum is not yet known after forward declaration. Well, you use forward declaration of a struct to be able to pass a pointer around or refer to an object from a place that's refered to in the forward declared struct definition itself too.

Forward declaring an enum would not be too useful, because one would wish to be able to pass around the enum by-value. You couldn't even have a pointer to it, because i recently got told some platforms use pointers of different size for char than for int or long. So it all depends on the content of the enum.

The current C++ Standard explicitly disallows doing something like

enum X;

(in 7.1.5.3/1). But the next C++ Standard due to next year allows the following, which convinced me the problem actually has to do with the underlying type:

enum X : int;

It's known as a "opaque" enum declaration. You can even use X by value in the following code. And its enumerators can later be defined in a later redeclaration of the enumeration. See 7.2 in the current working draft.

How do I create a Python function with optional arguments?

Try calling it like: obj.some_function( '1', 2, '3', g="foo", h="bar" ). After the required positional arguments, you can specify specific optional arguments by name.

Capture Video of Android's Screen

Take a look at Remote Manager. But seems to me it doesn't work correctly with devices which have big screen. Although, you can try DEMO before.

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

tick_params is very useful for setting tick properties. Labels can be moved to the top with:

    ax.tick_params(labelbottom=False,labeltop=True)

Excel VBA - Delete empty rows

How about

sub foo()
  dim r As Range, rows As Long, i As Long
  Set r = ActiveSheet.Range("A1:Z50")
  rows = r.rows.Count
  For i = rows To 1 Step (-1)
    If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
  Next
End Sub

Try this

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Range("A" & i & ":" & "Z" & i)
            Else
                Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

IF you want to delete the entire row then use this code

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Rows(i)
            Else
                Set DelRange = Union(DelRange, Rows(i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

How to quit android application programmatically

We want code that is robust and simple. This solution works on old devices and newer devices.

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        getActivity().finishAffinity();
    } else{
        getActivity().finish();
        System.exit( 0 );
    }

Delete a closed pull request from GitHub

There is no way you can delete a pull request yourself -- you and the repo owner (and all users with push access to it) can close it, but it will remain in the log. This is part of the philosophy of not denying/hiding what happened during development.

However, if there are critical reasons for deleting it (this is mainly violation of Github Terms of Service), Github support staff will delete it for you.

Whether or not they are willing to delete your PR for you is something you can easily ask them, just drop them an email at [email protected]

UPDATE: Currently Github requires support requests to be created here: https://support.github.com/contact

POST unchecked HTML checkboxes

I also like the solution that you just post an extra input field, using JavaScript seems a little hacky to me.

Depending on what you use for you backend will depend on which input goes first.

For a server backend where the first occurrence is used (JSP) you should do the following.

  <input type="checkbox" value="1" name="checkbox_1"/>
  <input type="hidden" value="0" name="checkbox_1"/>


For a server backend where the last occurrence is used (PHP,Rails) you should do the following.

  <input type="hidden" value="0" name="checkbox_1"/>
  <input type="checkbox" value="1" name="checkbox_1"/>


For a server backend where all occurrences are stored in a list data type ([],array). (Python / Zope)

You can post in which ever order you like, you just need to try to get the value from the input with the checkbox type attribute. So the first index of the list if the checkbox was before the hidden element and the last index if the checkbox was after the hidden element.


For a server backend where all occurrences are concatenated with a comma (ASP.NET / IIS) You will need to (split/explode) the string by using a comma as a delimiter to create a list data type. ([])

Now you can attempt to grab the first index of the list if the checkbox was before the hidden element and grab the last index if the checkbox was after the hidden element.

Backend parameter handling

image source

How to use ADB in Android Studio to view an SQLite DB

You can use a very nice tool called Stetho by adding this to build.gradle file:

compile 'com.facebook.stetho:stetho:1.4.1'

And initialized it inside your Application or Activity onCreate() method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Stetho.initializeWithDefaults(this);
    setContentView(R.layout.activity_main);
}

Then you can view the db records in chrome in the address:

chrome://inspect/#devices

For more details you can read my post: How to view easily your db records

Changing navigation title programmatically

Swift 5.1

// Set NavigationBar Title Programmatically and Dynamic

Note : First add NavigationControllerItem to Your ViewController then goto their ViewController.swift file and Just Copy and Paste this in viewDidLoad().

navigationItem.title = "Your Title Here"

Is an entity body allowed for an HTTP DELETE request?

Using DELETE with a Body is risky... I prefer this approach for List Operations over REST:

Regular Operations

GET /objects/ Gets all Objects

GET /object/ID Gets an Object with specified ID

POST /objects Adds a new Object

PUT /object/ID Adds an Object with specified ID, Updates an Object

DELETE /object/ID Deletes the object with specified ID

All Custom actions are POST

POST /objects/addList Adds a List or Array of Objects included in body

POST /objects/deleteList Deletes a List of Objects included in body

POST /objects/customQuery Creates a List based on custom query in body

If a client doesn't support your extended operations they can work in the regular way.

Convert UTF-8 with BOM to UTF-8 with no BOM in Python

You can use codecs.

import codecs
with open("test.txt",'r') as filehandle:
    content = filehandle.read()
if content[:3] == codecs.BOM_UTF8:
    content = content[3:]
print content.decode("utf-8")

How to set iPhone UIView z index?

We can use zPosition in ios

if we have a view named salonDetailView eg : @IBOutlet weak var salonDetailView: UIView!

In my case see the image

and have UIView for GMSMapView eg : @IBOutlet weak var mapViewUI: GMSMapView!

To show the View salonDetailView upper of the mapViewUI

use zPosition as below

salonDetailView.layer.zPosition = 1

What is the difference between dict.items() and dict.iteritems() in Python2?

In Py2.x

The commands dict.items(), dict.keys() and dict.values() return a copy of the dictionary's list of (k, v) pair, keys and values. This could take a lot of memory if the copied list is very large.

The commands dict.iteritems(), dict.iterkeys() and dict.itervalues() return an iterator over the dictionary’s (k, v) pair, keys and values.

The commands dict.viewitems(), dict.viewkeys() and dict.viewvalues() return the view objects, which can reflect the dictionary's changes. (I.e. if you del an item or add a (k,v) pair in the dictionary, the view object can automatically change at the same time.)

$ python2.7

>>> d = {'one':1, 'two':2}
>>> type(d.items())
<type 'list'>
>>> type(d.keys())
<type 'list'>
>>> 
>>> 
>>> type(d.iteritems())
<type 'dictionary-itemiterator'>
>>> type(d.iterkeys())
<type 'dictionary-keyiterator'>
>>> 
>>> 
>>> type(d.viewitems())
<type 'dict_items'>
>>> type(d.viewkeys())
<type 'dict_keys'>

While in Py3.x

In Py3.x, things are more clean, since there are only dict.items(), dict.keys() and dict.values() available, which return the view objects just as dict.viewitems() in Py2.x did.

But

Just as @lvc noted, view object isn't the same as iterator, so if you want to return an iterator in Py3.x, you could use iter(dictview) :

$ python3.3

>>> d = {'one':'1', 'two':'2'}
>>> type(d.items())
<class 'dict_items'>
>>>
>>> type(d.keys())
<class 'dict_keys'>
>>>
>>>
>>> ii = iter(d.items())
>>> type(ii)
<class 'dict_itemiterator'>
>>>
>>> ik = iter(d.keys())
>>> type(ik)
<class 'dict_keyiterator'>

How best to determine if an argument is not sent to the JavaScript function

There are several different ways to check if an argument was passed to a function. In addition to the two you mentioned in your (original) question - checking arguments.length or using the || operator to provide default values - one can also explicitly check the arguments for undefined via argument2 === undefined or typeof argument2 === 'undefined' if one is paranoid (see comments).

Using the || operator has become standard practice - all the cool kids do it - but be careful: The default value will be triggered if the argument evaluates to false, which means it might actually be undefined, null, false, 0, '' (or anything else for which Boolean(...) returns false).

So the question is when to use which check, as they all yield slightly different results.

Checking arguments.length exhibits the 'most correct' behaviour, but it might not be feasible if there's more than one optional argument.

The test for undefined is next 'best' - it only 'fails' if the function is explicitly called with an undefined value, which in all likelyhood should be treated the same way as omitting the argument.

The use of the || operator might trigger usage of the default value even if a valid argument is provided. On the other hand, its behaviour might actually be desired.

To summarize: Only use it if you know what you're doing!

In my opinion, using || is also the way to go if there's more than one optional argument and one doesn't want to pass an object literal as a workaround for named parameters.

Another nice way to provide default values using arguments.length is possible by falling through the labels of a switch statement:

function test(requiredArg, optionalArg1, optionalArg2, optionalArg3) {
    switch(arguments.length) {
        case 1: optionalArg1 = 'default1';
        case 2: optionalArg2 = 'default2';
        case 3: optionalArg3 = 'default3';
        case 4: break;
        default: throw new Error('illegal argument count')
    }
    // do stuff
}

This has the downside that the programmer's intention is not (visually) obvious and uses 'magic numbers'; it is therefore possibly error prone.

Returning a promise in an async function in TypeScript

When you do new Promise((resolve)... the type inferred was Promise<{}> because you should have used new Promise<number>((resolve).

It is interesting that this issue was only highlighted when the async keyword was added. I would recommend reporting this issue to the TS team on GitHub.

There are many ways you can get around this issue. All the following functions have the same behavior:

const whatever1 = () => {
    return new Promise<number>((resolve) => {
        resolve(4);
    });
};

const whatever2 = async () => {
    return new Promise<number>((resolve) => {
        resolve(4);
    });
};

const whatever3 = async () => {
    return await new Promise<number>((resolve) => {
        resolve(4);
    });
};

const whatever4 = async () => {
    return Promise.resolve(4);
};

const whatever5 = async () => {
    return await Promise.resolve(4);
};

const whatever6 = async () => Promise.resolve(4);

const whatever7 = async () => await Promise.resolve(4);

In your IDE you will be able to see that the inferred type for all these functions is () => Promise<number>.

Displaying Total in Footer of GridView and also Add Sum of columns(row vise) in last Column

/*This code will use gridview sum inside data list*/
SumOFdata(grd_DataDetail);

  private void SumOFEPFWages(GridView grd)
    {
        Label lbl_TotAmt = (Label)grd.FooterRow.FindControl("lblTotGrossW");
        /*Sum of the total Amount of the day*/
        foreach (GridViewRow gvr in grd.Rows)
        {
            Label lbl_Amount = (Label)gvr.FindControl("lblGrossS");
            lbl_TotAmt.Text = (Convert.ToDouble(lbl_Amount.Text) + Convert.ToDouble(lbl_TotAmt.Text)).ToString();
        }

    }

How to Set Variables in a Laravel Blade Template

There is a simple workaround that doesn't require you to change any code, and it works in Laravel 4 just as well.

You just use an assignment operator (=) in the expression passed to an @if statement, instead of (for instance) an operator such as ==.

@if ($variable = 'any data, be it string, variable or OOP') @endif

Then you can use it anywhere you can use any other variable

{{ $variable }}

The only downside is your assignment will look like a mistake to someone not aware that you're doing this as a workaround.

Converting dict to OrderedDict

You are creating a dictionary first, then passing that dictionary to an OrderedDict. For Python versions < 3.6 (*), by the time you do that, the ordering is no longer going to be correct. dict is inherently not ordered.

Pass in a sequence of tuples instead:

ship = [("NAME", "Albatross"),
        ("HP", 50),
        ("BLASTERS", 13),
        ("THRUSTERS", 18),
        ("PRICE", 250)]
ship = collections.OrderedDict(ship)

What you see when you print the OrderedDict is it's representation, and it is entirely correct. OrderedDict([('PRICE', 250), ('HP', 50), ('NAME', 'Albatross'), ('BLASTERS', 13), ('THRUSTERS', 18)]) just shows you, in a reproducable representation, what the contents are of the OrderedDict.


(*): In the CPython 3.6 implementation, the dict type was updated to use a more memory efficient internal structure that has the happy side effect of preserving insertion order, and by extension the code shown in the question works without issues. As of Python 3.7, the Python language specification has been updated to require that all Python implementations must follow this behaviour. See this other answer of mine for details and also why you'd still may want to use an OrderedDict() for certain cases.

how to draw a rectangle in HTML or CSS?

In the HTML page you have to to put your css code between the tags, while in the body a div which has as id rectangle. Here the code:

<!doctype>
<html>
<head>
<style>
#rectangle 
{
   all your css code
}
</style>
</head>
<body>
<div id="rectangle"></div>
</body>
</html>

Dynamically access object property using variable

Access dynamic object properties in js we can use bracket notation.

const something = { 
  bar: "Foobar!" 
};
const foo = 'bar';

console.log(something[foo]); // "Foobar!"

Adding a simple spacer to twitter bootstrap

In Bootstrap 4 you can use classes like mt-5, mb-5, my-5, mx-5 (y for both top and bottom, x for both left and right).

According to their site:

The classes are named using the format {property}{sides}-{size} for xs and {property}{sides}-{breakpoint}-{size} for sm, md, lg, and xl.

Link: https://getbootstrap.com/docs/4.0/utilities/spacing/

Insert node at a certain position in a linked list C++

 void addToSpecific()
 {
 int n;   
 int f=0;   //flag
 Node *temp=H;    //H-Head, T-Tail
 if(NULL!=H)  
 {
    cout<<"Enter the Number"<<endl;
    cin>>n;
    while(NULL!=(temp->getNext()))
    {
       if(n==(temp->getInfo()))
       {
      f=1;
      break;
       }
       temp=temp->getNext();
    }
 }
 if(NULL==H)
 {
    Node *nn=new Node();
    nn->setInfo();
    nn->setNext(NULL);
    T=H=nn;
 }
 else if(0==f)
 {
    Node *nn=new Node();
    nn->setInfo();
    nn->setNext(NULL);
    T->setNext(nn);
    T=nn;
 }
 else if(1==f)
 {
    Node *nn=new Node();
    nn->setInfo();
    nn->setNext(NULL);
    nn->setNext((temp->getNext()));
    temp->setNext(nn);
 }
 }

trying to animate a constraint in swift

It's very important to point out that view.layoutIfNeeded() applies to the view subviews only.

Therefore to animate the view constraint, it is important to call it on the view-to-animate superview as follows:

    topConstraint.constant = heightShift

    UIView.animate(withDuration: 0.3) {

        // request layout on the *superview*
        self.view.superview?.layoutIfNeeded()
    }

An example for a simple layout as follows:

class MyClass {

    /// Container view
    let container = UIView()
        /// View attached to container
        let view = UIView()

    /// Top constraint to animate
    var topConstraint = NSLayoutConstraint()


    /// Create the UI hierarchy and constraints
    func createUI() {
        container.addSubview(view)

        // Create the top constraint
        topConstraint = view.topAnchor.constraint(equalTo: container.topAnchor, constant: 0)


        view.translatesAutoresizingMaskIntoConstraints = false

        // Activate constaint(s)
        NSLayoutConstraint.activate([
           topConstraint,
        ])
    }

    /// Update view constraint with animation
    func updateConstraint(heightShift: CGFloat) {
        topConstraint.constant = heightShift

        UIView.animate(withDuration: 0.3) {

            // request layout on the *superview*
            self.view.superview?.layoutIfNeeded()
        }
    }
}

CSS3 equivalent to jQuery slideUp and slideDown?

Aight fam, after some research and experimenting, I think the best approach is to have the thing's height at 0px, and let it transition to an exact height. You get the exact height with JavaScript. The JavaScript isn't doing the animating, it's just changing the height value. Check it:

function setInfoHeight() {
  $(window).on('load resize', function() {
    $('.info').each(function () {
      var current = $(this);
      var closed = $(this).height() == 0;
      current.show().height('auto').attr('h', current.height() );
      current.height(closed ? '0' : current.height());
    });
  });

Whenever the page loads or is resized, the element with class info will get its h attribute updated. Then you could have a button trigger the style="height: __" to set it to that previously set h value.

function moreInformation() {
  $('.icon-container').click(function() {
    var info = $(this).closest('.dish-header').next('.info'); // Just the one info
    var icon = $(this).children('.info-btn'); // Select the logo

    // Stop any ongoing animation loops. Without this, you could click button 10
    // times real fast, and watch an animation of the info showing and closing
    // for a few seconds after
    icon.stop();
    info.stop();

    // Flip icon and hide/show info
    icon.toggleClass('flip');

    // Metnod 1, animation handled by JS
    // info.slideToggle('slow');

    // Method 2, animation handled by CSS, use with setInfoheight function
    info.toggleClass('active').height(icon.is('.flip') ? info.attr('h') : '0');

  });
};

Here's the styling for the info class.

.info {
  display: inline-block;
  height: 0px;
  line-height: 1.5em;
  overflow: hidden;
  padding: 0 1em;
  transition: height 0.6s, padding 0.6s;
  &.active {
    border-bottom: $thin-line;
    padding: 1em;
  }
}

I used this on one of my projects so class names are specific. You can change them up however you like.

The styling might not be supported cross-browser. Works fine in chrome.

Below is the live example for this code. Just click on the ? icon to start the animation

CodePen

Select a row from html table and send values onclick of a button

In my case $(document).ready(function() was missing. Try this.

$(document).ready(function(){   
("#table tr").click(function(){
       $(this).addClass('selected').siblings().removeClass('selected');    
       var value=$(this).find('td:first').html();
       alert(value);    
    });
    $('.ok').on('click', function(e){
        alert($("#table tr.selected td:first").html());
    });
});

Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null

Got the answer: I should not use parentheses after return (). This works:

return  <div> <Search_Bar /> </div>

If you want to write multiline, then return ( ...

Your starting parenthesis should be on the same line as return.

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

For Boto3 , use this code.

import boto3
from botocore.client import Config


s3 = boto3.resource('s3',
        aws_access_key_id='xxxxxx',
        aws_secret_access_key='xxxxxx',
        region_name='us-south-1',
        config=Config(signature_version='s3v4')
        )

How to configure Visual Studio to use Beyond Compare

BComp.exe works in multiple-tabbed scenario as well, so there is no need to add /solo unless you really want separate windows for each file comparison. Tested/verified on Beyond Compare 3 and 4. Moral: use BComp.exe, not BCompare.exe, for VS external compare tool configuration.

HTML 5 Favicon - Support?

No, not all browsers support the sizes attribute:

Note that some platforms define specific sizes:

Angular2 handling http response

in angular2 2.1.1 I was not able to catch the exception using the (data),(error) pattern, so I implemented it using .catch(...).

It's nice because it can be used with all other Observable chained methods like .retry .map etc.

import {Observable} from 'rxjs/Rx';


  Http
  .put(...)
  .catch(err =>  { 
     notify('UI error handling');
     return Observable.throw(err); // observable needs to be returned or exception raised
  })
  .subscribe(data => ...) // handle success

from documentation:

Returns

(Observable): An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.

How do I center a window onscreen in C#?

Use this:

this.CenterToScreen();  // This will take care of the current form

How to find what code is run by a button or element in Chrome using Developer Tools

Solution 1: Framework blackboxing

Works great, minimal setup and no third parties.

According to Chrome's documentation:

What happens when you blackbox a script?

Exceptions thrown from library code will not pause (if Pause on exceptions is enabled), Stepping into/out/over bypasses the library code, Event listener breakpoints don't break in library code, The debugger will not pause on any breakpoints set in library code. The end result is you are debugging your application code instead of third party resources.

Here's the updated workflow:
  1. Pop open Chrome Developer Tools (F12 or ?+?+i), go to settings (upper right, or F1). Find a tab on the left called "Blackboxing"

enter image description here

  1. This is where you put the RegEx pattern of the files you want Chrome to ignore while debugging. For example: jquery\..*\.js (glob pattern/human translation: jquery.*.js)
  2. If you want to skip files with multiple patterns you can add them using the pipe character, |, like so: jquery\..*\.js|include\.postload\.js (which acts like an "or this pattern", so to speak. Or keep adding them with the "Add" button.
  3. Now continue to Solution 3 described down below.

Bonus tip! I use Regex101 regularly (but there are many others: ) to quickly test my rusty regex patterns and find out where I'm wrong with the step-by-step regex debugger. If you are not yet "fluent" in Regular Expressions I recommend you start using sites that help you write and visualize them such as http://buildregex.com/ and https://www.debuggex.com/

You can also use the context menu when working in the Sources panel. When viewing a file, you can right-click in the editor and choose Blackbox Script. This will add the file to the list in the Settings panel:

enter image description here


Solution 2: Visual Event

enter image description here

It's an excellent tool to have:

Visual Event is an open-source Javascript bookmarklet which provides debugging information about events that have been attached to DOM elements. Visual Event shows:

  • Which elements have events attached to them
  • The type of events attached to an element
  • The code that will be run with the event is triggered
  • The source file and line number for where the attached function was defined (Webkit browsers and Opera only)


Solution 3: Debugging

You can pause the code when you click somewhere in the page, or when the DOM is modified... and other kinds of JS breakpoints that will be useful to know. You should apply blackboxing here to avoid a nightmare.

In this instance, I want to know what exactly goes on when I click the button.

  1. Open Dev Tools -> Sources tab, and on the right find Event Listener Breakpoints:

    enter image description here

  2. Expand Mouse and select click

  3. Now click the element (execution should pause), and you are now debugging the code. You can go through all code pressing F11 (which is Step in). Or go back a few jumps in the stack. There can be a ton of jumps


Solution 4: Fishing keywords

With Dev Tools activated, you can search the whole codebase (all code in all files) with ?+?+F or:

enter image description here

and searching #envio or whatever the tag/class/id you think starts the party and you may get somewhere faster than anticipated.

Be aware sometimes there's not only an img but lots of elements stacked, and you may not know which one triggers the code.


If this is a bit out of your knowledge, take a look at Chrome's tutorial on debugging.

Most Pythonic way to provide global configuration variables in config.py?

Similar to blubb's answer. I suggest building them with lambda functions to reduce code. Like this:

User = lambda passwd, hair, name: {'password':passwd, 'hair':hair, 'name':name}

#Col      Username       Password      Hair Color  Real Name
config = {'st3v3' : User('password',   'blonde',   'Steve Booker'),
          'blubb' : User('12345678',   'black',    'Bubb Ohaal'),
          'suprM' : User('kryptonite', 'black',    'Clark Kent'),
          #...
         }
#...

config['st3v3']['password']  #> password
config['blubb']['hair']      #> black

This does smell like you may want to make a class, though.

Or, as MarkM noted, you could use namedtuple

from collections import namedtuple
#...

User = namedtuple('User', ['password', 'hair', 'name']}

#Col      Username       Password      Hair Color  Real Name
config = {'st3v3' : User('password',   'blonde',   'Steve Booker'),
          'blubb' : User('12345678',   'black',    'Bubb Ohaal'),
          'suprM' : User('kryptonite', 'black',    'Clark Kent'),
          #...
         }
#...

config['st3v3'].password   #> passwd
config['blubb'].hair       #> black

Online SQL syntax checker conforming to multiple databases

You could try a formatter like this

They will always be limited because they don't (and can't) know what user defined functions you may have defined in your database (or which built-in functions you have or don't have access to).

You could also look at ANTLR (but that would be an offline solution)

Accessing the index in 'for' loops?

for i in range(len(ints)):
   print i, ints[i]

Select from table by knowing only date without time (ORACLE)

You could use the between function to get all records between 2010-08-03 00:00:00:000 AND 2010-08-03 23:59:59:000

Setting Custom ActionBar Title from Fragment

Use the following:

getActivity().setTitle("YOUR_TITLE");

Where is Ubuntu storing installed programs?

Simply, type the command:

~$ whereis "program name"

python pip: force install ignoring dependencies

pip has a --no-dependencies switch. You should use that.

For more information, run pip install -h, where you'll see this line:

--no-deps, --no-dependencies
                        Ignore package dependencies

Python: Append item to list N times

For immutable data types:

l = [0] * 100
# [0, 0, 0, 0, 0, ...]

l = ['foo'] * 100
# ['foo', 'foo', 'foo', 'foo', ...]

For values that are stored by reference and you may wish to modify later (like sub-lists, or dicts):

l = [{} for x in range(100)]

(The reason why the first method is only a good idea for constant values, like ints or strings, is because only a shallow copy is does when using the <list>*<number> syntax, and thus if you did something like [{}]*100, you'd end up with 100 references to the same dictionary - so changing one of them would change them all. Since ints and strings are immutable, this isn't a problem for them.)

If you want to add to an existing list, you can use the extend() method of that list (in conjunction with the generation of a list of things to add via the above techniques):

a = [1,2,3]
b = [4,5,6]
a.extend(b)
# a is now [1,2,3,4,5,6]

Reading value from console, interactively

@rob answer will work most of the times, but it might not work as you expect with long inputs.

That is what you should be using instead:

const stdin = process.openStdin();
let content = '';

stdin.addListener('data', d => {
  content += d.toString();
});

stdin.addListener('end', () => {
  console.info(`Input: ${content}`);
});

Explanation on why this solution works:

addListener('data') works like a buffer, callback will be called when it is full or/and its the end of input.

What about long inputs? A single 'data' callback will not be enough, hence it you will get your input split in two or more parts. That is often not convenient.

addListener('end') will notify us when the stdin reader is done reading our input. Since we have been storing the previous data, we can now read and process it all together.

How to run a shell script in OS X by double-clicking?

Alternatively, you could create a regular Mac OS X application from your script using Platypus

Woocommerce, get current product id

your can query woocommerce programatically you can even add a product to your shopping cart. I'm sure you can figure out how to interact with woocommerce cart once you read the code. how to interact with woocommerce cart programatically

====================================

<?php

add_action('wp_loaded', 'add_product_to_cart');
function add_product_to_cart()
{
    global $wpdb;

    if (!is_admin()) {


        $product_id = wc_get_product_id_by_sku('L3-670115');

        $found = false;

        if (is_user_logged_in()) {
            if (sizeof(WC()->cart->get_cart()) > 0) {
                foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
                    $_product = $values['data'];
                    if ($_product->get_id() == $product_id)
                        WC()->cart->remove_cart_item($cart_item_key);
                }
            }
        } else {
            if (sizeof(WC()->cart->get_cart()) > 0) {
                foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
                    $_product = $values['data'];
                    if ($_product->id == $product_id)
                        $found = true;
                }
                // if product not found, add it
                if (!$found)
                    WC()->cart->add_to_cart($product_id);
            } else {
                // if no products in cart, add it
                WC()->cart->add_to_cart($product_id);
            }
        }
    }
}

sql primary key and index

Declaring a PRIMARY KEY or UNIQUE constraint causes SQL Server to automatically create an index.

An unique index can be created without matching a constraint, but a constraint (either primary key or unique) cannot exist without having a unique index.

From here, the creation of a constraint will:

  • cause an index with the same name to be created
  • deny dropping the created index as constraint is not allowed to exists without it

and at the same time dropping the constraint will drop the associated index.

So, is there actual difference between a PRIMARY KEY or UNIQUE INDEX:

  • NULL values are not allowed in PRIMARY KEY, but allowed in UNIQUE index; and like in set operators (UNION, EXCEPT, INTERSECT), here NULL = NULL which means that you can have only one value as two NULLs are find as duplicates of each other;
  • only one PRIMARY KEY may exists per table while 999 unique indexes can be created
  • when PRIMARY KEY constraint is created, it is created as clustered unless there is already a clustered index on the table or NONCLUSTERED is used in its definition; when UNIQUE index is created, it is created as NONCLUSTERED unless it is not specific to be CLUSTERED and such already does not exist;

How to use "not" in xpath?

not() is a function in xpath (as opposed to an operator), so

//a[not(contains(@id, 'xx'))]

How to know user has clicked "X" or the "Close" button?

I've done something like this.

private void Form_FormClosing(object sender, FormClosingEventArgs e)
    {
        if ((sender as Form).ActiveControl is Button)
        {
            //CloseButton
        }
        else
        {
            //The X has been clicked
        }
    }

node.js shell command execution

@TonyO'Hagan is comprehrensive shelljs answer, but, I would like to highlight the synchronous version of his answer:

var shell = require('shelljs');
var output = shell.exec('netstat -rn', {silent:true}).output;
console.log(output);

Get the Query Executed in Laravel 3/4

If you are using Laravel 5 you need to insert this before query or on middleware :

\DB::enableQueryLog();

Remove all subviews?

Using Swift UIView extension:

extension UIView {
    func removeAllSubviews() {
        for subview in subviews {
            subview.removeFromSuperview()
        }
    }
}

How can I align text directly beneath an image?

Your HTML:

<div class="img-with-text">
    <img src="yourimage.jpg" alt="sometext" />
    <p>Some text</p>
</div>

If you know the width of your image, your CSS:

.img-with-text {
    text-align: justify;
    width: [width of img];
}

.img-with-text img {
    display: block;
    margin: 0 auto;
}

Otherwise your text below the image will free-flow. To prevent this, just set a width to your container.

How to install a plugin in Jenkins manually

The accepted answer is accurate, but make sure that you also install all necessary dependencies as well. Installing using the CLI or web seems to take care of this, but my plugins were not showing up in the browser or using java -jar jenkins-cli.jar -s http://localhost:8080 list-plugins until I also installed the dependencies.

How do I test if a string is empty in Objective-C?

The first approach is valid, but doesn't work if your string has blank spaces (@" "). So you must clear this white spaces before testing it.

This code clear all the blank spaces on both sides of the string:

[stringObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ];

One good idea is create one macro, so you don't have to type this monster line:

#define allTrim( object ) [object stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ]

Now you can use:

NSString *emptyString = @"   ";

if ( [allTrim( emptyString ) length] == 0 ) NSLog(@"Is empty!");

Format an Integer using Java String Format

String.format("%03d", 1)  // => "001"
//              ¦¦¦   +-- print the number one
//              ¦¦+------ ... as a decimal integer
//              ¦+------- ... minimum of 3 characters wide
//              +-------- ... pad with zeroes instead of spaces

See java.util.Formatter for more information.

SQL Server stored procedure parameters

You are parsing wrong parameter combination.here you passing @TaskName = and @ID instead of @TaskName = .SP need only one parameter.

MySQL stored procedure vs function, which would I use when?

Stored procedure can be called recursively but stored function can not

Is there a java setting for disabling certificate validation?

It is very simple .In my opinion it is the best way for everyone

       Unirest.config().verifySsl(false);
       HttpResponse<String> response = null;
       try {
           Gson gson = new Gson();
           response = Unirest.post("your_api_url")
                   .header("Authorization", "Basic " + "authkey")
                   .header("Content-Type", "application/json")
                   .body("request_body")
                   .asString();
           System.out.println("------RESPONSE -------"+ gson.toJson(response.getBody()));
       } catch (Exception e) {
           System.out.println("------RESPONSE ERROR--");
           e.printStackTrace();
       }
   }

How to find and return a duplicate value in array

Here is my take on it on a big set of data - such as a legacy dBase table to find duplicate parts

# Assuming ps is an array of 20000 part numbers & we want to find duplicates
# actually had to it recently.
# having a result hash with part number and number of times part is 
# duplicated is much more convenient in the real world application
# Takes about 6  seconds to run on my data set
# - not too bad for an export script handling 20000 parts

h = {};

# or for readability

h = {} # result hash
ps.select{ |e| 
  ct = ps.count(e) 
  h[e] = ct if ct > 1
}; nil # so that the huge result of select doesn't print in the console

Best way to check if column returns a null value (from database to .net application)

Just check for

if(table.rows[0][0] == null)
{
     //Whatever I want to do
}

or you could

if(t.Rows[0].IsNull(0))
{
     //Whatever I want to do
}

Increasing the maximum post size

You can specify both max post size and max file size limit in php.ini

post_max_size = 64M
upload_max_filesize = 64M

Display an array in a readable/hierarchical format

Instead of

print_r($data);

try

print "<pre>";
print_r($data);
print "</pre>";

How to JOIN three tables in Codeigniter

Try as follows:

public function funcname($id)
{
    $this->db->select('*');
    $this->db->from('Album a'); 
    $this->db->join('Category b', 'b.cat_id=a.cat_id', 'left');
    $this->db->join('Soundtrack c', 'c.album_id=a.album_id', 'left');
    $this->db->where('c.album_id',$id);
    $this->db->order_by('c.track_title','asc');         
    $query = $this->db->get(); 
    return $query->result_array();
}

If no result found CI returns false otherwise true

How to Convert Int to Unsigned Byte and Back

Java 8 provides Byte.toUnsignedInt to convert byte to int by unsigned conversion. In Oracle's JDK this is simply implemented as return ((int) x) & 0xff; because HotSpot already understands how to optimize this pattern, but it could be intrinsified on other VMs. More importantly, no prior knowledge is needed to understand what a call to toUnsignedInt(foo) does.

In total, Java 8 provides methods to convert byte and short to unsigned int and long, and int to unsigned long. A method to convert byte to unsigned short was deliberately omitted because the JVM only provides arithmetic on int and long anyway.

To convert an int back to a byte, just use a cast: (byte)someInt. The resulting narrowing primitive conversion will discard all but the last 8 bits.

Finalize vs Dispose

There're some keys about from the book MCSD Certification Toolkit (exam 70-483) pag 193:

destructor ˜(it's almost equal to) base.Finalize(), The destructor is converted into an override version of the Finalize method that executes the destructor’s code and then calls the base class’s Finalize method. Then its totally non deterministic you can't able to know when will be called because depends on GC.

If a class contains no managed resources and no unmanaged resources, it shouldn't implement IDisposable or have a destructor.

If the class has only managed resources, it should implement IDisposable but it shouldn't have a destructor. (When the destructor executes, you can’t be sure managed objects still exist, so you can’t call their Dispose() methods anyway.)

If the class has only unmanaged resources, it needs to implement IDisposable and needs a destructor in case the program doesn’t call Dispose().

Dispose() method must be safe to run more than once. You can achieve that by using a variable to keep track of whether it has been run before.

Dispose() should free both managed and unmanaged resources.

The destructor should free only unmanaged resources. When the destructor executes, you can’t be sure managed objects still exist, so you can’t call their Dispose methods anyway. This is obtained by using the canonical protected void Dispose(bool disposing) pattern, where only managed resources are freed (disposed) when disposing == true.

After freeing resources, Dispose() should call GC.SuppressFinalize, so the object can skip the finalization queue.

An Example of a an implementation for a class with unmanaged and managed resources:

using System;

class DisposableClass : IDisposable
{
    // A name to keep track of the object.
    public string Name = "";

    // Free managed and unmanaged resources.
    public void Dispose()
    {
        FreeResources(true);

        // We don't need the destructor because
        // our resources are already freed.
        GC.SuppressFinalize(this);
    }

    // Destructor to clean up unmanaged resources
    // but not managed resources.
    ~DisposableClass()
    {
        FreeResources(false);
    }

    // Keep track if whether resources are already freed.
    private bool ResourcesAreFreed = false;

    // Free resources.
    private void FreeResources(bool freeManagedResources)
    {
        Console.WriteLine(Name + ": FreeResources");
        if (!ResourcesAreFreed)
        {
            // Dispose of managed resources if appropriate.
            if (freeManagedResources)
            {
                // Dispose of managed resources here.
                Console.WriteLine(Name + ": Dispose of managed resources");
            }

            // Dispose of unmanaged resources here.
            Console.WriteLine(Name + ": Dispose of unmanaged resources");

            // Remember that we have disposed of resources.
            ResourcesAreFreed = true;
        }
    }
}

MySQL "CREATE TABLE IF NOT EXISTS" -> Error 1050

Create mysql connection with following parameter. "'raise_on_warnings': False". It will ignore the warning. e.g.

config = {'user': 'user','password': 'passwd','host': 'localhost','database': 'db',   'raise_on_warnings': False,}
cnx = mysql.connector.connect(**config)

Prevent Caching in ASP.NET MVC for specific actions using an attribute

In the controller action append to the header the following lines

    public ActionResult Create(string PositionID)
    {
        Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
        Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.
        Response.AppendHeader("Expires", "0"); // Proxies.

How to customise file type to syntax associations in Sublime Text?

for ST3

$language = "language u wish"

if exists,

go to ~/.config/sublime-text-3/Packages/User/$language.sublime-settings

else

create ~/.config/sublime-text-3/Packages/User/$language.sublime-settings

and set

{ "extensions": [ "yourextension" ] }

This way allows you to enable syntax for composite extensions (e.g. sql.mustache, js.php, etc ... )

Android - R cannot be resolved to a variable

check your R directory ...sometimes if a file name is not all lower case and has special characters you can get this error. Im using eclipse and it only accepts file names a-z0-9_.

How can I open a popup window with a fixed size using the HREF tag?

I can't comment on Esben Skov Pedersen's answer directly, but using the following notation for links:

<a href="javascript:window.open('http://www.websiteofyourchoice.com');">Click here</a>

In Internet Explorer, the new browser window appears, but the current window navigates to a page which says "[Object]". To avoid this, simple put a "void(0)" behind the JavaScript function.

Source: https://support.microsoft.com/en-us/kb/257321

Oracle pl-sql escape character (for a " ' ")

SELECT q'[Alex's Tea Factory]' FROM DUAL

How to use a parameter in ExecStart command line?

To attempt command line arguments directly is not possible.

One alternative might be environment variables (https://superuser.com/questions/728951/systemd-giving-my-service-multiple-arguments).

This is where I found the answer: http://www.freedesktop.org/software/systemd/man/systemctl.html

so sudo systemctl restart myprog -v -- systemctl will think you're trying to set one of its flags, not myprog's flag.

sudo systemctl restart myprog someotheroption -- systemctl will restart myprog and the someotheroption service, if it exists.

How to return more than one value from a function in Python?

You separate the values you want to return by commas:

def get_name():
   # you code
   return first_name, last_name

The commas indicate it's a tuple, so you could wrap your values by parentheses:

return (first_name, last_name)

Then when you call the function you a) save all values to one variable as a tuple, or b) separate your variable names by commas

name = get_name() # this is a tuple
first_name, last_name = get_name()
(first_name, last_name) = get_name() # You can put parentheses, but I find it ugly

Android Left to Right slide animation

I was not able to find any solution for this type of animation using ViewPropertyAnimator.

Here's an example:

Layout:

<FrameLayout
android:id="@+id/child_view_container"
android:layout_width="match_parent"
android:layout_height="wrap_content">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/child_view"
        android:gravity="center_horizontal"
        android:layout_gravity="center_horizontal"
    />
</FrameLayout>

Animate - Right to left and exit view:

final childView = findViewById(R.id.child_view);
View containerView = findViewById(R.id.child_view_container);
childView.animate()
  .translationXBy(-containerView.getWidth())
  .setDuration(TRANSLATION_DURATION)
  .setInterpolator(new AccelerateDecelerateInterpolator())
  .setListener(new AnimatorListenerAdapter() {
    @Override
    public void onAnimationEnd(Animator animation) {
        childView.setVisibility(View.GONE);
    }
});

Animate - Right to left enter view:

final View childView = findViewById(R.id.child_view);
View containerView = findViewById(R.id.child_view_container);
childView.setTranslationX(containerView.getWidth());
childView.animate()
    .translationXBy(-containerView.getWidth())
    .setDuration(TRANSLATION_DURATION)
    .setInterpolator(new AccelerateDecelerateInterpolator())
    .setListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationStart(Animator animation) {
            childView.setVisibility(View.VISIBLE);
        }
    });

How to get the URL of the current page in C#

a tip for people who needs the path/url in global.asax file;

If you need to run this in global.asax > Application_Start and you app pool mode is integrated then you will receive the error below:

Request is not available in this context exception in Application_Start.

In that case you need to use this:

System.Web.HttpRuntime.AppDomainAppVirtualPath

Hope will help others..

.NET Format a string with fixed spaces

try this:

"String goes here".PadLeft(20,' ');
"String goes here".PadRight(20,' ');

for the center get the length of the string and do padleft and padright with the necessary characters

int len = "String goes here".Length;
int whites = len /2;
"String goes here".PadRight(len + whites,' ').PadLeft(len + whites,' ');

Rename specific column(s) in pandas

There are at least five different ways to rename specific columns in pandas, and I have listed them below along with links to the original answers. I also timed these methods and found them to perform about the same (though YMMV depending on your data set and scenario). The test case below is to rename columns A M N Z to A2 M2 N2 Z2 in a dataframe with columns A to Z containing a million rows.

# Import required modules
import numpy as np
import pandas as pd
import timeit

# Create sample data
df = pd.DataFrame(np.random.randint(0,9999,size=(1000000, 26)), columns=list('ABCDEFGHIJKLMNOPQRSTUVWXYZ'))

# Standard way - https://stackoverflow.com/a/19758398/452587
def method_1():
    df_renamed = df.rename(columns={'A': 'A2', 'M': 'M2', 'N': 'N2', 'Z': 'Z2'})

# Lambda function - https://stackoverflow.com/a/16770353/452587
def method_2():
    df_renamed = df.rename(columns=lambda x: x + '2' if x in ['A', 'M', 'N', 'Z'] else x)

# Mapping function - https://stackoverflow.com/a/19758398/452587
def rename_some(x):
    if x=='A' or x=='M' or x=='N' or x=='Z':
        return x + '2'
    return x
def method_3():
    df_renamed = df.rename(columns=rename_some)

# Dictionary comprehension - https://stackoverflow.com/a/58143182/452587
def method_4():
    df_renamed = df.rename(columns={col: col + '2' for col in df.columns[
        np.asarray([i for i, col in enumerate(df.columns) if 'A' in col or 'M' in col or 'N' in col or 'Z' in col])
    ]})

# Dictionary comprehension - https://stackoverflow.com/a/38101084/452587
def method_5():
    df_renamed = df.rename(columns=dict(zip(df[['A', 'M', 'N', 'Z']], ['A2', 'M2', 'N2', 'Z2'])))

print('Method 1:', timeit.timeit(method_1, number=10))
print('Method 2:', timeit.timeit(method_2, number=10))
print('Method 3:', timeit.timeit(method_3, number=10))
print('Method 4:', timeit.timeit(method_4, number=10))
print('Method 5:', timeit.timeit(method_5, number=10))

Output:

Method 1: 3.650640267
Method 2: 3.163998427
Method 3: 2.998530871
Method 4: 2.9918436889999995
Method 5: 3.2436501520000007

Use the method that is most intuitive to you and easiest for you to implement in your application.

PHP: Read Specific Line From File

You have to loop the file till end of file.

  while(!feof($file))
  {
     echo fgets($file). "<br />";
  }
  fclose($file);

HTML colspan in CSS

I've created this fiddle:

enter image description here

http://jsfiddle.net/wo40ev18/3/

HTML

<div id="table">
<div class="caption">
    Center Caption
</div>
<div class="group">
      <div class="row">
            <div class="cell">Link 1t</div>
            <div class="cell"></div>
          <div class="cell"></div>
          <div class="cell"></div>
            <div class="cell"></div>
            <div class="cell ">Link 2</div>
      </div>
</div>

CSS

   #table {
    display:table;
}

.group {display: table-row-group; }

.row {
    display:table-row;
    height: 80px;
    line-height: 80px;
}

.cell {
    display:table-cell;
    width:1%;
    text-align: center;
    border:1px solid grey;
    height: 80px
        line-height: 80px;
}

.caption {
    border:1px solid red; caption-side: top; display: table-caption; text-align: center; 
    position: relative;
    top: 80px;
    height: 80px;
      height: 80px;
    line-height: 80px;

}

Quickest way to clear all sheet contents VBA

Try this one:

Sub clear_sht
  Dim sht As Worksheet
  Set sht = Worksheets(GENERATOR_SHT_NAME)
  col_cnt = sht.UsedRange.Columns.count
  If col_cnt = 0 Then
    col_cnt = 1
  End If

  sht.Range(sht.Cells(1, 1), sht.Cells(sht.UsedRange.Rows.count, col_cnt)).Clear
End Sub

SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'

Maybe a bit late, but I found this answer looking over the internet. It could help others with the same problem.

$sudo mysql -u root
[mysql] use mysql;
[mysql] update user set plugin='' where User='root';
[mysql] flush privileges;
[mysql] \q

Now you should be able to log in as root in phpmyadmin.

(Found here.)

How to ignore the certificate check when ssl

Since there is only one global ServicePointManager, setting ServicePointManager.ServerCertificateValidationCallback will yield the result that all subsequent requests will inherit this policy. Since it is a global "setting" it would be prefered to set it in the Application_Start method in Global.asax.

Setting the callback overrides the default behaviour and you can yourself create a custom validation routine.

How to set character limit on the_content() and the_excerpt() in wordpress

For Using the_content() functions (for displaying the main content of the page)

$content = get_the_content();

echo substr($content, 0, 100);

For Using the_excerpt() functions (for displaying the excerpt-short content of the page)

$excerpt= get_the_excerpt();

echo substr($excerpt, 0, 100);

IE8 css selector

This question is ancient but..

Right after the opening body tag..

<!--[if gte IE 8]>
<div id="IE8Body">
<![endif]-->

Right before the closing body tag..

<!--[if gte IE 8]>
</div>
<![endif]-->

CSS..

#IE8Body #nav li ul {}

You could do this for all IE browsers using conditional statements, OR target ALL browsers by encapsulating all content in a div with browser name + version server-side

On select change, get data attribute value

Vanilla Javascript:

this.querySelector(':checked').getAttribute('data-id')

Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in

MySQL socket is located, in general, in /tmp/mysql.sock or /var/mysql/mysql.sock, but probably PHP looks in the wrong place.

  1. Check where is your socket with:

     sudo /usr/libexec/locate.updatedb
    
  2. When the updatedb is terminated:

     locate mysql.sock
    
  3. Then locate your php.ini:

     php -i | grep php.ini
    

    this will output something like:

     Configuration File (php.ini) Path => /opt/local/etc/php54
     Loaded Configuration File => /opt/local/etc/php54/php.ini
    
  4. Edit your php.ini

     sudo vim /opt/local/etc/php54/php.ini
    
  5. Change the lines:

     pdo_mysql.default_socket=/tmp/mysql.sock
     mysql.default_socket=/tmp/mysql.sock
     mysqli.default_socket = /tmp/mysql.sock
    

    where /tmp/mysql.sock is the path to your socket.

  6. Save your modifications and exit ESC + SHIFT: x

  7. Restart Apache

     sudo apachectl stop
     sudo apachectl start
    

TERM environment variable not set

Using a terminal command i.e. "clear", in a script called from cron (no terminal) will trigger this error message. In your particular script, the smbmount command expects a terminal in which case the work-arounds above are appropriate.

How do I get the current absolute URL in Ruby on Rails?

You can either use

request.original_url 

or

"#{request.protocol}#{request.host_with_port}" 

to get the current URL.

JSON Structure for List of Objects

The first one is invalid syntax. You cannot have object properties inside a plain array. The second one is right although it is not strict JSON. It's a relaxed form of JSON wherein quotes in string keys are omitted.

This tutorial by Patrick Hunlock, may help to learn about JSON and this site may help to validate JSON.

IFrame: This content cannot be displayed in a frame

The X-Frame-Options is defined in the Http Header and not in the <head> section of the page you want to use in the iframe.

Accepted values are: DENY, SAMEORIGIN and ALLOW-FROM "url"

Proper way to exit command line program?

Using control-z suspends the process (see the output from stty -a which lists the key stroke under susp). That leaves it running, but in suspended animation (so it is not using any CPU resources). It can be resumed later.

If you want to stop a program permanently, then any of interrupt (often control-c) or quit (often control-\) will stop the process, the latter producing a core dump (unless you've disabled them). You might also use a HUP or TERM signal (or, if really necessary, the KILL signal, but try the other signals first) sent to the process from another terminal; or you could use control-z to suspend the process and then send the death threat from the current terminal, and then bring the (about to die) process back into the foreground (fg).

Note that all key combinations are subject to change via the stty command or equivalents; the defaults may vary from system to system.

Android Google Maps v2 - set zoom level for myLocation

I tried with "mMap.animateCamera( CameraUpdateFactory.zoomTo( 17.0f ) );" but it didn't work for me. So I used this animation for zooming in on start.

LatLng loc = new LatLng(33.8688, 151.2093);
mMap.addMarker(new MarkerOptions().position(loc).title("Sydney"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 18), 5000, null);

How to insert an item into an array at a specific index (JavaScript)?

You can implement the Array.insert method by doing this:

Array.prototype.insert = function ( index, item ) {
    this.splice( index, 0, item );
};

Then you can use it like:

var arr = [ 'A', 'B', 'D', 'E' ];
arr.insert(2, 'C');

// => arr == [ 'A', 'B', 'C', 'D', 'E' ]

What is the difference between 127.0.0.1 and localhost

Wikipedia sums this up well:

On modern computer systems, localhost as a hostname translates to an IPv4 address in the 127.0.0.0/8 (loopback) net block, usually 127.0.0.1, or ::1 in IPv6.

The only difference is that it would be looking up in the DNS for the system what localhost resolves to. This lookup is really, really quick. For instance, to get to stackoverflow.com you typed in that to the address bar (or used a bookmarklet that pointed here). Either way, you got here through a hostname. localhost provides a similar functionality.

Grep to find item in Perl array

I could happen that if your array contains the string "hello", and if you are searching for "he", grep returns true, although, "he" may not be an array element.

Perhaps,

if (grep(/^$match$/, @array)) more apt.

What is the difference between Eclipse for Java (EE) Developers and Eclipse Classic?

If you want to build Java EE applications, it's best to use Eclipse IDE for Java EE. It has editors from HTML to JSP/JSF, Javascript. It's rich for webapps development, and provide plugins and tools to develop Java EE applications easily (all bundled).

Eclipse Classic is basically the full featured Eclipse without the Java EE part.

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Even if your JSON is ok it could be DB charset (UTF8) problem. If your DB's charset/collation are UTF8 but PDO isn't set up properly (charset/workaround missing) some à / è / ò / ì / etc. in your DB could break your JSON encoding (still encoded but causing parsing issues). Check your connection string, it should be similar to one of these:

$pdo = new PDO('mysql:host=hostname;dbname=DBname;**charset=utf8**','username','password'); // PHP >= 5.3.6

$pdo = new PDO('mysql:host=hostname;dbname=DBname','username','password',**array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")**); // older versions

P.S. Outdated but still could be helpful for people who're stuck with "unexpected character".

Remove a data connection from an Excel 2010 spreadsheet in compatibility mode

I had the same problem. Get the warning. Went to Data connections and deleted connection. Save, close reopen. Still get the warning. I use a xp/vista menu plugin for classic menus. I found under data, get external data, properties, uncheck the save query definition. Save close and reopen. That seemed to get rid of the warning. Just removing the connection does not work. You have to get rid of the query.

Changing API level Android Studio

In android studio you can easily press:

  1. Ctrl + Shift + Alt + S.
  2. If you have a newer version of android studio, then press on app first. Then, continue with step three as follows.
  3. A window will open with a bunch of options
  4. Go to Flavors and that's actually all you need

You can also change the versionCode of your app there.

How to get Python requests to trust a self signed SSL certificate?

With the verify parameter you can provide a custom certificate authority bundle

requests.get(url, verify=path_to_bundle_file)

From the docs:

You can pass verify the path to a CA_BUNDLE file with certificates of trusted CAs. This list of trusted CAs can also be specified through the REQUESTS_CA_BUNDLE environment variable.

What does this mean? "Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM"

In your example

return $cnf::getConfig($key)

Probably should be:

return $cnf->getConfig($key)

And make getConfig not static

How to override toString() properly in Java?

Always have easy way: Right Click > Generate > toString() > select template that you want. enter image description here

How to generate a random string of 20 characters

I'd use this approach:

String randomString(final int length) {
    Random r = new Random(); // perhaps make it a class variable so you don't make a new one every time
    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < length; i++) {
        char c = (char)(r.nextInt((int)(Character.MAX_VALUE)));
        sb.append(c);
    }
    return sb.toString();
}

If you want a byte[] you can do this:

byte[] randomByteString(final int length) {
    Random r = new Random();
    byte[] result = new byte[length];
    for(int i = 0; i < length; i++) {
        result[i] = r.nextByte();
    }
    return result;
}

Or you could do this

byte[] randomByteString(final int length) {
    Random r = new Random();
    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < length; i++) {
        char c = (char)(r.nextInt((int)(Character.MAX_VALUE)));
        sb.append(c);
    }
    return sb.toString().getBytes();
}

Postgres: check if array field contains value?

With ANY operator you can search for only one value.

For example,

select * from mytable where 'Book' = ANY(pub_types);

If you want to search multiple values, you can use @> operator.

For example,

select * from mytable where pub_types @> '{"Journal", "Book"}';

You can specify in which ever order you like.

How to store a large (10 digits) integer?

A primitive long or its java.lang.Long wrapper can also store ten digits.

CSS selectors ul li a {...} vs ul > li > a {...}

1) for example HTML code:

<ul>
    <li>
        <a href="#">firstlink</a>
        <span><a href="#">second link&lt;/a>
    </li>
</ul>

and css rules:

1) ul li a {color:red;} 
2) ul > li > a {color:blue;}

">" - symbol mean that that will be searching only child selector (parentTag > childTag)

so first css rule will apply to all links (first and second) and second rule will apply anly to first link

2) As for efficiency - I think second will be more fast - as in case with JavaScript selectors. This rule read from right to left, this mean that when rule will parse by browser, it get all links on page: - in first case it will find all parent elements for each link on page and filter all links where exist parent tags "ul" and "li" - in second case it will check only parent node of link if it is "li" tag then -> check if parent tag of "li" is "ul"

some thing like this. Hope I describe all properly for you

"Unable to locate tools.jar" when running ant

There are two directories that looks like JDK.

  C:\Program Files\Java\jdk1.7.0_02
  C:\Program Files (x86)\Java\jdk1.7.0_02\

This may be due to both 64 bit and 32 bit JDK installed? What ever may be the case, the java.exe seen by ant.bat should from the JDK. If the JRE's java.exe comes first in the path, that will be used to guess the JDK location.

Put 'C:\Program Files (x86)\Java\jdk1.7.0_02\bin' or 'C:\Program Files\Java\jdk1.7.0_02' as the first argument in the path.

Further steps:

You can take output of ant -diagnostics and look for interesting keys. (assuming Sun/Oracle JDK).

 java.class.path 
 java.library.path
 sun.boot.library.path

(in my case tools.jar appears in java.class.path)

How do I get logs from all pods of a Kubernetes replication controller?

I use this command.

kubectl -n <namespace> logs -f deployment/<app-name> --all-containers=true --since=10m

Connect Android to WiFi Enterprise network EAP(PEAP)

Finally, I've defeated my CiSCO EAP-FAST corporate wifi network, and all our Android devices are now able to connect to it.

The walk-around I've performed in order to gain access to this kind of networks from an Android device are easiest than you can imagine.

There's a Wifi Config Editor in the Google Play Store you can use to "activate" the secondary CISCO Protocols when you are setting up a EAP wifi connection.

Its name is Wifi Config Advanced Editor.

  • First, you have to setup your wireless network manually as close as you can to your "official" corporate wifi parameters.

  • Save it.

  • Go to the WCE and edit the parameters of the network you have created in the previous step.

  • There are 3 or 4 series of settings you should activate in order to force the Android device to use them as a way to connect (the main site I think you want to visit is Enterprise Configuration, but don't forget to check all the parameters to change them if needed.
    As a suggestion, even if you have a WPA2 EAP-FAST Cipher, try LEAP in your setup. It worked for me as a charm.

  • When you finished to edit the config, go to the main Android wifi controller, and force to connect to this network.

  • Do not Edit the network again with the Android wifi interface.

I have tested it on Samsung Galaxy 1 and 2, Note mobile devices, and on a Lenovo Thinkpad Tablet.

Prevent the keyboard from displaying on activity start

declare this code( android:windowSoftInputMode="stateAlwaysHidden") in manifest inside your activity tag .

like this :

<activity android:name=".MainActivity"
  android:windowSoftInputMode="stateAlwaysHidden">

Android studio Gradle build speed up

I was able to reduce my gradle build from 43 seconds down to 25 seconds on my old core2duo laptop (running linux mint) by adding the following to the gradle.properties file in android studio

org.gradle.parallel=true
org.gradle.daemon=true

source on why the daemon setting makes builds faster: https://www.timroes.de/2013/09/12/speed-up-gradle/

Change class on mouseover in directive

In general I fully agree with Jason's use of css selector, but in some cases you may not want to change the css, e.g. when using a 3rd party css-template, and rather prefer to add/remove a class on the element.

The following sample shows a simple way of adding/removing a class on ng-mouseenter/mouseleave:

<div ng-app>
  <div 
    class="italic" 
    ng-class="{red: hover}"
    ng-init="hover = false"
    ng-mouseenter="hover = true"
    ng-mouseleave="hover = false">
      Test 1 2 3.
  </div>
</div>

with some styling:

.red {
  background-color: red;
}

.italic {
  font-style: italic;
  color: black;
}

See running example here: jsfiddle sample

Styling on hovering is a view concern. Although the solution above sets a "hover" property in the current scope, the controller does not need to be concerned about this.

Logical operators ("and", "or") in DOS batch

Only the OR part is tricky, but with a general boolean expression containing NOT OR AND the only nice solution is this:

REM if A == B OR C == C then yes

(call :strequ A B || call :strequ C C) && echo yes
exit /b

:strequ
if "%1" == "%2" exit /b 0
exit /b 1

Bootstrap Collapse not Collapsing

Maybe your mobile view port is not set. Add following meta tag inside <head></head> to allow menu to work on mobiles.

<meta name=viewport content="width=device-width, initial-scale=1">

JavaScript: Check if mouse button down?

You need to handle the MouseDown and MouseUp and set some flag or something to track it "later down the road"... :(

Get installed applications in a system

While the accepted solution works, it is not complete. By far.

If you want to get all the keys, you need to take into consideration 2 more things:

x86 & x64 applications do not have access to the same registry. Basically x86 cannot normally access x64 registry. And some applications only register to the x64 registry.

and

some applications actually install into the CurrentUser registry instead of the LocalMachine

With that in mind, I managed to get ALL installed applications using the following code, WITHOUT using WMI

Here is the code:

List<string> installs = new List<string>();
List<string> keys = new List<string>() {
  @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
  @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
};

// The RegistryView.Registry64 forces the application to open the registry as x64 even if the application is compiled as x86 
FindInstalls(RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64), keys, installs);
FindInstalls(RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64), keys, installs);

installs = installs.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList();
installs.Sort(); // The list of ALL installed applications



private void FindInstalls(RegistryKey regKey, List<string> keys, List<string> installed)
{
  foreach (string key in keys)
  {
    using (RegistryKey rk = regKey.OpenSubKey(key))
    {
      if (rk == null)
      {
        continue;
      }
      foreach (string skName in rk.GetSubKeyNames())
      {
        using (RegistryKey sk = rk.OpenSubKey(skName))
        {
          try
          {
            installed.Add(Convert.ToString(sk.GetValue("DisplayName")));
          }
          catch (Exception ex)
          { }
        }
      }
    }
  }
}

IF EXIST C:\directory\ goto a else goto b problems windows XP batch files

@echo off

:START
rmdir temporary
cls
IF EXIST "temporary\." (echo The temporary directory exists) else echo The temporary directory doesn't exist
echo.
dir temporary /A:D
pause

echo.
echo.
echo Note the directory is not found
echo.
echo Press any key to make a temporary directory, cls, and test again
pause

Mkdir temporary
cls
IF EXIST "temporary\." (echo The temporary directory exists) else echo The temporary directory doesn't exist
echo.
dir temporary /A:D
pause
echo.
echo press any key to goto START and remove temporary directory 
pause 

goto START

Change width of select tag in Twitter Bootstrap

You can use something like this

<div class="row">
     <div class="col-xs-2">
       <select id="info_type" class="form-control">
             <option>College</option>
             <option>Exam</option>
       </select>
     </div>
</div>

http://getbootstrap.com/css/#column-sizing

Django gives Bad Request (400) when DEBUG = False

in the settings.py of your project, check line 28, where is the Allows Host

settings.py


ALLOWED_HOSTS = ['IP', 'servidor', ]

you must put the IP and the server you use, level local or web settings.py

ALLOWED_HOSTS = ['127.0.0.1', 'localhost', 'www.ejemplo.com']

or

ALLOWED_HOSTS = ['*']

How to make execution pause, sleep, wait for X seconds in R?

Sys.sleep() will not work if the CPU usage is very high; as in other critical high priority processes are running (in parallel).

This code worked for me. Here I am printing 1 to 1000 at a 2.5 second interval.

for (i in 1:1000)
{
  print(i)
  date_time<-Sys.time()
  while((as.numeric(Sys.time()) - as.numeric(date_time))<2.5){} #dummy while loop
}

js 'types' can only be used in a .ts file - Visual Studio Code using @ts-check

You must use a .ts file - e.g. test.ts to get Typescript validation, intellisense typing of vars, return types, as well as "typed" error checking (e.g. passing a string to a method that expects an number param will error out).

It will be transpiled into (standard) .js via tsc.


Update (11/2018):

Clarification needed based on down-votes, very helpful comments and other answers.

types

  • Yes, you can do type checking in VS Code in .js files with @ts-check - as shown in the animation

  • What I originally was referring to for Typescript types is something like this in .ts which isn't quite the same thing:

    hello-world.ts

    function hello(str: string): string {
      return 1;
    }
    
    function foo(str:string):void{
       console.log(str);
    }
    

    This will not compile. Error: Type "1" is not assignable to String

  • if you tried this syntax in a Javascript hello-world.js file:

    //@ts-check
    
    function hello(str: string): string {
      return 1;
    }
    
    function foo(str:string):void{
       console.log(str);
    }
    

    The error message referenced by OP is shown: [js] 'types' can only be used in a .ts file

If there's something I missed that covers this as well as the OP's context, please add. Let's all learn.

ReferenceError: Invalid left-hand side in assignment

The same happened for me with eslint module. EsLinter throw Parsing error: Invalid left-hand side in assignment expression for await in second if statement.

if (condition_one) {
  let result = await myFunction()
}

if (condition_two) {
  let result = await myFunction() // eslint parsing error
}

As strange as it sounds what fixed this error was to add ; semicolon at the end of line where await occurred.

if (condition_one) {
  let result = await myFunction();
}

if (condition_two) {
  let result = await myFunction();
}

Easiest way to open a download window without navigating away from the page

I've been looking for a good way to use javascript to initiate the download of a file, just as this question suggests. However these answers not been helpful. I then did some xbrowser testing and have found that an iframe works best on all modern browsers IE>8.

downloadUrl = "http://example.com/download/file.zip";
var downloadFrame = document.createElement("iframe"); 
downloadFrame.setAttribute('src',downloadUrl);
downloadFrame.setAttribute('class',"screenReaderText"); 
document.body.appendChild(downloadFrame); 

class="screenReaderText" is my class to style content that is present but not viewable.

css:

.screenReaderText { 
  border: 0; 
  clip: rect(0 0 0 0); 
  height: 1px; 
  margin: -1px; 
  overflow: hidden; 
  padding: 0; 
  position: absolute; 
  width: 1px; 
}

same as .visuallyHidden in html5boilerplate

I prefer this to the javascript window.open method because if the link is broken the iframe method simply doesn't do anything as opposed to redirecting to a blank page saying the file could not be opened.

window.open(downloadUrl, 'download_window', 'toolbar=0,location=no,directories=0,status=0,scrollbars=0,resizeable=0,width=1,height=1,top=0,left=0');
window.focus();